hexsha
stringlengths 40
40
| size
int64 6
14.9M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 6
260
| max_stars_repo_name
stringlengths 6
119
| max_stars_repo_head_hexsha
stringlengths 40
41
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 6
260
| max_issues_repo_name
stringlengths 6
119
| max_issues_repo_head_hexsha
stringlengths 40
41
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 6
260
| max_forks_repo_name
stringlengths 6
119
| max_forks_repo_head_hexsha
stringlengths 40
41
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2
1.04M
| max_line_length
int64 2
11.2M
| alphanum_fraction
float64 0
1
| cells
sequence | cell_types
sequence | cell_type_groups
sequence |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e71f93404c20cc3e8ad39f3d0fa89f27e53003dd | 348,031 | ipynb | Jupyter Notebook | course_notes/.ipynb_checkpoints/AMATH582-Lec16-checkpoint.ipynb | raph651/Amath-582-Data-Analysis | c1d72d897b7611652c7fe1f71c5439062b8bdf9e | [
"MIT"
] | null | null | null | course_notes/.ipynb_checkpoints/AMATH582-Lec16-checkpoint.ipynb | raph651/Amath-582-Data-Analysis | c1d72d897b7611652c7fe1f71c5439062b8bdf9e | [
"MIT"
] | null | null | null | course_notes/.ipynb_checkpoints/AMATH582-Lec16-checkpoint.ipynb | raph651/Amath-582-Data-Analysis | c1d72d897b7611652c7fe1f71c5439062b8bdf9e | [
"MIT"
] | null | null | null | 502.209235 | 84,724 | 0.937322 | [
[
[
"Demo notebook for Lecture 16. Kernel ridge regression on housing market dataset. ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd \n\nfrom google.colab import drive\n\n# the following command loads up your google drive. It will promp you to give Colab access to your Gdrive\ndrive.mount('/content/drive')",
"Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n"
],
[
"datapath = '/content/drive/MyDrive/Courses/AMATH482582-WIN2022/Notebooks/HousingData/Realestateval.xlsx'\n\ndata = pd.read_excel(datapath)",
"_____no_output_____"
],
[
"print(data)\n\n# convert the data to numpy array\nd = np.array(data)\n\n# separate the data into features X and output Y\n\nX = d[:, 1:7]\nY = d[:,7]\n\nprint('X:', X)\nprint('Y:', Y)",
" No X1 transaction date ... X6 longitude Y house price of unit area\n0 1 2012.916667 ... 121.54024 37.9\n1 2 2012.916667 ... 121.53951 42.2\n2 3 2013.583333 ... 121.54391 47.3\n3 4 2013.500000 ... 121.54391 54.8\n4 5 2012.833333 ... 121.54245 43.1\n.. ... ... ... ... ...\n409 410 2013.000000 ... 121.50381 15.4\n410 411 2012.666667 ... 121.54310 50.0\n411 412 2013.250000 ... 121.53986 40.6\n412 413 2013.000000 ... 121.54067 52.5\n413 414 2013.500000 ... 121.54310 63.9\n\n[414 rows x 8 columns]\nX: [[2012.9166667 32. 84.87882 10. 24.98298\n 121.54024 ]\n [2012.9166667 19.5 306.5947 9. 24.98034\n 121.53951 ]\n [2013.5833333 13.3 561.9845 5. 24.98746\n 121.54391 ]\n ...\n [2013.25 18.8 390.9696 7. 24.97923\n 121.53986 ]\n [2013. 8.1 104.8101 5. 24.96674\n 121.54067 ]\n [2013.5 6.5 90.45606 9. 24.97433\n 121.5431 ]]\nY: [ 37.9 42.2 47.3 54.8 43.1 32.1 40.3 46.7 18.8 22.1 41.4 58.1\n 39.3 23.8 34.3 50.5 70.1 37.4 42.3 47.7 29.3 51.6 24.6 47.9\n 38.8 27. 56.2 33.6 47. 57.1 22.1 25. 34.2 49.3 55.1 27.3\n 22.9 25.3 47.7 46.2 15.9 18.2 34.7 34.1 53.9 38.3 42. 61.5\n 13.4 13.2 44.2 20.7 27. 38.9 51.7 13.7 41.9 53.5 22.6 42.4\n 21.3 63.2 27.7 55. 25.3 44.3 50.7 56.8 36.2 42. 59. 40.8\n 36.3 20. 54.4 29.5 36.8 25.6 29.8 26.5 40.3 36.8 48.1 17.7\n 43.7 50.8 27. 18.3 48. 25.3 45.4 43.2 21.8 16.1 41. 51.8\n 59.5 34.6 51. 62.2 38.2 32.9 54.4 45.7 30.5 71. 47.1 26.6\n 34.1 28.4 51.6 39.4 23.1 7.6 53.3 46.4 12.2 13. 30.6 59.6\n 31.3 48. 32.5 45.5 57.4 48.6 62.9 55. 60.7 41. 37.5 30.7\n 37.5 39.5 42.2 20.8 46.8 47.4 43.5 42.5 51.4 28.9 37.5 40.1\n 28.4 45.5 52.2 43.2 45.1 39.7 48.5 44.7 28.9 40.9 20.7 15.6\n 18.3 35.6 39.4 37.4 57.8 39.6 11.6 55.5 55.2 30.6 73.6 43.4\n 37.4 23.5 14.4 58.8 58.1 35.1 45.2 36.5 19.2 42. 36.7 42.6\n 15.5 55.9 23.6 18.8 21.8 21.5 25.7 22. 44.3 20.5 42.3 37.8\n 42.7 49.3 29.3 34.6 36.6 48.2 39.1 31.6 25.5 45.9 31.5 46.1\n 26.6 21.4 44. 34.2 26.2 40.9 52.2 43.5 31.1 58. 20.9 48.1\n 39.7 40.8 43.8 40.2 78.3 38.5 48.5 42.3 46. 49. 12.8 40.2\n 46.6 19. 33.4 14.7 17.4 32.4 23.9 39.3 61.9 39. 40.6 29.7\n 28.8 41.4 33.4 48.2 21.7 40.8 40.6 23.1 22.3 15. 30. 13.8\n 52.7 25.9 51.8 17.4 26.5 43.9 63.3 28.8 30.7 24.4 53. 31.7\n 40.6 38.1 23.7 41.1 40.1 23. 117.5 26.5 40.5 29.3 41. 49.7\n 34. 27.7 44. 31.1 45.4 44.8 25.6 23.5 34.4 55.3 56.3 32.9\n 51. 44.5 37. 54.4 24.5 42.5 38.1 21.8 34.1 28.5 16.7 46.1\n 36.9 35.7 23.2 38.4 29.4 55. 50.2 24.7 53. 19.1 24.7 42.2\n 78. 42.8 41.6 27.3 42. 37.5 49.8 26.9 18.6 37.7 33.1 42.5\n 31.3 38.1 62.1 36.7 23.6 19.2 12.8 15.6 39.6 38.4 22.8 36.5\n 35.6 30.9 36.3 50.4 42.9 37. 53.5 46.6 41.2 37.9 30.8 11.2\n 53.7 47. 42.3 28.6 25.7 31.3 30.1 60.7 45.3 44.9 45.1 24.7\n 47.1 63.3 40. 48. 33.1 29.5 24.8 20.9 43.1 22.8 42.1 51.7\n 41.5 52.2 49.5 23.8 30.5 56.8 37.4 69.7 53.3 47.3 29.3 40.3\n 12.9 46.6 55.3 25.6 27.3 67.7 38.6 31.3 35.3 40.3 24.7 42.5\n 31.9 32.2 23. 37.3 35.5 27.7 28.5 39.7 41.2 37.2 40.5 22.3\n 28.1 15.4 50. 40.6 52.5 63.9]\n"
],
[
"# generate some plots to visualize the data set \n\nfig, ax = plt.subplots(2,3, figsize=(24,12))\n\nfor j in range(2):\n for i in range(3):\n\n ax[j][i].scatter( X[:, i+ j*3], Y )\n ax[j][i].set_xlabel('x_'+str(i + j*3), fontsize=20)",
"_____no_output_____"
]
],
[
[
"Clearly there are some trends in the data. For example $x_3$ (numer of convenience stores nearby) seems to have a direct effect on the price. We now use Scikitlearn's kernel regression algorithm to fit a model to this data set. ",
"_____no_output_____"
]
],
[
[
"# First we use sklearn to split our data set into training and test sets \n\nimport sklearn as skl\nimport sklearn.model_selection\n\n# test_size is a number between 0.0 and 1.0, the ratio of test set to entire data set\nX_train, X_test, Y_train, Y_test = skl.model_selection.train_test_split(X, Y, test_size=0.15, random_state=10 )\n\n# plot the training and test sets \n\nfig, ax = plt.subplots(2,3, figsize=(24,12))\n\nfor j in range(2):\n for i in range(3):\n\n ax[j][i].scatter( X_train[:, i+ j*3], Y_train, color='k', label='Train' )\n ax[j][i].scatter( X_test[:, i+ j*3], Y_test, color='r', label='Test')\n ax[j][i].set_xlabel('x_'+str(i + j*3), fontsize=20)\n\nplt.legend(fontsize=20)",
"_____no_output_____"
],
[
"import numpy.matlib\n\n# Next we normalize and center the training set\n\nX_train_N = X_train.shape[0]\n\nX_train_mean = np.mean(X_train, axis=0)\nX_train_std = np.std(X_train, axis=0)\n\nX_train_normal = (X_train - np.matlib.repmat(X_train_mean, X_train_N, 1))/np.matlib.repmat(X_train_std, X_train_N, 1)\n\nY_train_N = Y_train.shape[0]\n\nY_train_mean = np.mean(Y_train, axis=0)\nY_train_std = np.std(Y_train, axis=0)\n\nY_train_normal = (Y_train - Y_train_mean)/Y_train_std\n\nprint(X_train_normal.shape)\nprint(Y_train_normal.shape)\n\nfig, ax = plt.subplots(2,3, figsize=(24,12))\n\nfor j in range(2):\n for i in range(3):\n\n ax[j][i].scatter( X_train_normal[:, i+ j*3], Y_train_normal )\n ax[j][i].set_xlabel('x_'+str(i + j*3), fontsize=20)\n\n# while we're here we also normalize and center the test set. \n# NOTE: the shift and scaling here are those computed on the training set \nX_test_N = X_test.shape[0]\n\nX_test_normal = (X_test - np.matlib.repmat(X_train_mean, X_test_N, 1))/np.matlib.repmat(X_train_std, X_test_N, 1)\nY_test_normal = (Y_test - Y_train_mean)/Y_train_std",
"(351, 6)\n(351,)\n"
],
[
"# now we can use sklearn's kernel ridgeregression function to fit our model. We will first do this with a \n# fixed kernel length scale then use CV to choose the length scale as well. Test error will be reported on the test set\n\nimport sklearn.kernel_ridge\n\n# see https://scikit-learn.org/stable/modules/metrics.html#metrics for possible choices of kernels\nsigma = 0.5\n\n\n\nKRR = skl.kernel_ridge.KernelRidge(kernel='rbf', alpha = 0.9, gamma=1/(2*sigma**2))\n\nKRR.fit(X_train_normal, Y_train_normal)\n\n# use our fitted model to predict the Y values on the test set \nY_pred_normal = KRR.predict(X_test_normal)\n\n# plot the predicted values of Y against the test set\n\nfig, ax = plt.subplots(2,3, figsize=(24,12))\n\nfor j in range(2):\n for i in range(3):\n\n ax[j][i].scatter( X_test_normal[:, i+ j*3], Y_test_normal, color='r', label='Test' )\n ax[j][i].scatter( X_test_normal[:, i+ j*3], Y_pred_normal, color='b', label='Prediction' )\n ax[j][i].set_xlabel('x_'+str(i + j*3), fontsize=20)\n\nplt.legend(fontsize=20)\n\n",
"_____no_output_____"
]
],
[
[
"You can play around with the above code to see the profound impact of the $\\gamma$ and $\\alpha$ parameters on the performance of the model. To address this we will now employ CV. Note that we have two parameters to optimize over so this is not going to be cheap. But the problem is small enough that we can do it.",
"_____no_output_____"
]
],
[
[
"# range of values of sigma to try \n\n\nK_sgm = 10\nK_lmbd = 10\n\nsgm = np.linspace(-5, 0, K_sgm)\nlmbd = np.linspace(-5, 0, K_lmbd)\n\nscores = np.zeros((K_sgm, K_lmbd))\nscores_std = np.zeros((K_sgm, K_lmbd))\n\nKRR_CV = skl.kernel_ridge.KernelRidge(kernel='rbf')\n\nfor i in range(K_sgm):\n\n KRR_CV.gamma = 1/(2*(2**sgm[i])**2)\n\n for j in range(K_lmbd): \n\n KRR_CV.alpha = (2**lmbd[j])\n this_score = skl.model_selection.cross_val_score(KRR_CV, X_train_normal, Y_train_normal)\n\n scores[i,j] = np.abs(np.mean(this_score))\n scores_std[i,j] = np.abs(np.std(this_score))\n\n\nprint(scores)",
"[[0.07536454 0.07538201 0.0753445 0.07516939 0.07469763 0.0736543\n 0.071625 0.06809524 0.06260305 0.0549892 ]\n [0.07660564 0.07664237 0.07663043 0.07648759 0.0760534 0.07504816\n 0.07304783 0.06952318 0.06399569 0.0562946 ]\n [0.08373957 0.08370871 0.08359892 0.08331599 0.08268436 0.08140682\n 0.0790418 0.07504768 0.06894589 0.06058481]\n [0.10130992 0.10114337 0.10082872 0.10024439 0.09917963 0.09729506\n 0.09410483 0.08903196 0.0815886 0.07165744]\n [0.16271177 0.1619552 0.16083686 0.15913982 0.15652932 0.15251854\n 0.14646968 0.13768783 0.12565616 0.1103697 ]\n [0.26107477 0.26010801 0.25871487 0.25659145 0.25325193 0.24797395\n 0.23978722 0.22758636 0.21044768 0.18811911]\n [0.34908633 0.35103258 0.35331378 0.35569947 0.35762577 0.35805011\n 0.35536438 0.34750034 0.33235354 0.30851469]\n [0.39854576 0.41017913 0.42375536 0.43863417 0.45357761 0.4667803\n 0.47603011 0.47892585 0.47312035 0.45665681]\n [0.38475339 0.41754505 0.45066582 0.48215245 0.51022562 0.53351642\n 0.55102665 0.56192448 0.56532465 0.56017305]\n [0.44902009 0.49222438 0.52891248 0.55918883 0.58341875 0.60207346\n 0.61556041 0.62407753 0.62753048 0.62551001]]\n"
],
[
"\nsv, lv = np.meshgrid(sgm, lmbd)\n\n#fig = plt.figure(figsize = (10, 7))\n#ax = plt.axes(projection =\"3d\")\n\n#ax.scatter(sv, lv, np.log(scores))\n#ax.set_xlabel('$\\sigma$', fontsize=20)\n#ax.set_ylabel('$\\lambda$', fontsize=20)\n\nfig, ax = plt.subplots(1,2, figsize=(20,10))\n\ncm0 = ax[0].contourf(sv, lv, np.log2(scores))\nax[0].set_xlabel('$\\sigma$')\nax[0].set_ylabel('$\\lambda$')\nax[0].set_title('Score')\nfig.colorbar(cm0, ax=ax[0])\n\n\ncm1 = ax[1].contourf(sv, lv, np.log2(scores_std))\nax[1].set_xlabel('$\\sigma$')\nax[1].set_ylabel('$\\lambda$')\nax[1].set_title('Score std')\nfig.colorbar(cm1, ax=ax[1])\n\n\nfig.tight_layout()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e71f95c0be53982cc484e8a2358ba49045fa8bc7 | 11,167 | ipynb | Jupyter Notebook | boards/ZCU104/notebooks/prio_linux/gpio_linux.ipynb | byuccl/PYNQ-PRIO | 1d554a31131f93fd950f02e0a670475ef850771c | [
"BSD-3-Clause"
] | 12 | 2019-02-20T23:30:47.000Z | 2022-03-05T10:28:39.000Z | boards/ZCU104/notebooks/prio_linux/gpio_linux.ipynb | byuccl/PYNQ-PRIO | 1d554a31131f93fd950f02e0a670475ef850771c | [
"BSD-3-Clause"
] | 1 | 2020-01-16T06:27:28.000Z | 2020-03-27T06:34:14.000Z | boards/ZCU104/notebooks/prio_linux/gpio_linux.ipynb | byuccl/PYNQ-PRIO | 1d554a31131f93fd950f02e0a670475ef850771c | [
"BSD-3-Clause"
] | 6 | 2019-03-04T14:28:08.000Z | 2022-03-30T21:02:47.000Z | 29.46438 | 281 | 0.512492 | [
[
[
"# PRIO Linux: GPIO Demo\nThis demo illastrates how to use device tree overlays to interact with partially reconfigurable designs. \n",
"_____no_output_____"
],
[
"### Step One: \nDownload the static bitstream",
"_____no_output_____"
]
],
[
[
"from prio_linux import PrIoOverlay\n\nFULL_BITSTREAM_PATH = \"/usr/local/lib/python3.6/dist-packages/prio_linux/\"\nPARTIAL_BITSTREAM_PATH = \"/usr/local/lib/python3.6/dist-packages/prio_linux/partial/\"\nDTBO_PATH = \"/usr/local/lib/python3.6/dist-packages/prio_linux/dtbo/\"\n\noverlay = PrIoOverlay(FULL_BITSTREAM_PATH + \"prio_linux.bit\")",
"_____no_output_____"
]
],
[
[
"### Step Two:\nDownload the partial bitstreams and insert the dtbo files",
"_____no_output_____"
]
],
[
[
"overlay.pr_download(\"pr_0\", PARTIAL_BITSTREAM_PATH + \"pr_0_gpio.bit\", DTBO_PATH + \"pr_0_gpio.dtbo\")",
"_____no_output_____"
]
],
[
[
"### Step Three:\n\nDefine a convenient wrapper class that wraps around Xilinx's GPIO wrapper class (reminds me of a certain Christopher Nolan movie, except instead of dreams, it's GPIO wrappers) and groups pins into a single GPIO object.",
"_____no_output_____"
]
],
[
[
"from pynq import GPIO \n\n# returns the bit of the value at the position \ndef getBit(value, position):\n return (value & (0x01 << position)) >> position\n\n# puts bit in value at postion\ndef putBit(value, bit, position):\n return (value | (int(bit) << position))\n\n \nclass BYU_GPIO:\n \"\"\"Class to group GPIO pins together into a user-friendly interface.\n Attributes\n ----------\n starting_index : int\n The index of the first GPIO pin\n num_of_pins: int\n number of pins, starting from the gpio pin at the starting index, that you \n would like to group together.\n direction : int\n Input/output direction of the GPIOs. the LSB corresponding to the first index.\n 0 signifies output, 1 siginifies input.\n \n \"\"\"\n \n ALL_INPUTS = 0xFFFF\n ALL_OUTPUTS = 0x0000\n \n def __init__(self, name, direction):\n name = \"/amba/\" + name\n self.pins = []\n for x in range(GPIO.get_gpio_npins(name)):\n if (getBit(direction, x)):\n direction_str = 'in'\n else:\n direction_str = 'out'\n self.pins.append(GPIO(GPIO.get_gpio_pin(x, name), direction_str))\n \n def setDirection(self, direction):\n for x in range(0, len(self.pins)):\n if (getBit(direction, x)):\n direction_str = 'in'\n else:\n direction_str = 'out' \n with open(self.pins[x]._impl.path + 'direction', 'w') as f:\n f.write(direction_str)\n self.pins[x]._impl.direction = direction_str\n \n \n def getDirection(self):\n direction = 0\n for x in range(0, len(self.pins)):\n if (self.pins[x].direction == \"in\"):\n direction = putBit(direction, 1, x)\n return direction \n \n def write(self, value):\n for x in range(0, len(self.pins)):\n if(self.pins[x].direction == \"out\"):\n self.pins[x].write(getBit(value, x))\n else:\n pass\n# print(\"WARNING (GPIO_PIN\" + str(self.pins[x].index) + \"): Cannot write GPIO input.\")\n \n def read(self):\n value = 0\n for x in range(0, len(self.pins)):\n if(self.pins[x].direction == \"in\"):\n value = putBit(value, self.pins[x].read(), x)\n else:\n pass\n# print(\"WARNING (GPIO_PIN\" + str(self.pins[x].index) + \"): Cannot read GPIO output.\")\n return value\n \n def release(self):\n for pin in(self.pins):\n pin.release()",
"_____no_output_____"
]
],
[
[
"### Step Four:\n\nInitialize the upper pins of **`PMOD0`** for the gpio hardware inside pr_region_0.",
"_____no_output_____"
]
],
[
[
"gpio0 = BYU_GPIO(\"pr_0_gpio\", BYU_GPIO.ALL_OUTPUTS)",
"_____no_output_____"
]
],
[
[
"### Step Five:\n\nRun the demos!",
"_____no_output_____"
],
[
"## Demo: Constant Output\nOutputs a constant pattern to the **`pr_0`** pins.\n\n** Hardware Setup:** For this demo, we suggest using at least one LED to check the output of every pin. These LEDs should be hooked up to the top row of **`PMOD 0`**. Every other pin should be high.\n\n<img src=\"images/gpio_hw_setup1.JPG\" align=\"center\"/>\n",
"_____no_output_____"
]
],
[
[
"# Desired pattern of gpio output.\nLED_PATTERN = 0b1010\n\n#sets the value of all the pins in region 0 so everyother pin is high.\ngpio0.write(LED_PATTERN)",
"_____no_output_____"
]
],
[
[
"## Demo: Binary Counter\nThis demo will output the count, in binary, of a counter to the pins of **`pr_0`**.\n\n** Hardware Setup:** This Demo should use the same LED setup as the **`Constant Output`** Demo",
"_____no_output_____"
]
],
[
[
"import time\n\nOUTPUTS_OFF = 0b0\n\n# Sets the direction of all pins in region 0 to output.\ngpio0.setDirection(BYU_GPIO.ALL_OUTPUTS)\n\n# Counts from 0 to 15 in binary\nfor output in range(0, 16):\n \n gpio0.write(output)\n \n #pauses for a half second\n time.sleep(0.5)\n \n#sets the value of all the pins in region 0 so every pin is low\ngpio0.write(OUTPUTS_OFF)",
"_____no_output_____"
]
],
[
[
"## Demo: Blink Test\nThe following demonstrates the Input and Output functionalities of GPIO interface by toggling the value on top-right pin on **`PMOD 1`**, and reading that value from the bottom-right pin on **`PMOD 1`**. This value will then be echoed to the top-right pin on **`PMOD 0`**.\n\n** Hardware Setup:** Keep the LEDs on the top row of **`PMOD 0`**. Connect a wire from the top-right pin on **`PMOD 1`** to the bottom-right pin on **`PMOD 1`**.\n\n\n\n<img src=\"images/gpio_hw_setup2.JPG\" align=\"center\"/>\n\n\nThe LED connected to the top-right pin on PMOD 0 will indicate the current value being read from bottom-right pin on PMOD 1. This LED should toggle on and off.",
"_____no_output_____"
],
[
"### Setup additional reconfigurable regions\nSince this demo requires two additional PR regions, we must setup them up with the following code.",
"_____no_output_____"
]
],
[
[
"overlay.pr_download(\"pr_1\", PARTIAL_BITSTREAM_PATH + \"pr_1_gpio.bit\", DTBO_PATH + \"pr_1_gpio.dtbo\")\ngpio1 = BYU_GPIO(\"pr_1_gpio\", BYU_GPIO.ALL_OUTPUTS)\n\noverlay.pr_download(\"pr_3\", PARTIAL_BITSTREAM_PATH + \"pr_3_gpio.bit\", DTBO_PATH + \"pr_3_gpio.dtbo\")\ngpio3 = BYU_GPIO(\"pr_3_gpio\", BYU_GPIO.ALL_INPUTS)",
"_____no_output_____"
],
[
"import time\n\n# Since only the right most pin is needed as an output\n# for the LEDs, that one is set to an output(0), while\n# the rest are set to inputs (1).\ngpio0.setDirection(0xe)\n\nled_value = 0\n\nfor i in range(20):\n time.sleep(0.5)\n gpio1.write(led_value)\n led_value = led_value ^ 0b10000001\n \n val = gpio3.read() & 0x01\n \n gpio0.write(val)\n if val:\n print('on')\n else:\n print('off')",
"off\non\noff\non\noff\non\noff\non\noff\non\noff\non\noff\non\noff\non\noff\non\noff\non\n"
],
[
"gpio0.release()\ngpio1.release()\ngpio3.release()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
e71f9712f7cca34da11176062d3ff41dee8a322f | 536,087 | ipynb | Jupyter Notebook | week08/inClass_week08.ipynb | UIUC-iSchool-DataViz/spring2019online | e586cfafd90d6de38c308bf8ad072c9a4ed8485b | [
"BSD-3-Clause"
] | 1 | 2019-08-11T04:03:24.000Z | 2019-08-11T04:03:24.000Z | week08/inClass_week08.ipynb | UIUC-iSchool-DataViz/spring2019online | e586cfafd90d6de38c308bf8ad072c9a4ed8485b | [
"BSD-3-Clause"
] | 1 | 2020-03-02T00:11:33.000Z | 2020-03-02T00:11:33.000Z | week08/inClass_week08.ipynb | UIUC-iSchool-DataViz/spring2019online | e586cfafd90d6de38c308bf8ad072c9a4ed8485b | [
"BSD-3-Clause"
] | 1 | 2020-03-09T16:13:34.000Z | 2020-03-09T16:13:34.000Z | 120.468989 | 67,712 | 0.772455 | [
[
[
"# Basic maps with cartopy",
"_____no_output_____"
]
],
[
[
"# import our usual things\n%matplotlib inline\nimport cartopy\nimport pandas as pd\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"# make plots a little bigger\nplt.rcParams['figure.dpi'] = 100 # 300",
"_____no_output_____"
],
[
"states_files = cartopy.io.shapereader.natural_earth(resolution='110m', category='cultural', \n name='admin_1_states_provinces_lakes_shp')",
"_____no_output_____"
],
[
"# read the shape file's contents\nreader = cartopy.io.shapereader.Reader(states_files)\n\n# line by line reading of data\ndata_line = reader.records()\ndata = next(data_line)\ndata",
"_____no_output_____"
],
[
"# grab individual bits of info\nregions = lambda data: data.attributes['diss_me']\nstates_by_region = sorted(reader.records(),key=regions)[:5]\nstates_by_region",
"_____no_output_____"
],
[
"# lets move on from (badly spelled) academic pulling of data\nfig = plt.figure()\nax = fig.add_subplot(111, projection=cartopy.crs.PlateCarree())\nax.coastlines()\nplt.title('Equirectangular')",
"_____no_output_____"
],
[
"fig = plt.figure()\nax = fig.add_subplot(111,projection=cartopy.crs.Mollweide())\nax.coastlines()\nplt.title(\"Mollweide\")",
"_____no_output_____"
],
[
"# lets draw some lines between points\nchampaign_lat, champaign_lon = 40.1164, -88.2434\nant_lat, ant_lon = -18.8792, 47.5079",
"_____no_output_____"
],
[
"fig = plt.figure()\nax = fig.add_subplot(111, projection = cartopy.crs.PlateCarree())\nax.coastlines()\nax.gridlines()\nax.set_global()\nax.plot([champaign_lon, ant_lon],[champaign_lat,ant_lat], \n transform=cartopy.crs.PlateCarree())\n# shortest distance\nax.plot([champaign_lon, ant_lon],[champaign_lat,ant_lat], \n transform=cartopy.crs.Geodetic())\n",
"_____no_output_____"
],
[
"# I can also plot points\nfig =plt.figure()\nax=fig.add_subplot(111,projection=cartopy.crs.Mollweide())\nchampaign = 40.1164, -88.2434\noahu = 19.8968, -155.582\nax.scatter(champaign[1],champaign[0], \n transform = cartopy.crs.PlateCarree())\nax.scatter(oahu[1],oahu[0], transform=cartopy.crs.PlateCarree())\nax.set_global()\nax.coastlines()",
"_____no_output_____"
],
[
"locations = pd.read_csv('/Users/jillnaiman1/Downloads/location.txt', header=None, delimiter='\\t',\n names=['longitude', 'latitude', 'empty1', 'empty2'])",
"_____no_output_____"
],
[
"del locations['empty1'], locations['empty2']",
"_____no_output_____"
],
[
"locations",
"_____no_output_____"
],
[
"fig = plt.figure()\nax = fig.add_subplot(111,projection=cartopy.crs.LambertCylindrical())\nax.scatter(locations['longitude'], locations['latitude'], transform=cartopy.crs.PlateCarree())\nax.coastlines()\n#ax.set_global()",
"_____no_output_____"
],
[
"import cartopy.io.img_tiles\nimagery = cartopy.io.img_tiles.OSM()\n\nfig = plt.figure()\nax = fig.add_subplot(111,projection=cartopy.crs.LambertCylindrical())\nax.scatter(locations['longitude'], locations['latitude'], transform=cartopy.crs.PlateCarree())\nax.coastlines()\nax.add_image(imagery, 4)",
"_____no_output_____"
],
[
"seismic = pd.read_csv('/Users/jillnaiman1/Downloads/data_tohoku_norm_transpose.csv',\n header = None)",
"_____no_output_____"
],
[
"seismic.shape, locations.shape",
"_____no_output_____"
],
[
"14401/(60*60)",
"_____no_output_____"
],
[
"import ipywidgets\[email protected](station=(0,437))\ndef plot(station=0):\n plt.plot(seismic[station])\n plt.xlabel(\"Time in sec\")\n plt.ylabel(\"Normalized Displacement\")\n plt.ylim(-1,1)",
"_____no_output_____"
],
[
"nstations = 300\nntimes = 1440\n\nimport numpy as np\nstationsIndex = np.random.choice(range(locations.shape[0]-1), nstations, replace=False)\ntimesIndex = np.random.choice(range(seismic.shape[0]-1), ntimes, replace=False)\n\nstationsIndex.sort()\ntimesIndex.sort()\n",
"_____no_output_____"
],
[
"locations2 = locations.loc[stationsIndex]\nseismic2 = seismic.loc[timesIndex, stationsIndex]",
"_____no_output_____"
],
[
"seismic2.shape, locations2.shape",
"_____no_output_____"
],
[
"fig = plt.figure()\nax = fig.add_subplot(111, projection=cartopy.crs.LambertCylindrical())\nax.scatter(locations2['longitude'], locations2['latitude'], transform=cartopy.crs.PlateCarree())\nax.coastlines()",
"_____no_output_____"
],
[
"seismic2",
"_____no_output_____"
],
[
"@ipywidgets.interact(station=(0,nstations-1))\ndef plot(station=0):\n plt.plot(seismic2.iloc[:,station])\n plt.xlabel(\"Time in sec\")\n plt.ylabel(\"Normalized Displacement\")\n plt.ylim(-1,1)",
"_____no_output_____"
],
[
"import bqplot\n# scales\nx_sc = bqplot.LinearScale()\ny_sc = bqplot.LinearScale()\n\n# marks\nlines = bqplot.Lines(x=seismic2.index.values, y=seismic2.loc[:,0], \n scales={'x':x_sc, 'y':y_sc})\n\n# axes\nx_ax = bqplot.Axis(scale=x_sc)\ny_ax = bqplot.Axis(scale=y_sc, orientation='vertical')\n\n# combine into figure\nfig = bqplot.Figure(marks=[lines], axes=[x_ax,y_ax])\n\n# lets link a slider widget\nslider = ipywidgets.IntSlider(min=0,max=nstations-1)\n\n# create a linking function\ndef update_slider(event):\n lines.y = seismic2.iloc[:,event['new']]\n \nslider.observe(update_slider,'value')\n\nipywidgets.VBox([slider, fig])",
"_____no_output_____"
],
[
"# combining sensor data as a function of time with our map data (locations)\[email protected](station=(0,nstations-1,1), t=(0,ntimes,1))\ndef plot(station=0, t=0):\n fig = plt.figure()\n # map figure\n ax=fig.add_subplot(211, projection=cartopy.crs.LambertCylindrical())\n colors=seismic2.iloc[t]\n ax.scatter(locations2['longitude'], locations2['latitude'], \n transform=cartopy.crs.PlateCarree(), c=colors)\n ax.coastlines()\n \n # plot of a particular sensosr as a function of time\n ax = fig.add_subplot(212)\n ax.plot(seismic2.index.values, seismic2.iloc[:,station])\n ax.set_ylim(-1,1)",
"_____no_output_____"
]
],
[
[
"# Maps with bqplot",
"_____no_output_____"
]
],
[
[
"map_mark = bqplot.Map(scales={'projection':bqplot.AlbersUSA()})\nfig = bqplot.Figure(marks=[map_mark],title='Basic')\nfig",
"_____no_output_____"
],
[
"# lets do state map instead\nsc_geo = bqplot.AlbersUSA() # scales, USA\nstate_data = bqplot.topo_load('map_data/USStatesMap.json')\n\n# lets add a tooltip that shows us something about the\n# underlying data\ndef_tt = bqplot.Tooltip(fields=['id','name'])\n\n\n# generate marks\nstates_map = bqplot.Map(map_data=state_data, scales={'projection':sc_geo}, \n tooltip=def_tt)\nstates_map.interactions ={'hover':'tooltip', 'click':'select'}\n\nfrom states_utils import get_ids_and_names\nids, state_names = get_ids_and_names(states_map)\n\ndef get_data_value(change):\n if change['owner'].selected is not None:\n for i, s in enumerate(change['owner'].selected):\n print(state_names[s==ids], s)\nstates_map.observe(get_data_value,'selected')\n\nfig = bqplot.Figure(marks=[states_map], title='US States Map', \n fig_margin={'top':0, 'bottom':0, 'left':0, 'right':0})\nfig",
"_____no_output_____"
],
[
"# lets link some export data to our map\ncomm = pd.read_csv('/Users/jillnaiman1/Downloads/total_export.csv')",
"_____no_output_____"
],
[
"comm",
"_____no_output_____"
],
[
"comm.loc[comm['State']=='Alabama'].values",
"_____no_output_____"
],
[
"years = list(comm.columns.values)\nyears = np.array(years[1:])\nyears = years.astype('int')\nyears",
"_____no_output_____"
],
[
"# lets do state map instead\nsc_geo = bqplot.AlbersUSA() # scales, USA\nstate_data = bqplot.topo_load('map_data/USStatesMap.json')\n\n# lets add a tooltip that shows us something about the\n# underlying data\ndef_tt = bqplot.Tooltip(fields=['id','name'])\n\n\n# generate marks for map\nstates_map = bqplot.Map(map_data=state_data, scales={'projection':sc_geo}, \n tooltip=def_tt)\nstates_map.interactions ={'hover':'tooltip', 'click':'select'}\n\nfrom states_utils import get_ids_and_names\nids, state_names = get_ids_and_names(states_map)\n\n# line plot for exports\nx_scl = bqplot.LinearScale()\ny_scl = bqplot.LinearScale()\nax_xcl = bqplot.Axis(label='Year', scale=x_scl)\nax_ycl = bqplot.Axis(label='Total Export from State NA', scale=y_scl, orientation='vertical', side='left')\nlines = bqplot.Lines(x=years, y=np.zeros(len(years)), scales={'x':x_scl, 'y':y_scl})\nfig_lines = bqplot.Figure(marks=[lines],axes=[ax_ycl, ax_xcl])\n\ndef get_data_value(change):\n exports = np.zeros(len(years))\n snames =''\n if change['owner'].selected is not None:\n for i, s in enumerate(change['owner'].selected):\n sn = state_names[s == ids][0]\n snames += sn +', '\n exports_in = comm.loc[comm['State']==sn].values[0][1:]\n # I have commas in my strings\n exports_in = np.array([export_in[i].replace(',','') for i in range(length(export_in))])\n export = np.apd(exports,exports_in.astype('float64'))\n lines.y=exports\n ax_ycl.label='Total export from ' + snnames\n \n #print(state_names[s==ids], s)\nstates_map.observe(get_data_value,'selected')\n\nfig = bqplot.Figure(marks=[states_map], title='US States Map', \n fig_margin={'top':0, 'bottom':0, 'left':0, 'right':0})\n\nipywidgets.HBox([fig,fig_lines])",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e71f99a4260a5e08ee63681cdcd3f6c4a5e24185 | 628,662 | ipynb | Jupyter Notebook | 90_workshops/202104_egu_short_course/exercise_solutions/14_Sentinel-5P_TROPOMI_AI_L2_exercise_solution.ipynb | trivedi-c/atm_Practical3 | 1cd1e0bd263d274cada781d871ad37314ebe139e | [
"MIT"
] | null | null | null | 90_workshops/202104_egu_short_course/exercise_solutions/14_Sentinel-5P_TROPOMI_AI_L2_exercise_solution.ipynb | trivedi-c/atm_Practical3 | 1cd1e0bd263d274cada781d871ad37314ebe139e | [
"MIT"
] | null | null | null | 90_workshops/202104_egu_short_course/exercise_solutions/14_Sentinel-5P_TROPOMI_AI_L2_exercise_solution.ipynb | trivedi-c/atm_Practical3 | 1cd1e0bd263d274cada781d871ad37314ebe139e | [
"MIT"
] | null | null | null | 252.880933 | 254,224 | 0.88388 | [
[
[
"<img src='./img/egu21_logo.png' alt='Logo EU Copernicus EUMETSAT' align='left' width='25%'></img><img src='./img/atmos_logos.png' alt='Logo EU Copernicus EUMETSAT' align='right' width='65%'></img></span>\n\n<br>",
"_____no_output_____"
],
[
"<br>",
"_____no_output_____"
],
[
"<a href=\"./00_index.ipynb\"><< Index</a><br>\n<a href=\"./13_CAMS_European_air_quality_forecast_dust_concentration_exercise_solution.ipynb\"><< 13 - CAMS European Air Quality Forecast - Dust - Exercise Solution</a><span style=\"float:right;\"><a href=\"./15_Metop-ABC_GOME-2_AAI_L3_exercise_solution.ipynb\">15 - Metop-ABC GOME-2 AAI Level 3 - Exercise Solution>></a></span>",
"_____no_output_____"
],
[
"<div class=\"alert alert-block alert-info\">\n<b>EXERCISE WORKBOOK</b>\n</div>",
"_____no_output_____"
],
[
"<hr>",
"_____no_output_____"
],
[
"# Sentinel-5P TROPOMI - Ultraviolet Aerosol Index (AI) - Level 2",
"_____no_output_____"
],
[
"This notebook is an `exercise workbook` which allows you to practise the preparation of Sentinel-5P TROPOMI Aerosol Index Level-2 data to analyse a dust event at the beginning of February 2021.",
"_____no_output_____"
],
[
"### How it works",
"_____no_output_____"
],
[
"This exercise workbook consists of two types of exercises:",
"_____no_output_____"
],
[
"#### Coding assignments\nCoding assignments ask you to fill an empty code cell with code.\nYou recognize `coding assignments` as the yellow-coloured boxes.\n\n<div class=\"alert alert-block alert-warning\">\n<b>Coding assignment</b>\n</div>",
"_____no_output_____"
],
[
"#### Questions\n\nQuestions ask you to reflect on a result and output. `Questions` are provided as green-coloured boxes.\n\n<div class=\"alert alert-block alert-success\">\n<b>Question</b>\n</div>",
"_____no_output_____"
],
[
"<br>",
"_____no_output_____"
],
[
"#### Outline:\n* [1 - Load and browse 'Sentinel-5P TROPOMI Aerosol Index Level 2' data](#load_browse_s5p)\n* [2 - Retrieve the variable 'Aerosol index from 354 and 388 nm' as xarray.DataArray](#data_retrieve_s5p)\n* [3 - Visualize 'Sentinel-5P TROPOMI aerosol index from 388 and 354 nm'](#visualize_s5p)\n* [4 - Create a geographical subset for Europe](#subset_s5p)",
"_____no_output_____"
],
[
"<hr>",
"_____no_output_____"
],
[
"##### Load required libraries",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport os\nimport xarray as xr\nimport numpy as np\nimport netCDF4 as nc\nimport pandas as pd\n\nfrom IPython.display import HTML\n\nimport matplotlib.pyplot as plt\nimport matplotlib.colors\nfrom matplotlib.cm import get_cmap\nfrom matplotlib import animation\nimport cartopy.crs as ccrs\nfrom cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER\nimport cartopy.feature as cfeature\n\nfrom matplotlib.axes import Axes\nfrom cartopy.mpl.geoaxes import GeoAxes\nGeoAxes._pcolormesh_patched = Axes.pcolormesh\n\nimport warnings\nwarnings.simplefilter(action = \"ignore\", category = RuntimeWarning)\nwarnings.simplefilter(action = \"ignore\", category = UserWarning)",
"_____no_output_____"
]
],
[
[
"##### Load helper functions",
"_____no_output_____"
]
],
[
[
"%run ./functions.ipynb",
"_____no_output_____"
]
],
[
[
"<hr>",
"_____no_output_____"
],
[
"### <a id='load_browse_s5p'></a>Load and browse `Sentinel-5P TROPOMI Aerosol Index Level 2` data",
"_____no_output_____"
],
[
"A Sentinel-5P TROPOMI Aerosol Index Level 2 file is organised in two groups: `PRODUCT` and `METADATA`. The `PRODUCT` group stores the main data fields of the product, including `latitude`, `longitude` and the variable itself. The `METADATA` group provides additional metadata items.\n\nSentinel-5P TROPOMI variables have the following dimensions:\n* `scanline`: the number of measurements in the granule / along-track dimension index\n* `ground_pixel`: the number of spectra in a measurement / across-track dimension index\n* `time`: time reference for the data\n* `corner`: pixel corner index\n\nSentinel-5P TROPOMI data is disseminated in `netCDF`. You can load a `netCDF` file with the `open_dataset()` function of the xarray library. In order to load the variable as part of a Sentinel-5P data files, you have to specify the following keyword arguments: \n- `group='PRODUCT'`: to load the `PRODUCT` group\n\nLet us load a Sentinel-5P TROPOMI data file as `xarray.Dataset` from 06 February 2021:",
"_____no_output_____"
]
],
[
[
"file = xr.open_dataset('./eodata/sentinel5p/ai/2021/02/06/S5P_OFFL_L2__AER_AI_20210206T120713_20210206T134843_17197_01_010400_20210208T015719.nc', group='PRODUCT')\nfile\n\n",
"_____no_output_____"
]
],
[
[
"<br>",
"_____no_output_____"
],
[
"<div class=\"alert alert-block alert-success\">\n<b>Question:</b><br>\n Look at the loaded xarray.Dataset and identify the dimensions. What data variables are available in the data file?\n</div>",
"_____no_output_____"
],
[
"You see that the loaded data object contains of four dimensions and seven data variables:\n* **Dimensions**:\n * `scanline` \n * `ground_pixel`\n * `time`\n * `corner`\n\n\n* **Data variables**:\n * `delta_time`: the offset of individual measurements within the granule, given in milliseconds\n * `time_utc`: valid time stamp of the data\n * `qa_value`: quality descriptor, varying between 0 (nodata) and 1 (full quality data).\n * `aerosol_index_354_388`: Aerosol index from 354 and 388 nm\n * `aerosol_index_340_380`: Aerosol index from 340 and 380 nm\n * `aerosol_index_354_388_precision`: Precision of aerosol index from 354 and 388 nm\n * `aerosol_index_340_380_precision`: Precision of aerosol index from 340 and 380 nm",
"_____no_output_____"
],
[
"<br>",
"_____no_output_____"
],
[
"### <a id='data_retrieve_s5p'></a>Retrieve the variable `Aerosol index from 354 and 388 nm` as xarray.DataArray",
"_____no_output_____"
],
[
"As a next step, you want to load one specific data variable from the `xarray.Dataset` above.",
"_____no_output_____"
],
[
"<div class=\"alert alert-block alert-warning\">\n<b>Coding assignment:</b><br>\n\nEnter below the code which selects the data variable <b>aerosol_index_354_388</b> from the xarray.Dataset <i>file</i> and call it <b>ai</b>. \n</div>",
"_____no_output_____"
]
],
[
[
"# Enter your solution here\n\n\n\n\n\n",
"_____no_output_____"
],
[
"ai = file['aerosol_index_354_388']\nai",
"_____no_output_____"
]
],
[
[
"<br>",
"_____no_output_____"
],
[
"<div class=\"alert alert-block alert-success\">\n<b>Question:</b><br>\n \nCan you identify the `long_name` of the selected data variable and do you know where it is stored?\n</div>",
"_____no_output_____"
],
[
"**Response**:\n\nThe long name of a data variable is stored as `long_name` attribute. The `long_name` of **aerosol_index_354_388** is `Aerosol index from 388 and 354 nm`.\n",
"_____no_output_____"
],
[
"<br>",
"_____no_output_____"
],
[
"You see that the `xarray.DataArray` has three dimensions, with the dimension time only having one entry. Let us select the single time step, in order to have the two-dimensional data array.",
"_____no_output_____"
],
[
"<div class=\"alert alert-block alert-warning\">\n<b>Coding assignment:</b><br>\n\nEnter below the code which selects the one time step from the xarray.DataArray `ai` and call it <b>ai_0602</b> \n</div>",
"_____no_output_____"
]
],
[
[
"# Enter your solution here\n\n\n\n\n\n\n\n\n",
"_____no_output_____"
],
[
"ai_0602 = ai[0,:,:]\nai_0602",
"_____no_output_____"
]
],
[
[
"<br>",
"_____no_output_____"
],
[
"Additionally, you can save the attributes `units` and `longname`, which you can make use of when visualizing the data.",
"_____no_output_____"
],
[
"<div class=\"alert alert-block alert-warning\">\n<b>Coding assignment:</b><br>\n\nEnter below the code which selects the following attributes: \n* `long_name` and \n* `units`.\n \nCall the variables `longname` and `units` respectively.\n</div>",
"_____no_output_____"
]
],
[
[
"# Enter your solution here\n\n\n\n\n\n\n\n",
"_____no_output_____"
],
[
"longname = ai_0602.long_name\nunits = ai_0602.units\n\nlongname, units",
"_____no_output_____"
]
],
[
[
"<br>",
"_____no_output_____"
],
[
"### <a id='visualize_s5p'></a>Visualize `Sentinel-5P TROPOMI aerosol index from 388 and 354 nm`",
"_____no_output_____"
],
[
"The next step is to visualize the dataset.",
"_____no_output_____"
],
[
"<div class=\"alert alert-block alert-warning\">\n<b>Coding assignment:</b><br>\n\nMake use of the function [visualize_pcolormesh](../functions.ipynb#visualize_pcolormesh) in order to visualize the xarray.DataArray <code>ai_0602</code>. <br>\n \nThe following kwargs have to be defined:\n* `data_array`\n* `longitude`\n* `latitude`\n* `projection`\n* `color_sale`\n* `unit`\n* `longname`\n* `vmin`,\n* `vmax`,\n* `lonmin`, `lonmax`, `latmin`, `latmax`\n* `set_global`\n \nNote: with `?visualize_pcolormesh` you can open the function's docstring to see what keyword arguments are needed to prepare your plot.\n\n</div>",
"_____no_output_____"
]
],
[
[
"# Enter your solution here\n\n\n\n\n\n\n\n\n\n",
"_____no_output_____"
],
[
"visualize_pcolormesh(data_array=ai_0602,\n longitude=ai_0602.longitude,\n latitude=ai_0602.latitude,\n projection=ccrs.PlateCarree(),\n color_scale='YlGn',\n unit=units,\n long_name=longname + ' ' + str(ai_0602.time.data),\n vmin=0, \n vmax=1,\n lonmin=-180,\n lonmax=180,\n latmin=-90,\n latmax=90,\n set_global=True)",
"_____no_output_____"
]
],
[
[
"<br>",
"_____no_output_____"
],
[
"### <a id='subset_s5p'></a>Create a geographical subset for Europe",
"_____no_output_____"
],
[
"The map above shows the aerosol index of one footprint along the entire latitude range. Let us create a geographical subset for Europe, in order to better analyse the Saharan dust event over Europe.",
"_____no_output_____"
],
[
"<div class=\"alert alert-block alert-warning\">\n<b>Coding assignment:</b><br>\n\nCreate a geographical subset for Europe. Make use of the function <a href='../functions.ipynb#generate_geographical_subset'>generate_geographical_subset</a> and call the new DataArray <code>ai_0602_subset</code>.<br>\n\nThe bounding box information can be the following:<br>\n- **latmin=28.**\n- **latmax=71.**\n- **lonmin=-22.**\n- **lonmax=43**\n\n<b>HINT:</b><br> With `?generate_geographical_subset`, you can see what keyword arguments the function requires.\n\n</div>",
"_____no_output_____"
]
],
[
[
"# Enter your solution here\n\n\n\n\n\n",
"_____no_output_____"
],
[
"latmin=28\nlatmax=71\nlonmin=-22\nlonmax=43\n\nai_0602_subset = generate_geographical_subset(xarray=ai_0602, \n latmin=latmin, \n latmax=latmax, \n lonmin=lonmin, \n lonmax=lonmax)\nai_0602_subset",
"_____no_output_____"
]
],
[
[
"<br>",
"_____no_output_____"
],
[
"<div class=\"alert alert-block alert-success\">\n<b>Question:</b><br>\n\nHow many entries for `scanline` does the DataArray **ai_0602_subset** have compared to the DataArray **ai_0602**?\n</div>",
"_____no_output_____"
],
[
"**Response**\n\nThe scanline entries have reduced from formerly `4172` to now `911` values.",
"_____no_output_____"
],
[
"<br>",
"_____no_output_____"
],
[
"Let us now visualize the subsetted `xarray.DataArray` over Europe.",
"_____no_output_____"
],
[
"<div class=\"alert alert-block alert-warning\">\n<b>Coding assignment:</b><br>\n\nMake use of the function [visualize_pcolormesh](../functions.ipynb#visualize_pcolormesh) in order to visualize the subsetted DataArray <code>ai_0602_subset</code>. <br>\n \nMake sure to set the `set_global` kwarg to `False` and specify the latitude and longitude bounding box to the ones specified for Europe.\n\nTry also to add the time information as part of the title. Add the string of the datetime information to the `longname` variable: `longname + ' ' + str(ai_0602_subset.time.data)`.",
"_____no_output_____"
]
],
[
[
"# Enter your solution here\n\n\n\n\n\n\n",
"_____no_output_____"
],
[
"visualize_pcolormesh(data_array=ai_0602_subset,\n longitude=ai_0602_subset.longitude,\n latitude=ai_0602_subset.latitude,\n projection=ccrs.PlateCarree(),\n color_scale='YlGn',\n unit=units,\n long_name=longname + ' ' + str(ai_0602_subset.time.data),\n vmin=0, \n vmax=3,\n lonmin=lonmin,\n lonmax=lonmax,\n latmin=latmin,\n latmax=latmax,\n set_global=False)",
"_____no_output_____"
]
],
[
[
"<br>",
"_____no_output_____"
],
[
"<br>",
"_____no_output_____"
],
[
"<a href=\"./00_index.ipynb\"><< Index</a><br>\n<a href=\"./13_CAMS_European_air_quality_forecast_dust_concentration_exercise_solution.ipynb\"><< 13 - CAMS European Air Quality Forecast - Dust - Exercise Solution</a><span style=\"float:right;\"><a href=\"./15_Metop-ABC_GOME-2_AAI_L3_exercise_solution.ipynb\">15 - Metop-ABC GOME-2 AAI Level 3 - Exercise Solution>></a></span>",
"_____no_output_____"
],
[
"<hr>",
"_____no_output_____"
],
[
"<img src='../../img/copernicus_logo.png' alt='Logo EU Copernicus' align='right' width='20%'><br><br><br><br>\n<p style=\"text-align:right;\">This project is licensed under the <a href=\"./LICENSE\">MIT License</a> and is developed under a Copernicus contract.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e71faa0dc2463f6b6bb9fd7d57975570415a1121 | 18,531 | ipynb | Jupyter Notebook | Worksheet 3, Pandas.ipynb | 5T0m/worksheets | aea1c8cd5700056e7ed5af5982469cc737a70b49 | [
"MIT"
] | 24 | 2019-02-09T13:19:34.000Z | 2022-02-27T14:07:25.000Z | Worksheet 3, Pandas.ipynb | 5T0m/worksheets | aea1c8cd5700056e7ed5af5982469cc737a70b49 | [
"MIT"
] | 1 | 2022-02-26T16:47:01.000Z | 2022-02-26T16:47:01.000Z | Worksheet 3, Pandas.ipynb | 5T0m/worksheets | aea1c8cd5700056e7ed5af5982469cc737a70b49 | [
"MIT"
] | 51 | 2019-02-10T12:22:28.000Z | 2022-03-16T10:59:19.000Z | 30.680464 | 432 | 0.613944 | [
[
[
"this worksheets is part of the [mlvu machine learning course](https://mlvu.github.io)<br>\nsetting up your environment: https://bit.ly/3bzpn5C\n\nFor this worksheet, we'll need to install the pandas package. Run the cell below, or run ```pip install pandas``` in the terminal/command-line/command prompt.",
"_____no_output_____"
]
],
[
[
"!pip install pandas",
"_____no_output_____"
]
],
[
[
"# Worksheet 3: Pandas\n\nPandas is a python package for data analysis. Where numpy is a package built around a the data structure of a <em>matrix</em>, pandas is a package built around the data structure of a _dataframe_. A dataframe is a lot like a matrix, with some key differences:\n\n* In a data frame, the columns have header names. \n* Different datatypes (int, string, boolean) are allowed within the same dataframe. Each column has its own datatype\n\nIn short, dataframes represent datasets of the kind we've seen in the lectures: an instance per row, and a feature per column. \n\nPandas is designed to work together with numpy and matplotlib. Let's import all of them",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"To explore Pandas we'll import the ANSUR II dataset (we also used this to create the examples in the first lecture). ANSUR II is an _anthropometric_ dataset: it contains body measurements. ANSUR II contains 108 measurements for about 4000 men and about 2000 women (all US soldiers).\n\nWe'll start by reading the data. Like numpy, pandas has a function for reading CSV files. Pandas' function is much more robust, and much less likely to give you trouble. It does come with [a lot of options](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html), so you may have to try a few things before you get it to read your data accurately.\n\nANSUR II comes in two separate tables: one for male soldiers, and one for female soldiers:",
"_____no_output_____"
]
],
[
[
"female = pd.read_csv('./ansur/ANSUR II FEMALE Public.csv')\nmale = pd.read_csv('./ansur/ANSUR II MALE Public.csv')",
"_____no_output_____"
]
],
[
[
"All the warnings from the first two social impact videos, and from the fourth lecture apply here. This is not a sample that is representative of the population, and the gender class is a sensitive attribute that is poorly captured by two classes.\n\n```male``` and ```female``` are pandas DataFrame objects. Jupyter notebooks will print these as tables:",
"_____no_output_____"
]
],
[
[
"male",
"_____no_output_____"
]
],
[
[
"These are big dataframes. Pandas can give us some quick summary statistics per column very easily.",
"_____no_output_____"
]
],
[
[
"male.describe()",
"_____no_output_____"
]
],
[
[
"\nIn pandas these columns are called <em>Series</em>, and a dataframe is basically a list of Series objects with the same length (indexed in various ways for efficient access).\n\nLet's have a look at all the available measurements.",
"_____no_output_____"
]
],
[
[
"for i, col in enumerate(female.columns):\n print(i, col)",
"_____no_output_____"
]
],
[
[
"Each column name with a lowercase letter represents a physical measurement. Some of these are quite technical (like <em>bizygomaticbreadth</em>). The dataset comes with a very helpful document that shows what each measurement means (and how it should be performed). It's [included with the worksheets](./ansur/Hotzman_2011_ANSURIII_Measurements_a548497.pdf). Scroll down to section 6.4 for the description of the measurements.",
"_____no_output_____"
],
[
"Once the dataframe is loaded, you can refer to the columns by name as python objects. For instance:",
"_____no_output_____"
]
],
[
[
"male.stature",
"_____no_output_____"
]
],
[
[
"Jupyter notebooks even gives you dynamic autocomplete. Try putting your cursor at the end of the next line and pressing the ```TAB``` button on your keyboard (it may take a second).",
"_____no_output_____"
]
],
[
[
"female.",
"_____no_output_____"
]
],
[
[
"We can now easily do scatterplots of different measurements. Let's plot the ```stature``` (height) against the ```span``` (distance between outstretched arms).",
"_____no_output_____"
]
],
[
[
"plt.scatter(female.stature, female.span, color='red')\nplt.scatter(male.stature, male.span, color='blue');",
"_____no_output_____"
]
],
[
[
"Even if we make the points transparent (```alpha=0.1```) and small (```s=1```), it's quite a dense cloud. We can easily select a small subset by [slicing](https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/):",
"_____no_output_____"
]
],
[
[
"male[:3]",
"_____no_output_____"
]
],
[
[
"Note that slicing like this only works over the rows. We can't do ```male[:3, 5:12]```, like we could in numpy.\n\nFor now, we know enough to plot a small subset of the data.",
"_____no_output_____"
]
],
[
[
"female_sub = female[:50]\nmale_sub = male[:50]\n\nplt.scatter(female_sub.stature, female_sub.span, color='red')\nplt.scatter(male_sub.stature, male_sub.span, color='blue');",
"_____no_output_____"
]
],
[
[
"To select a set of columns, the best method is to pass a list of strings containing column names. The result is another dataframe.",
"_____no_output_____"
]
],
[
[
"male[['bicepscircumferenceflexed', 'Age']]",
"_____no_output_____"
]
],
[
[
"### Simple arithmetic\n\nLike numpy, pandas objects overload basic arithmetic operations. For instance, the units in this dataset are in millimeters, which is a little hard to read. To convert them to meters, we can simply multiply by 0.001.\n",
"_____no_output_____"
]
],
[
[
"stat = female.stature * 0.001\nspan = female.span * 0.001\n\nplt.scatter(stat, span);\n\nplt.xlabel('height (m)')\nplt.ylabel('span (m)');",
"_____no_output_____"
]
],
[
[
"### Descriptive statistics\n\nFor most descriptive statistics, pandas provides member functions:",
"_____no_output_____"
]
],
[
[
"print('mean ', female.stature.mean())\nprint('std dev. ', female.stature.std())\nprint('median ', female.stature.median())\nprint('standard error ', female.stature.sem())",
"_____no_output_____"
]
],
[
[
"### Concatenating and sampling\n\nTo perform the classification task from the first lecture (predicting gender from physical measurements), we want the male and female data in a single dataframe. To accomplish this, we can concatenate the two dataframes",
"_____no_output_____"
]
],
[
[
"people = pd.concat([male, female])",
"_____no_output_____"
]
],
[
[
"This gives us a dataset of all the male measurements first, and then all the female measurements. For many reasons, it's helpful to shuffle these, so that the order is random. The simplest way to do this is pandas is to _sample_ a new dataframe (without replacement) of the same size:",
"_____no_output_____"
]
],
[
[
"people = people.sample(frac=1)\npeople[:5].Gender",
"_____no_output_____"
]
],
[
[
"Note that the row indices from the original dataframe are retained and shuffled as well. For our purposes this doesn't matter.",
"_____no_output_____"
],
[
"## Performing Classification\n\n### Categories and codes\n\nTo perform classification on this dataset, we need to convert the target value from strings to categorical data.\n\nSince gender is a sensitive attribute and we're just looking for any example, let's instead try to predict handedness. This is indicated by the attribute ```WritingPreference```.\n\nRight now, pandas thinks the column can have any string value: when we convert it, it checks the existing values (```Left Hand```, ```Right hand``` and ```Either hand (No preference)```) and limits the column values to those two options (changing the datatype).",
"_____no_output_____"
]
],
[
[
"wp_cat = people.WritingPreference.astype('category')\nprint(wp_cat.dtype)\nprint(wp_cat.cat.categories)",
"_____no_output_____"
]
],
[
[
"Note that we haven't changed the original data. To insert the categorized column back into the original dataframe, we just re-assign it.",
"_____no_output_____"
]
],
[
[
"people.WritingPreference = people.WritingPreference.astype('category')",
"_____no_output_____"
]
],
[
[
"We can quickly check the class balance using the ```value_counts()``` function. (For a more fancy display, try the hist() function).",
"_____no_output_____"
]
],
[
[
"people.WritingPreference.value_counts(normalize=True) \n\n# normalize=False will give you absolute counts",
"_____no_output_____"
]
],
[
[
"What does this tell us about the performance of the majority class baseline?",
"_____no_output_____"
],
[
"For many tasks (including classification with sklearn), we need integers instead of categorical values. Pandas actually uses integer codes behind the scenes for its categories and it's a simple matter to get a column of integers from a column of categorical data:",
"_____no_output_____"
]
],
[
[
"people.WritingPreference.cat.codes",
"_____no_output_____"
]
],
[
[
"This allows us, for instance, to scatterplot the data using the categories for color.",
"_____no_output_____"
],
[
"You can add a cmap argument like ```cmap='copper'``` to change the colors. A [colormap](https://matplotlib.org/examples/color/colormaps_reference.html) maps a range of numeric values to a range of colors. I our case, we only have the values 0 and 1, so those get mapped to the extremes of the chosen colormap.",
"_____no_output_____"
]
],
[
[
"sub = people[:500]\nplt.scatter(sub.stature, sub.span, c=sub.WritingPreference.cat.codes, alpha=0.3);",
"_____no_output_____"
]
],
[
[
"Clearly, stature and span are not very predictive. Perhaps the measurements of the right arm will tell us a little more??",
"_____no_output_____"
]
],
[
[
"sub = people[:500]\nplt.scatter(sub.bicepscircumferenceflexed, sub.bideltoidbreadth, c=sub.WritingPreference.cat.codes, alpha=0.3);",
"_____no_output_____"
]
],
[
[
"Clearly, this is a difficult problem. It may even be impossible from the features we have. Let's try anyway.",
"_____no_output_____"
],
[
"### Classification\n\nRunning a classifier looks much the same as it did with a numpy array.",
"_____no_output_____"
]
],
[
[
"from sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\n\ntrain = people[:4000]\ntest = people[4000:]\n# NB: We can split like this because we know the data is shuffled\n\ncls = SVC()\ncls.fit(train[['stature','span']], train.WritingPreference)\n\naccuracy_score(cls.predict(test[['stature', 'span']]), test.WritingPreference)",
"_____no_output_____"
]
],
[
[
"Very slightly higher than the majority class (though your results may differ). Can we conclude that handedness can be predicted from height and span?\n\nLet's see what we get for a kNN classifier on all measurements.",
"_____no_output_____"
]
],
[
[
"from sklearn.neighbors import KNeighborsClassifier as KNN\nfrom sklearn.metrics import accuracy_score\n\ntrain = people[:4000]\ntest = people[4000:]\n# NB: We can split like this because we know the data is shuffled\n\ntraina, testa = train.iloc[:, 1:94], test.iloc[:, 1:94] # select all measurement columns\n\ncls = KNN(n_neighbors=1)\ncls.fit(traina, train.WritingPreference)\n\naccuracy_score(cls.predict(testa), test.WritingPreference)",
"_____no_output_____"
]
],
[
[
"Lower than the majority class. Note that with the number of neigbhors at 1, kNN is likely to overfit. See what happens if you increase the number of neighbors.\n\nAt this point, we're in danger of multiple testing, so we should make a proper train/validation/test split. Can you see how you would do that?",
"_____no_output_____"
],
[
"As you can see, sklearn integrates beautifully with pandas, making our training and testing code even simpler. Not all libraries integrate this well with pandas; mlxtend, for instance, only inderstands numpy data.\n\nHappily, pandas data contains numpy arrays in the background, and we can simply ask for those by retrieving the ```.values``` attribute.",
"_____no_output_____"
]
],
[
[
"from mlxtend.plotting import plot_decision_regions\n\n# Plot the decision boundary with the first 50 points in the test set\nnumpy_x = train[['stature','span']].values\nnumpy_y = train.WritingPreference.cat.codes.values\n\n# This is necessary if pandas read the CSV files as integers\n# (seems to depend on version/OS)\nnumpy_x = numpy_x.astype(float)\n\n# Rebuild the classifier \n# (a classifier trained on pandas data doesn't interoperate well with pure numpy data)\ntree = KNN(n_neighbors=2)\ntree.fit(numpy_x, numpy_y)\n\nplot_decision_regions(numpy_x[:25, :], numpy_y[:25], clf=tree, res=0.1);\n\n",
"_____no_output_____"
]
],
[
[
"## Final comments\n\nAs usual, there is a lot more to learn. A good place to start is the 10-minute quicktstart guide to pandas:\nhttps://pandas.pydata.org/pandas-docs/stable/10min.html\n\nOne very useful feature we didn't mention is _grouping_ (which will be familiar if you've done a little SQL):\nhttps://pandas.pydata.org/pandas-docs/stable/groupby.html\n\nHere's a list of 12 random tips, which gives you a good idea of how far pandas can go:\nhttps://www.analyticsvidhya.com/blog/2016/01/12-pandas-techniques-python-data-manipulation/\n\nNext week, deep learning with _Keras_.",
"_____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"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e71fb9a74264866d7da0c1f04d09ae29dc923106 | 297,025 | ipynb | Jupyter Notebook | Capstone/Mobile Inverted Pendulum/MIP.ipynb | kasiv008/Robotics | 302b3336005acd81202ebbbb0c52a4b2692fa9c7 | [
"MIT"
] | 1 | 2021-07-19T10:15:08.000Z | 2021-07-19T10:15:08.000Z | Capstone/Mobile Inverted Pendulum/MIP.ipynb | kasiv008/Robotics | 302b3336005acd81202ebbbb0c52a4b2692fa9c7 | [
"MIT"
] | null | null | null | Capstone/Mobile Inverted Pendulum/MIP.ipynb | kasiv008/Robotics | 302b3336005acd81202ebbbb0c52a4b2692fa9c7 | [
"MIT"
] | null | null | null | 155.266597 | 87,720 | 0.846259 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport scipy.integrate as inte\nfrom numpy import matmul as mm",
"_____no_output_____"
],
[
"def rdivide(A,B):\n c,low = cho_factor(B.T)\n K = cho_solve((c,low),A.T).T\n return C\ndef ldivide(A,B):\n c,low = cho_factor(A)\n tmp = cho_solve((c,low),B)\n return C",
"_____no_output_____"
],
[
"def circle(x,y,r):\n ang = np.arange(0,2*np.pi,0.01)\n xp = r*np.cos(ang)\n yp = r*np.sin(ang)\n plt.plot(x+xp,y+yp,color='k',linewidth=2)",
"_____no_output_____"
],
[
"def eom(params,th,phi,dth,dphi,u):\n A = params['mr']*params['r']*params['d']*np.cos(phi)\n B = params['ir']+params['mr']*(params['d']**2)\n C = params['mr']*params['g']*params['d']\n D = params['mr']*(params['r']**2)\n E = params['r']*params['mr']*params['d']*np.cos(phi) \n F = params['mr']*params['r']*params['d']\n tau = u\n tmp1 = A*F*np.sin(phi)*dphi**2-C*D*np.sin(phi)+(A+D)*tau\n tmp2 = A*E-B*D; phidd = tmp1/tmp2\n thdd = -((A+B)*phidd-C*np.sin(phi)+tau)/A\n qdd = np.array([thdd,phidd])\n return qdd",
"_____no_output_____"
],
[
"params = {}; params['g'] = 9.81\nparams['mr'] = .25; params['ir'] = .0001\nparams['d'] = .1; params['r'] = .02\n\neom(params, np.pi/4, np.pi/2, np.pi/6, np.pi/6, 1)",
"_____no_output_____"
],
[
"def dynamics(params,t,X):\n Xd = np.zeros(X.shape);u=0\n th,phi,dth,dphi = X[0],X[1],X[2],X[3]\n Xd[:2] = X[2:]\n Xd[2:] = eom(params,th,phi,dth,dphi,u)\n return Xd\ndef robotSim():\n params = {}; params['g'] = 9.81\n params['mr'] = .25; params['ir'] = .0001\n params['d'] = .1; params['r'] = .02\n t0,t1 = 0,2; y0 = np.array([0,1,0,0])\n t = np.linspace(t0,t1,445)\n y = np.zeros((len(t),len(y0))); y[0,:] = y0\n r = inte.ode(lambda t,y:dynamics(params,t,y)).set_integrator(\"dopri5\") \n r.set_initial_value(y0, t0) # initial values\n for i in range(1, t.size):\n y[i, :] = r.integrate(t[i]) # get one more value, add it to the array\n if not r.successful():\n raise RuntimeError(\"Could not integrate\")\n return t,y",
"_____no_output_____"
],
[
"t,y = robotSim()",
"_____no_output_____"
],
[
"plt.figure(figsize=(20,10))\nplt.subplot(4,1,1)\nplt.plot(t,y[:,1])\n\nplt.subplot(4,1,2)\nplt.plot(t,y[:,3])\n\nplt.subplot(4,1,3)\nplt.plot(t,y[:,0])\n\nplt.subplot(4,1,4)\nplt.plot(t,y[:,2])",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(10,10))\nplt.ylim([-.3,.3]); plt.xlim([-2,2])\nax = plt.gca()\ni = -1\nth,phi,dth,dphi = y[i,0],y[i,1],y[i,2],y[i,3]\nx = th*.02\nplt.ylim([-.3,.3]); plt.xlim([-2,2])\nplt.gca().set_aspect('equal', adjustable='box')\nax.plot(np.array([x,x+.1*2*np.sin(phi)]),\n np.array([0,2*.1*np.cos(phi)]),\n color=.5*np.array([1,1,1]),linewidth=12)\ncircle(x,0,.02)\nax.plot(np.array([-2,2]),\n np.array([-.02,-.02]),\n color=.3*np.array([1,1,1])) ",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(15,5))\nplt.ylim([-.3,.3]); plt.xlim([-2,2])\nj=0\nfor i in np.array([0,20,40,60,80,100]):\n ax = plt.subplot(3,2,j+1)\n th,phi,dth,dphi = y[i,0],y[i,1],y[i,2],y[i,3]\n x = th*.02\n plt.ylim([-.3,.3]); plt.xlim([-2,2])\n plt.gca().set_aspect('equal', adjustable='box')\n ax.plot(np.array([x,x+.1*2*np.sin(phi)]),\n np.array([0,2*.1*np.cos(phi)]),\n color=.5*np.array([1,1,1]),linewidth=12)\n circle(x,0,.02)\n ax.plot(np.array([-2,2]),\n np.array([-.02,-.02]),\n color=.3*np.array([1,1,1])) \n j+=1",
"_____no_output_____"
]
],
[
[
"#### Play the animation",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n%matplotlib notebook\n\nfig = plt.figure(figsize=(10,10))\nplt.ylim([-.3,.3]); plt.xlim([-2,2])\nax = plt.gca()\nplt.ion()\nfig.show()\nfig.canvas.draw()\n\nfor i in range(len(t)):\n th,phi,dth,dphi = y[i,0],y[i,1],y[i,2],y[i,3]\n x = th*.02\n ax.clear()\n plt.ylim([-.3,.3]); plt.xlim([-2,2])\n plt.gca().set_aspect('equal', adjustable='box')\n ax.plot(np.array([x,x+.1*2*np.sin(phi)]),\n np.array([0,2*.1*np.cos(phi)]),\n color=.5*np.array([1,1,1]),linewidth=12)\n circle(x,0,.02)\n ax.plot(np.array([-2,2]),\n np.array([-.02,-.02]),\n color=.3*np.array([1,1,1]))\n \n fig.canvas.draw()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e71fbe6164a47d863cab7904a6f89db643564b63 | 339,768 | ipynb | Jupyter Notebook | 2018-09-21_reflections_projections_gambetta/talk.ipynb | taalexander/qiskit-presentations | b2e7b5144a8e1f9fa5c2155e814f5d3c31e8ad6d | [
"Apache-2.0"
] | 10 | 2018-09-07T16:43:51.000Z | 2018-09-28T09:35:51.000Z | 2018-09-21_reflections_projections_gambetta/talk.ipynb | taalexander/qiskit-presentations | b2e7b5144a8e1f9fa5c2155e814f5d3c31e8ad6d | [
"Apache-2.0"
] | 1 | 2018-09-12T03:38:06.000Z | 2018-09-12T03:44:58.000Z | 2018-09-21_reflections_projections_gambetta/talk.ipynb | taalexander/qiskit-presentations | b2e7b5144a8e1f9fa5c2155e814f5d3c31e8ad6d | [
"Apache-2.0"
] | 4 | 2018-09-12T04:08:59.000Z | 2018-09-27T03:06:51.000Z | 298.303775 | 83,492 | 0.935162 | [
[
[
"<img src=\"images/qiskit_banner.png\" width=\"500 px\" align=\"left\">",
"_____no_output_____"
],
[
"# Programming a Quantum Computer \n## Jay Gambetta\n## IBM Fellow, Quantum Computing ",
"_____no_output_____"
],
[
"www.qiskit.org An open source quantum computing framework for writing quantum experiments, programs, and applications",
"_____no_output_____"
]
],
[
[
"import slides",
"Hello Reflections|Projections ... \n"
],
[
"slides.lab()",
"_____no_output_____"
],
[
"slides.system()",
"_____no_output_____"
],
[
"slides.transmon()",
"_____no_output_____"
],
[
"slides.ibmqx()",
"_____no_output_____"
],
[
"slides.qiskit()",
"_____no_output_____"
],
[
"slides.elements()",
"_____no_output_____"
],
[
"slides.git()",
"_____no_output_____"
],
[
"from qiskit import IBMQ\nIBMQ.load_accounts()",
"_____no_output_____"
],
[
"IBMQ.backends()",
"_____no_output_____"
],
[
"IBMQ.backends(n_qubits=5)",
"_____no_output_____"
],
[
"from qiskit.backends.ibmq import least_busy\nleast_busy(IBMQ.backends(n_qubits=5))",
"_____no_output_____"
],
[
"for backend in IBMQ.backends(simulator=False):\n print(backend.status())",
"{'pending_jobs': 5, 'name': 'ibmqx4', 'operational': True}\n{'pending_jobs': 8, 'name': 'ibmqx5', 'operational': False}\n{'pending_jobs': 0, 'name': 'ibmqx2', 'operational': False}\n{'pending_jobs': 0, 'name': 'ibmq_16_melbourne', 'operational': True}\n"
],
[
"slides.ibmq_qcc()",
"_____no_output_____"
],
[
"slides.quantum()",
"_____no_output_____"
]
],
[
[
"thanks omgcatsinspace for the permission to use the quantum cat",
"_____no_output_____"
]
],
[
[
"slides.model()",
"_____no_output_____"
],
[
"from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute\nfrom qiskit.tools.visualization import plot_histogram, circuit_drawer, plot_state\nfrom qiskit import Aer",
"_____no_output_____"
],
[
"# Quantum and Classical Registers\nq = QuantumRegister(1)\nc = ClassicalRegister(1)\n\n# Build the circuit\nqc = QuantumCircuit(q, c)\nqc.h(q)\n\n#-----\n\nqc.measure(q, c)\n\n# Execute the circuit\nbackend = Aer.get_backend('qasm_simulator')\nresult = execute(qc, backend, shots=1000).result()\n\n# Display the result\nplot_histogram(result.get_counts(qc))",
"_____no_output_____"
],
[
"# Quantum Registers\nq = QuantumRegister(2)\n\n# Build the circuit\nbell = QuantumCircuit(q)\nbell.h(q[0])\nbell.cx(q[0], q[1])\n\n# Draw the circuit\ncircuit_drawer(bell)",
"_____no_output_____"
],
[
"c2 = ClassicalRegister(2)\n\n# Measurement in standard basis\nmeas_zi = QuantumCircuit(q, c) \nmeas_zi.measure(q[0], c[0])\n\n# Measurement in superposition basis\nmeas_xi = QuantumCircuit(q, c)\nmeas_xi.h(q[0])\nmeas_xi.measure(q[0], c[0])\n\n# Joint measurement in standard basis\nmeas_zz = QuantumCircuit(q, c2) \nmeas_zz.measure(q, c2)\n\n# Joint measurement in superposition basis\nmeas_xx = QuantumCircuit(q, c2) \nmeas_xx.h(q)\nmeas_xx.measure(q, c2)",
"_____no_output_____"
],
[
"# Execute the circuit\nqc = bell+meas_xx\nresult = execute(qc, backend, shots=1000).result()\n\n# Display the result\nplot_histogram(result.get_counts(qc))",
"_____no_output_____"
],
[
"# let's choose a device and \ndevice = least_busy(IBMQ.backends(simulator=False))\nprint('running it on ', device)\nqc = bell+meas_zz\njob = execute(qc, device)\n\nimport time\nlapse = 0\ninterval = 60\nwhile job.status().name != 'DONE':\n print('Status @ {} seconds'.format(interval * lapse))\n print(job.status())\n print(job.queue_position())\n time.sleep(interval)\n lapse += 1\nprint(job.status())\n \ndevice_result = job.result()\ndevice_counts = device_result.get_counts()\nplot_histogram(device_counts)",
"running it on ibmq_16_melbourne\nStatus @ 0 seconds\nJobStatus.INITIALIZING\nNone\nJobStatus.DONE\n"
],
[
"# Build the circuit\nsuperpositon = QuantumCircuit(q) \noracle = QuantumCircuit(q) \namplitude_amp = QuantumCircuit(q) \n\n\n#Make superposition off all\nsuperpositon.h(q)\n\n#encode the oracle \ntest = '01'\nif test == '00':\n oracle.z(q)\n oracle.cz(q[0], q[1]) \nif test == '10':\n oracle.z(q[1])\n oracle.cz(q[0], q[1]) \nif test == '01':\n oracle.z(q[0])\n oracle.cz(q[0], q[1]) \nif test == '11':\n oracle.cz(q[0], q[1])\n\n\n#amplitude amplifcation\namplitude_amp.h(q)\namplitude_amp.z(q)\namplitude_amp.cz(q[0], q[1])\namplitude_amp.h(q)\n\n\ngrover = superpositon+oracle+amplitude_amp\n\nqc = grover+meas_zz",
"_____no_output_____"
],
[
"circuit_drawer(qc)",
"_____no_output_____"
],
[
"# Execute the circuit\nresult = execute(qc, backend, shots=1).result()\n\nprint(result.get_counts(qc))",
"{'01': 1}\n"
],
[
"# let's choose a device and \ndevice = least_busy(IBMQ.backends(simulator=False))\nprint('running it on ', device)\nqc = grover+meas_zz\njob = execute(qc, device)\n\nlapse = 0\ninterval = 60\nwhile job.status().name != 'DONE':\n print('Status @ {} seconds'.format(interval * lapse))\n print(job.status())\n print(job.queue_position())\n time.sleep(interval)\n lapse += 1\nprint(job.status())\n \ndevice_result = job.result()\ndevice_counts = device_result.get_counts()\nplot_histogram(device_counts)",
"running it on ibmq_16_melbourne\nStatus @ 0 seconds\nJobStatus.INITIALIZING\nNone\nJobStatus.DONE\n"
],
[
"from qiskit.extensions import simulator\n\nsnapshots = ['0','1','2']\n\nsuperpositon.snapshot(snapshots[0])\noracle.snapshot(snapshots[1])\namplitude_amp.snapshot(snapshots[2])\n\ngrover_with_snapshot = superpositon+oracle+amplitude_amp\n\n# Execute the circuit\nbackend_state = Aer.get_backend('statevector_simulator')\nresult = execute(grover_with_snapshot, backend_state).result()",
"_____no_output_____"
],
[
"import numpy as np\n\nstate = result.get_snapshot(snapshots[0], grover_with_snapshot)\n\nprint(state.round(2))\nplot_state(np.outer(state, state.conj()))\n\nstate = result.get_snapshot(snapshots[1], grover_with_snapshot)\nprint(state.round(2))\nplot_state(np.outer(state, state.conj()))\n\nstate = result.get_snapshot(snapshots[2], grover_with_snapshot)\nprint(state.round(2))\nplot_state(np.outer(state, state.conj()))",
"[0.5+0.j 0.5+0.j 0.5+0.j 0.5+0.j]\n"
],
[
"slides.entanglement()",
"_____no_output_____"
],
[
"slides.aqua()",
"_____no_output_____"
],
[
"from collections import OrderedDict\n\nfrom qiskit_aqua_chemistry.drivers import ConfigurationManager\nfrom qiskit_aqua_chemistry.core import get_chemistry_operator_instance\nfrom qiskit_aqua_chemistry import FermionicOperator",
"_____no_output_____"
],
[
"cfg_mgr = ConfigurationManager()\npyscf_cfg = OrderedDict([\n ('atom', 'H .0 .0 .0; H .0 .0 0.735'),\n ('unit', 'Angstrom'),\n ('basis', 'sto3g')\n])\ndriver = cfg_mgr.get_driver_instance('PYSCF')\nh2molecule = driver.run({'properties': pyscf_cfg})",
"_____no_output_____"
],
[
"h2molecule._one_body_integrals",
"_____no_output_____"
],
[
"# get fermionic operator and mapping to qubit operator\nferOp = FermionicOperator(h1=h2molecule._one_body_integrals, h2=h2molecule._two_body_integrals)\nqubitOp = ferOp.mapping(map_type='PARITY', threshold=0.00000001)\nqubitOp = qubitOp.two_qubit_reduced_operator(2)\nprint(qubitOp.print_operators())",
"II\t(-1.052373245772859+0j)\nZI\t(0.3979374248431805+0j)\nIZ\t(-0.3979374248431805+0j)\nZZ\t(-0.011280104256235435+0j)\nXX\t(0.18093119978423153+0j)\n\n"
],
[
"from qiskit_aqua import run_algorithm\nfrom qiskit_aqua.input import get_input_instance",
"_____no_output_____"
],
[
"params = {\n 'algorithm': {'name': 'VQE'},\n 'backend': {'name': 'statevector_simulator'}\n}\nalgo_input = get_input_instance('EnergyInput')\nalgo_input.qubit_op = qubitOp \nresult = run_algorithm(params, algo_input)",
"_____no_output_____"
],
[
"print(result['energy'])",
"-1.8572750301268945\n"
],
[
"slides.execution()",
"_____no_output_____"
],
[
"slides.papers()",
"_____no_output_____"
],
[
"slides.community()",
"_____no_output_____"
],
[
"slides.thanks()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e71fcb364305a625fb966459b7ad6ae7f4d0e417 | 43,307 | ipynb | Jupyter Notebook | Air_fare_Code.ipynb | mkg47/Flight-Fare-Prediction-Web-App | 0cf9a2a697ae989e8338f63e6f9b178604d01f12 | [
"MIT"
] | null | null | null | Air_fare_Code.ipynb | mkg47/Flight-Fare-Prediction-Web-App | 0cf9a2a697ae989e8338f63e6f9b178604d01f12 | [
"MIT"
] | null | null | null | Air_fare_Code.ipynb | mkg47/Flight-Fare-Prediction-Web-App | 0cf9a2a697ae989e8338f63e6f9b178604d01f12 | [
"MIT"
] | null | null | null | 32.031805 | 2,285 | 0.470455 | [
[
[
"# Importing Libraries",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"# Importing DataSet",
"_____no_output_____"
]
],
[
[
"dataset=pd.read_excel(\"Data_Train.xlsx\")",
"_____no_output_____"
],
[
"df = pd.DataFrame(dataset)\n",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
]
],
[
[
"# Data Preprocessing ",
"_____no_output_____"
]
],
[
[
"df.shape",
"_____no_output_____"
],
[
"df.isnull().sum()",
"_____no_output_____"
],
[
"#removing Null value rows\ndataset.dropna(inplace= True)\ndf = pd.DataFrame(dataset)",
"_____no_output_____"
],
[
"df['Additional_Info'].value_counts()\n",
"_____no_output_____"
],
[
"#removing Unnecessary columns\ndf.drop(columns= [\"Additional_Info\"], inplace =True ,axis=1)\ndf.drop(columns= [\"Route\"], inplace =True ,axis=1)",
"_____no_output_____"
],
[
"df.columns",
"_____no_output_____"
],
[
"#Converting the Date_of_Journey column to datetime object followed by exctraction of date and month\ndf['Date_of_Journey'] = pd.to_datetime(df['Date_of_Journey'])\n",
"_____no_output_____"
],
[
"print (df['Date_of_Journey'].dtype)",
"datetime64[ns]\n"
],
[
"df['month'] = df['Date_of_Journey'].dt.month\ndf['day'] = df['Date_of_Journey'].dt.day\ndf.drop(columns = {\"Date_of_Journey\"}, inplace= True, axis=1)\ndf.drop(columns = {'Arrival_Time'}, inplace = True, axis=1)",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df['Total_Stops'].value_counts()",
"_____no_output_____"
],
[
"# Replacing the Total_Stops columns to numeric data\ndf['Total_Stops'] = df['Total_Stops'].replace(['non-stop'],'0')\ndf['Total_Stops'] = df['Total_Stops'].replace(['1 stop'],'1')\ndf['Total_Stops'] = df['Total_Stops'].replace(['2 stops'],'2')\ndf['Total_Stops'] = df['Total_Stops'].replace(['3 stops'],'3')\ndf['Total_Stops'] = df['Total_Stops'].replace(['4 stops'],'4')",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"#Rounding off the Dep_Time Column to only hours\ntime = pd.DatetimeIndex(df['Dep_Time'])",
"_____no_output_____"
],
[
"mn=time.minute\nhr=time.hour",
"_____no_output_____"
],
[
"k =0\nhour=([])\nfor m in mn:\n if m>=30:\n x = 1 + hr[k]\n else:\n x=hr[k]\n \n if x>=24:\n x=x-24\n hour.append(x)\n k +=1",
"_____no_output_____"
],
[
"df['Dep_Hour']=hour\ndf.drop(columns={\"Dep_Time\"}, inplace= True, axis=1)\n",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"duration=df[\"Duration\"]\nduration = list(duration)\nfor i in range(len(duration)):\n if (len(duration[i].split()) !=2):\n if \"h\" in duration[i]:\n duration[i]=duration[i]+ \" 0m\"\n else:\n duration[i]= \"0h \"+ duration[i]\n\n",
"_____no_output_____"
],
[
"#extracting the duration in hours and mins and converting it to floating value of hours\nduration_hours=[]\nduration_mins=[]\n\nfor i in range(len(duration)):\n duration_hours.append(duration[i].split(sep='h')[0])\n duration_mins.append(duration[i].split(sep=' ')[-1].split(sep='m')[0])\n\n",
"_____no_output_____"
],
[
"k=0\nx=[None]*len(duration_hours)\nfor hr in duration_hours:\n x[k]=(int(hr)*60+int(duration_mins[k]))\n k=k+1",
"_____no_output_____"
],
[
"df['Duration']=x",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"print(df.columns.tolist())",
"['Airline', 'Source', 'Destination', 'Duration', 'Total_Stops', 'Price', 'month', 'day', 'Dep_Hour']\n"
],
[
"# Reaggangement of Columns\ndf=df[['Airline', 'Source', 'Destination', 'Duration', 'Total_Stops', 'month', 'day', 'Dep_Hour', 'Price']]",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df['Airline'].value_counts()",
"_____no_output_____"
],
[
"df['Source'].value_counts()",
"_____no_output_____"
],
[
"df['Destination'].value_counts()",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"df['Destination'] = df['Destination'].replace(['New Delhi'],'Delhi')",
"_____no_output_____"
],
[
"df['Destination'].value_counts()",
"_____no_output_____"
],
[
"#Applying One hot encoding on columns=[\"Airline\", \"Source\", \"Destination\"]\nencoded_df=pd.get_dummies(data=df, columns=[\"Airline\", \"Source\", \"Destination\"], drop_first=True)",
"_____no_output_____"
],
[
"encoded_df.shape",
"_____no_output_____"
],
[
"encoded_df.columns",
"_____no_output_____"
],
[
"# Rearrangement of Columns \nencoded_df=encoded_df[['Duration', 'Total_Stops', 'month', 'day', 'Dep_Hour',\n 'Airline_Air India', 'Airline_GoAir', 'Airline_IndiGo',\n 'Airline_Jet Airways', 'Airline_Jet Airways Business',\n 'Airline_Multiple carriers',\n 'Airline_Multiple carriers Premium economy', 'Airline_SpiceJet',\n 'Airline_Trujet', 'Airline_Vistara', 'Airline_Vistara Premium economy',\n 'Source_Chennai', 'Source_Delhi', 'Source_Kolkata', 'Source_Mumbai',\n 'Destination_Cochin', 'Destination_Delhi', 'Destination_Hyderabad',\n 'Destination_Kolkata', 'Price']]",
"_____no_output_____"
],
[
"e_df=pd.DataFrame(encoded_df)\ne_df.shape",
"_____no_output_____"
],
[
"#Splitting dataset into X and Y followed by X_test,X_train,y_test,y_train\nX=e_df.iloc[:,:-1].values\ny=e_df.iloc[:,-1].values",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1)",
"_____no_output_____"
]
],
[
[
"# Training and Testing of Regression Model",
"_____no_output_____"
],
[
"### DecisionTreeClassifier",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import mean_squared_error\nfrom sklearn.tree import DecisionTreeClassifier\nregressor1=DecisionTreeClassifier()\nregressor1.fit(X_train,y_train)",
"_____no_output_____"
],
[
"regressor1.score(X_test,y_test)",
"_____no_output_____"
],
[
"preds1 = regressor1.predict(X_test)\nr1_score=mean_squared_error(y_test, preds1)",
"_____no_output_____"
],
[
"r1_score",
"_____no_output_____"
]
],
[
[
"### ExtraTreesRegressor",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import ExtraTreesRegressor\nregressor2= ExtraTreesRegressor()\nregressor2.fit(X_train,y_train)",
"_____no_output_____"
],
[
"regressor2.score(X_test,y_test)",
"_____no_output_____"
],
[
"preds2 = regressor2.predict(X_test)\nr2_score=mean_squared_error(y_test, preds2)",
"_____no_output_____"
],
[
"r2_score",
"_____no_output_____"
]
],
[
[
"### RandomForestRegressor",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import RandomForestRegressor\nregressor3= RandomForestRegressor()\nregressor3.fit(X_train,y_train)",
"_____no_output_____"
],
[
"regressor3.score(X_test,y_test)",
"_____no_output_____"
],
[
"preds3 = regressor3.predict(X_test)\nr3_score=mean_squared_error(y_test, preds3)",
"_____no_output_____"
],
[
"r3_score",
"_____no_output_____"
]
],
[
[
"### XGBRegressor",
"_____no_output_____"
]
],
[
[
"from xgboost import XGBRegressor\nregressor4 = XGBRegressor()\nregressor4.fit(X_train,y_train)",
"_____no_output_____"
],
[
"regressor4.score(X_test,y_test)",
"_____no_output_____"
],
[
"preds4 = regressor4.predict(X_test)\nr4_score=mean_squared_error(y_test, preds4)",
"_____no_output_____"
],
[
"r4_score",
"_____no_output_____"
]
],
[
[
"### As observed from the score of various Regressors, we find that XGBRegressor gives the best score.\n### So we will be implementing XGBRegressor in our Web App which will be hosted using Heroku",
"_____no_output_____"
]
],
[
[
"from xgboost import XGBRegressor\nmodel = XGBRegressor()\nmodel.fit(X,y)",
"_____no_output_____"
],
[
"import pickle\nfilename = 'finalized_model.pkl'\npickle.dump(model, open(filename, 'wb'))",
"_____no_output_____"
],
[
"loaded_model = pickle.load(open(filename, 'rb'))\nresult = loaded_model.score(X_test, y_test)\nprint(result)",
"0.9138419727179724\n"
]
],
[
[
"## The final XGBRegressor model is saved as pickle file named- finalized_model.pkl",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
e71fd01985a90340d5af5a83e453fb9b58b0113b | 718,615 | ipynb | Jupyter Notebook | face_mask_detection cnn/mask_detecition.ipynb | rajatbansal01/Deep-Learning-Projects | 4a7c6f8b0d956b31ef33f8417ba5b45c1eccb14e | [
"MIT"
] | 3 | 2021-04-18T08:39:14.000Z | 2021-09-29T05:49:36.000Z | face_mask_detection cnn/mask_detecition.ipynb | rajatbansal01/Deep-Learning-Projects | 4a7c6f8b0d956b31ef33f8417ba5b45c1eccb14e | [
"MIT"
] | null | null | null | face_mask_detection cnn/mask_detecition.ipynb | rajatbansal01/Deep-Learning-Projects | 4a7c6f8b0d956b31ef33f8417ba5b45c1eccb14e | [
"MIT"
] | null | null | null | 1,278.674377 | 694,072 | 0.957351 | [
[
[
"% cd /content/drive/MyDrive/edureka!/Assignments/test-1",
"/content/drive/MyDrive/edureka!/Assignments/test-1\n"
],
[
"import tensorflow \nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator \nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D, Activation\nfrom tensorflow.keras.preprocessing import image\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg",
"_____no_output_____"
],
[
"img_width, img_height = 150,150 #width and height of the images\ntrain_data_dir = \"dataset/train\"\nvalidation_data_dir= \"dataset/test\"\nnb_train_sample =40\nnb_validation_samples =20\nepochs =20\nbatch_size= 20",
"_____no_output_____"
],
[
"import tensorflow.keras.backend as k\nif k.image_data_format()=='channels_first': \n input_shape=(3, img_width, img_height)\nelse:\n input_shape=(img_width,img_height,3)",
"_____no_output_____"
],
[
"train_datagen=ImageDataGenerator ( rescale=1. /255,shear_range =0.2,zoom_range=0.2,horizontal_flip =True)\n\n\ntest_datagen=ImageDataGenerator (rescale=1. /255)\n\n\ntrain_generator =train_datagen.flow_from_directory(train_data_dir,target_size =(img_width,img_height), batch_size=batch_size,class_mode='binary',classes=['with_mask','without_mask'])\n\nvalidation_generator =test_datagen.flow_from_directory(validation_data_dir,target_size =(img_width,img_height), batch_size=batch_size,class_mode='binary')",
"Found 816 images belonging to 2 classes.\nFound 560 images belonging to 2 classes.\n"
],
[
"plt.figure(figsize=(12, 12))\nfor i in range(0, 15):\n plt.subplot(5, 3, i+1)\n for X_batch, Y_batch in train_generator:\n image = X_batch[0]\n plt.imshow(image)\n break\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
],
[
"model = Sequential()\nmodel.add(Conv2D(64,(3,3),input_shape=input_shape))\n\n\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Flatten())\nmodel.add(Dense(64)) \n\nmodel.add(Activation('relu'))\nmodel.add(Dense(1)) \nmodel.add(Activation('sigmoid')) \nmodel.summary()",
"Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 148, 148, 64) 1792 \n_________________________________________________________________\nactivation (Activation) (None, 148, 148, 64) 0 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 74, 74, 64) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 350464) 0 \n_________________________________________________________________\ndense (Dense) (None, 64) 22429760 \n_________________________________________________________________\nactivation_1 (Activation) (None, 64) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 1) 65 \n_________________________________________________________________\nactivation_2 (Activation) (None, 1) 0 \n=================================================================\nTotal params: 22,431,617\nTrainable params: 22,431,617\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"model.compile(optimizer='rmsprop',\n loss='binary_crossentropy',\n metrics=['accuracy'])\nmodel.summary()",
"Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 148, 148, 64) 1792 \n_________________________________________________________________\nactivation (Activation) (None, 148, 148, 64) 0 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 74, 74, 64) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 350464) 0 \n_________________________________________________________________\ndense (Dense) (None, 64) 22429760 \n_________________________________________________________________\nactivation_1 (Activation) (None, 64) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 1) 65 \n_________________________________________________________________\nactivation_2 (Activation) (None, 1) 0 \n=================================================================\nTotal params: 22,431,617\nTrainable params: 22,431,617\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"training = model.fit(train_generator,\n steps_per_epoch=nb_train_sample,\n epochs=10,\n validation_data=validation_generator,\n validation_steps=nb_validation_samples)",
"Epoch 1/10\n40/40 [==============================] - 178s 5s/step - loss: 0.4247 - accuracy: 0.8266 - val_loss: 0.2803 - val_accuracy: 0.8925\nEpoch 2/10\n40/40 [==============================] - 34s 878ms/step - loss: 0.3604 - accuracy: 0.8606 - val_loss: 0.2184 - val_accuracy: 0.9350\nEpoch 3/10\n40/40 [==============================] - 16s 409ms/step - loss: 0.2139 - accuracy: 0.9183 - val_loss: 0.1812 - val_accuracy: 0.9400\nEpoch 4/10\n40/40 [==============================] - 10s 257ms/step - loss: 0.2252 - accuracy: 0.9171 - val_loss: 0.1255 - val_accuracy: 0.9550\nEpoch 5/10\n40/40 [==============================] - 9s 218ms/step - loss: 0.2625 - accuracy: 0.9183 - val_loss: 0.0863 - val_accuracy: 0.9725\nEpoch 6/10\n40/40 [==============================] - 9s 217ms/step - loss: 0.2305 - accuracy: 0.9183 - val_loss: 0.0632 - val_accuracy: 0.9850\nEpoch 7/10\n40/40 [==============================] - 8s 209ms/step - loss: 0.1554 - accuracy: 0.9422 - val_loss: 0.4784 - val_accuracy: 0.8200\nEpoch 8/10\n40/40 [==============================] - 8s 203ms/step - loss: 0.1405 - accuracy: 0.9548 - val_loss: 0.0801 - val_accuracy: 0.9725\nEpoch 9/10\n40/40 [==============================] - 8s 207ms/step - loss: 0.1065 - accuracy: 0.9623 - val_loss: 0.0739 - val_accuracy: 0.9750\nEpoch 10/10\n40/40 [==============================] - 8s 208ms/step - loss: 0.1156 - accuracy: 0.9636 - val_loss: 0.0842 - val_accuracy: 0.9675\n"
],
[
"import numpy as np\nfrom google.colab import files\nfrom keras.preprocessing import image\n\nuploaded = files.upload()\n\nfor fn in uploaded.keys():\n \n # predicting images\n path = fn\n img = image.load_img(path, target_size=(150, 150))\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n\n images = np.vstack([x])\n classes = model.predict(images, batch_size=10)\n print(classes[0])\n if classes[0]>0.5:\n print(fn + \" is a without mask\")\n else:\n print(fn + \" is with mask\")",
"_____no_output_____"
],
[
"import json\nfrom keras.models import model_from_json\nfrom keras.models import load_model\nfrom keras.preprocessing import image\nimport numpy as np\n\n\nmodel_json = model.to_json()\nwith open(\"model.json\", \"w\") as json_file:\n json_file.write(model_json)\n\n\n\nmodel.save_weights('model.h5')\nprint(\"[INFO] Saved model to disk\")",
"[INFO] Saved model to disk\n"
],
[
"import json\nfrom tensorflow.keras.models import model_from_json\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing import image\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg",
"_____no_output_____"
],
[
"# load json and create model\njson_file = open('model.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nloaded_model = model_from_json(loaded_model_json)\n# load weights into new model\nloaded_model.load_weights(\"model.h5\")\nprint(\"Loaded model from disk\")\n# load the model we saved\n#model=load_model(\"kwhFinal.h5\")\npath = \"dataset/train/with_mask/21-with-mask.jpg\"\n# predicting images\nimg = image.load_img(path, target_size=(150, 150))\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\n\nclasses = loaded_model.predict(x)\nif classes[0]>0.5:\n print(\" is a without mask\")\nelse:\n print(\" is with mask\")\n\nimg=mpimg.imread(path)\nimgplot = plt.imshow(img)\nplt.show()",
"_____no_output_____"
],
[
"import cv2\nimport numpy as np\n\nresults={0:'without mask',1:'mask'}\nGR_dict={0:(0,0,255),1:(0,255,0)}\n\nrect_size = 4\ncap = cv2.VideoCapture(\"mask.mp4\") \n\n\nhaarcascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\nwhile True:\n (rval, im) = cap.read()\n im=cv2.flip(im,1,1) \n\n \n rerect_size = cv2.resize(im, (im.shape[1] // rect_size, im.shape[0] // rect_size))\n faces = haarcascade.detectMultiScale(rerect_size)\n for f in faces:\n (x, y, w, h) = [v * rect_size for v in f] \n \n face_img = im[y:y+h, x:x+w]\n rerect_sized=cv2.resize(face_img,(150,150))\n normalized=rerect_sized/255.0\n reshaped=np.reshape(normalized,(1,150,150,3))\n reshaped = np.vstack([reshaped])\n result=loaded_model.predict(reshaped)\n\n \n label=np.argmax(result,axis=1)[0]\n \n cv2.rectangle(im,(x,y),(x+w,y+h),GR_dict[label],2)\n cv2.rectangle(im,(x,y-40),(x+w,y),GR_dict[label],-1)\n cv2.putText(im, results[label], (x, y-10),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255,255,255),2)\n\n cv2.imshow('LIVE', im)\n key = cv2.waitKey(10)\n \n if key == 27: \n break\n\ncap.release()\n\ncv2.destroyAllWindows()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e71feb04e499e42235cb328e84798d6d3a04b84a | 503,566 | ipynb | Jupyter Notebook | Statistics_of_target_data_Analysing.ipynb | gkaiCinna/keras_retinanet | 3700b0b9504623c11fdd9c50a1c292242cdb6e60 | [
"Apache-2.0"
] | null | null | null | Statistics_of_target_data_Analysing.ipynb | gkaiCinna/keras_retinanet | 3700b0b9504623c11fdd9c50a1c292242cdb6e60 | [
"Apache-2.0"
] | null | null | null | Statistics_of_target_data_Analysing.ipynb | gkaiCinna/keras_retinanet | 3700b0b9504623c11fdd9c50a1c292242cdb6e60 | [
"Apache-2.0"
] | null | null | null | 463.688766 | 233,000 | 0.933461 | [
[
[
"# Statistics of target objects and analysing",
"_____no_output_____"
],
[
"## In order to better tuning RetinaNet, a statistics of objects' ratio(h/w) and scale(pixels of bboxs) should be done. These statistics will help to determine what layers should be used and the configuration of anchor box. ",
"_____no_output_____"
],
[
"### 1. Read in data and display",
"_____no_output_____"
]
],
[
[
"import os\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n%matplotlib inline",
"_____no_output_____"
],
[
"anno_path = 'data/train.csv'\ndf = pd.read_csv(anno_path, names=['img_path', 'xmin', 'ymin', 'xmax', 'ymax', 'label'])\ndf.head()",
"_____no_output_____"
],
[
"df.describe()",
"_____no_output_____"
],
[
"# df = df[df['label']!='AnyTable']",
"_____no_output_____"
],
[
"width = df['xmax'] - df['xmin']\nhight = df['ymax'] - df['ymin']\nratios = hight/ width\nratios = ratios.round(2)\nstatis = pd.concat([hight, width, ratios], axis=1, keys=['hight', 'width', 'ratio'], )",
"_____no_output_____"
],
[
"statis.head()",
"_____no_output_____"
],
[
"statis.describe()",
"_____no_output_____"
],
[
"ax = statis.plot(kind=\"scatter\", x=\"width\", y=\"hight\", figsize=(19,19), s=50)\nplt.xlabel(\"$width$\", fontsize=18)\nplt.ylabel(\"$hight$\", fontsize=18)\nax.tick_params(axis='both', which='major', labelsize=18)",
"_____no_output_____"
],
[
"from sklearn.cluster import KMeans, k_means\nfrom sklearn.metrics import silhouette_score\nimport numpy as np",
"_____no_output_____"
],
[
"km_num = 10\n## Take note that the latest version of Kmeans my behave slightly different. \nkmeans = KMeans(n_clusters=km_num)\nmodel = kmeans.fit(statis[['hight', 'width']])\n# Now, we can get the predicted model labels, or Centroids, in the form of an array:\n\nprint(model)\nratios_cl = model.cluster_centers_[:,0]/model.cluster_centers_[:,1]\nratios_cl = ratios_cl.round(decimals=2)\nprint('\\nratios distribution',np.sort(ratios_cl))",
"KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300,\n n_clusters=10, n_init=10, n_jobs=None, precompute_distances='auto',\n random_state=None, tol=0.0001, verbose=0)\n\nratios distribution [0.1 0.13 0.17 0.22 0.23 0.33 0.59 0.61 0.89 1.16]\n"
],
[
"plt.plot(range(len(ratios_cl)), np.sort(ratios_cl))\nplt.show()",
"_____no_output_____"
],
[
"model.labels_",
"_____no_output_____"
],
[
"# attach predicted cluster to original points\nstatis['predicted'] = model.labels_\n# Create a dataframe for cluster_centers (centroids)\ncentroids = pd.DataFrame(model.cluster_centers_, columns=['hight', 'width'])",
"_____no_output_____"
],
[
"color_map = [\n [0 ,255, 0] ,\n [31 , 0 , 255] ,\n [255 , 0 , 0] ,\n [0 , 159 , 255] ,\n [200 , 95 , 0] ,\n [122 , 89 , 156] ,\n [170 , 200 , 0] ,\n [20 , 120 , 82] ,\n [108 , 10 , 70] ,\n [0 , 25 , 255] ,\n [255 , 248 , 0] ,\n [0 , 255 , 255] ,\n [255 , 19 , 0] ,\n [170 , 30 , 100] ,\n [255 , 38 , 0] ,\n [0 , 255 , 25] ,\n [255 , 0 , 133] ,\n [255 , 172 , 0] ,\n [108 , 0 , 255] ,\n [0 , 82 , 255] ,\n [0 , 255 , 6] ,\n [255 , 0 , 152] ,\n [223 , 0 , 255] ,\n [12 , 0 , 255] ,\n [0 , 255 , 178] ,\n [184 , 0 , 255] ,\n [255 , 0 , 76] ,\n [146 , 255 , 0] ,\n [51 , 0 , 255] ,\n [0 , 197 , 255] ,\n [255 , 0 , 19] ,\n [255 , 0 , 38] ,\n [89 , 255 , 0] ,\n [255 , 153 , 0] ,\n [0 , 255 , 255] ,\n [0 , 255 , 216] ,\n [0 , 255 , 121] ,\n [255 , 0 , 248] ,\n [70 , 0 , 255] ,\n [0 , 255 , 159] ,\n [0 , 216 , 255] ,\n [0 , 6 , 255] ,\n [0 , 63 , 255] ,\n [31 , 255 , 0] ,\n [255 , 57 , 0] ,\n [255 , 0 , 210] ,\n [0 , 255 , 102] ,\n [242 , 255 , 0] ,\n [255 , 191 , 0] ,\n [0 , 255 , 63] ,\n [255 , 0 , 95] ,\n [146 , 0 , 255] ,\n [184 , 255 , 0] ,\n [255 , 114 , 0] ,\n [0 , 255 , 235] ,\n [255 , 229 , 0] ,\n [0 , 178 , 255] ,\n [255 , 0 , 114] ,\n [255 , 0 , 57] ,\n [0 , 140 , 255] ,\n [0 , 121 , 255] ,\n [12 , 255 , 0] ,\n [255 , 210 , 0] ,\n [0 , 255 , 44] ,\n [165 , 255 , 0] ,\n [0 , 255 , 140] ,\n [0 , 101 , 255] ,\n [223 , 255 , 0] ,\n [242 , 0 , 255] ,\n [89 , 0 , 255] ,\n [165 , 0 , 255] ,\n [70 , 255 , 0] ,\n [255 , 0 , 172] ,\n [255 , 76 , 0] ,\n [203 , 255 , 0] ,\n [204 , 0 , 255] ,\n [255 , 0 , 229] ,\n [255 , 133 , 0] ,\n [127 , 0 , 255] ,\n [0 , 235 , 255] ,\n [0 , 255 , 197] ,\n [255 , 0 , 191] ,\n [50 , 255 , 0]\n]",
"_____no_output_____"
],
[
"\n## Plot scatter by cluster / color, and centroids\ncolors = np.array(color_map[:km_num], dtype=np.float)\n# print(colors_raw)\nnorm = np.array([255.0,255.0,255.0], dtype=np.float)\ncolors = [x/norm for x in colors]\n# colors_raw = colors_raw.round(3)\n# colors = colors_raw[:km_num]\n# print(colors)\nstatis['color'] = statis['predicted'].map(lambda p: colors[p])\n# print(statis['color'])\n\nax = statis.plot( \n kind=\"scatter\", \n x=\"width\", y=\"hight\",\n c = statis['color'],\n figsize=(19,19),\n fontsize=15\n)\nax.set_title(\"H/W distribution of Table detection dataset\", fontsize=25)\nax.set_xlabel('Width', fontsize=18)\nax.set_ylabel('Height', fontsize=18)\n\nfor idx, row in centroids.iterrows():\n ratio = round(row[1]/row[0], 2)\n ax.annotate(ratio, (row[1], row[0]+20),size='xx-large')\n \nbx = centroids.plot(\n kind=\"scatter\", \n x=\"width\", y=\"hight\", \n marker=\"*\", c=[0,0,0],\n ax=ax,s=550,\n figsize=(19,19)\n)\n",
"'c' argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with 'x' & 'y'. Please use a 2-D array with a single row if you really want to specify the same RGB or RGBA value for all points.\n"
],
[
"new_df = statis.sort_values(by='ratio' ,ascending=True)\n# new_df = sorted_ratios.to_frame()\n# new_df.columns=['h_w_ratio']\nnew_df.iloc[:, :2].describe()",
"_____no_output_____"
],
[
"import numpy as np",
"_____no_output_____"
],
[
"fig= plt.figure(figsize=(20,20))\ncounts, rates, _ = plt.hist(new_df['ratio'][new_df['ratio']<5.0].values, bins=15,rwidth=1, color='g')\n# plt.xticks(np.arange(0.0, 10.0, 0.01))\nplt.title('Histogram of ratios of real number')\nplt.show()",
"_____no_output_____"
],
[
"print('ratios\\tcounts')\nfor c, r in zip(counts, rates):\n print('{:.2f}\\t{:.0f}'.format( r, c))",
"ratios\tcounts\n0.02\t3826\n0.21\t2058\n0.40\t659\n0.59\t319\n0.78\t513\n0.97\t782\n1.16\t55\n1.35\t23\n1.53\t2\n1.72\t2\n1.91\t1\n2.10\t0\n2.29\t2\n2.48\t0\n2.67\t4\n"
],
[
"fig= plt.figure(figsize=(20,20))\nplt.plot(rates[:-1], counts, '-d')",
"_____no_output_____"
],
[
"# counts, bins = np.histogram(new_df.val)\nfig= plt.figure(figsize=(20,20))\nplt.hist(new_df['ratio'].values, bins=50, density=True,rwidth=1, color='g', log=True)",
"_____no_output_____"
]
],
[
[
"From the histgram we observed that ",
"_____no_output_____"
]
],
[
[
"nne = pd.DataFrame(list(zip(x,y)), columns=['ratios', 'counts'])\nnne.head()\n# new_df.plot(kind='box', figsize=[20,20])",
"_____no_output_____"
],
[
"fig= plt.figure(figsize=(20,20))\nplt.hist2d(x=new_df['hight'], y=new_df['width'], bins=50)\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e71feb7f5e41791c933c7582bd8c5ad6cb081de0 | 34,484 | ipynb | Jupyter Notebook | src/notebooks/identification/generate_locations_slices_selwyn_dataset.ipynb | sushmaakoju/mturk-task-helper | 70416304f293e3907a1353ee52c440131aa8d7f1 | [
"MIT"
] | null | null | null | src/notebooks/identification/generate_locations_slices_selwyn_dataset.ipynb | sushmaakoju/mturk-task-helper | 70416304f293e3907a1353ee52c440131aa8d7f1 | [
"MIT"
] | null | null | null | src/notebooks/identification/generate_locations_slices_selwyn_dataset.ipynb | sushmaakoju/mturk-task-helper | 70416304f293e3907a1353ee52c440131aa8d7f1 | [
"MIT"
] | null | null | null | 42.415744 | 207 | 0.572004 | [
[
[
"### This script is for generating slices from main images for Selwyn dataset for Mechanical Turk labelling tasks, based on Sliding window with overlap.\n### Generates sub images, save only images where vehicles exist and validates and saves images and their corresponding image, vehicle, class name and location details to respective imagename.csv files.",
"_____no_output_____"
]
],
[
[
"from PIL import Image\nimport numpy as np\nfrom pathlib import Path\nimport cv2\nimport os\nimport re\nimport matplotlib.pyplot as plt\nimport glob\nimport urllib.request, json\nfrom io import BytesIO\nimport pandas as pd\nimport requests\nfrom urllib.parse import urlparse\nfrom numpy.lib.function_base import append\n\nImage.MAX_IMAGE_PIXELS = None",
"_____no_output_____"
]
],
[
[
"### Validate slices generated from sliding window with overlap.",
"_____no_output_____"
]
],
[
[
"def validate_slices(output_directory : str, num_xy_points:tuple, window_size:tuple) -> bool :\n print(num_xy_points)\n assert os.path.exists(output_directory), \"Output directory does not exist %s. Please check and try again.\"%str(output_directory)\n assert len(num_xy_points) > 0 and all(num_xy_points) and num_xy_points.count(0) == 0, \"Number of point tuple is 0 or None. Please check and try again.\"\n assert len(window_size) > 0 and all(window_size) and window_size.count(0) == 0, \"Window size tuple is empty is empty %d. Please check and try again.\"%window_size\n \n #validate exported files, format, count of files generated \n #files = os.listdir(output_directory)\n \n files = glob.glob(os.path.join(output_directory,\"*.png\"))\n files.sort(key=os.path.getmtime, reverse=False)\n print(output_directory, len(files))\n saved_files = [file for file in files if re.search(r\"\\d+(-)\\d+(-)[0-9]+[0-9]*(-)+[0-9]+[0-9]*(.tif|.png)\",str(file))] \n tot_points = num_xy_points[0]*num_xy_points[1]\n #check all files with tif since this method generated rows * count images and filenames\n print(len(saved_files), tot_points)\n assert len(saved_files) == tot_points, \"Missing or incorrect number of cropped sub-images. Check exported sub-images!\"\n print(\"Exported sub-images count look good!\")\n \ndef is_url(image_url):\n if type(image_url) != str:\n return False\n try:\n response = requests.get(image_url)\n print(\"URL is valid and exists on the internet \", response.ok)\n except requests.ConnectionError as exception:\n print(\"URL does not exist on Internet\")\n return False\n return True",
"_____no_output_____"
]
],
[
[
"### Validate image slices with vehicles",
"_____no_output_____"
]
],
[
[
"def validate_slices_with_vehicles(output_directory : str, tot_images:int, window_size:tuple) -> bool :\n print(tot_images)\n assert os.path.exists(output_directory), \"Output directory does not exist %s. Please check and try again.\"%str(output_directory)\n assert len(window_size) > 0 and all(window_size) and window_size.count(0) == 0, \"Window size tuple is empty is empty %d. Please check and try again.\"%window_size\n #validate exported files, format, count of files generated \n \n #files = os.listdir(output_directory)\n files = glob.glob(os.path.join(output_directory,\"*.png\"))\n files.sort(key=os.path.getmtime, reverse=False)\n \n print(output_directory, len(files))\n saved_files = [file for file in files if re.search(r\"\\d+(-)\\d+(-)[0-9]+[0-9]*(-)+[0-9]+[0-9]*(.tif|.png)\",str(file))] \n \n #check all files with tif since this method generated rows * count images and filenames\n print(len(saved_files), tot_images)\n assert len(saved_files) == tot_images, \"Missing or incorrect number of cropped sub-images. Check exported sub-images!\"\n print(\"Exported sub-images count look good!\")\n return True",
"_____no_output_____"
]
],
[
[
"### Given window size, length of side, overlap, generate points along the given length",
"_____no_output_____"
]
],
[
[
"def get_slide_points(actual_size:int, window_size:int, overlap=0.1) -> list():\n \"\"\"This function is to use a sliding window technique, is aka brute force still (without using numpy.slide_tricks/as_strided or scipy shortcuts).\n Returns points array for a given axis : points along X-axis i.e along the width of the image or y-axis i.e along height of the image\n The strides along x-axis remain same as sliding window moves to different rows along y-axis and viceversa.\n So we just need one pass along x-axis or y-axis.\n\n Args:\n actual_size (int): [actual size of the image so strides do not overrun the bounds]\n window_size (int): [size of window for cropping later, is always less than actual_size]\n overlap (float, optional): [Fraction of overlap for a stride along the axis. Defaults to 0.1]\n\n Returns:\n [List(int)]: [returns points array along a given axis length for each stride]\n \"\"\"\n assert actual_size > 0, \"Incorrect size provided for parameter 1. Please check and try again.\"\n assert window_size > 0, \"Incorrect size provided for parameter 2. Please check and try again.\"\n assert overlap > 0 and type(overlap) == float , \"Incorrect overlap value provided for parameter 3. It has to be Please check and try again.\"\n\n points = [0]\n assert actual_size > window_size and actual_size > 0 and window_size > 0, \"Incorrect actual size and window size. Please check function input params definitions.\"\n #for the purpose of ensuring overlap, calculate stride from window size and overlap so stride is within the window size we want to crop\n stride = int(window_size * (1-overlap))\n counter = 1\n #initialize and fill first point and append it\n #first point is point at end of first stride\n this_point = stride * counter\n points.append(this_point)\n counter += 1\n #start from second stride onwards and check if the point is running over the actual size\n while this_point + window_size < actual_size:\n #move on to next stride\n this_point = stride * counter\n points.append(this_point)\n counter += 1\n #loop ended - since this_point is overrunning the window size, so instead just add actual size - window size as this_point \n points.append(actual_size-window_size)\n assert len(points) == counter+1, \"Incorrect number of strides.\"\n return points",
"_____no_output_____"
]
],
[
[
"### For each annotations, image file pair, generate a dictionary for with numpy array locations for search vehicles from an Image slice.",
"_____no_output_____"
]
],
[
[
"def add_answers(annotationsfile,image_file):\n answer_dict = []\n class_loc = []\n with open(annotationsfile) as json_file:\n data = json.load(json_file)\n for key, values in data['locations'].items():\n xy = []\n x= [] \n y=[]\n if len(values) != 0:\n for value in values:\n x.append(int(value['x']))\n y.append(int(value['y']))\n \n class_loc.append({key:[np.array(x), np.array(y)]})#class_loc.append({key:np.array(xy)})\n else:\n class_loc.append({key:[]})\n return class_loc, answer_dict",
"_____no_output_____"
]
],
[
[
"### Get annotations that exist in a given cropped image and return vehicle class locations dictionary",
"_____no_output_____"
]
],
[
[
"def get_locations_from_image(i:int,j:int,class_loc:list, windowsize:int,newimage_name):\n vehicles_loc = {}\n vehicles_loc['subimagename'] =newimage_name\n count = 0\n #i rows, j columns\n for locset in class_loc:\n k,arr = *locset.keys(), *locset.values()\n if len(arr) != 0:\n x,y = arr\n\n x2 = np.where((x >= i) & (x<= i+300))[0]\n y2 = np.where((y >= j) & (y <= j+300))[0]\n ind = np.intersect1d(x2,y2)\n \n common_pts = []\n if len(ind) > 0:\n #print(ind,x[ind],y[ind],newimage_name,k)\n common_pts = [x[ind].tolist(),y[ind].tolist()]\n if len(common_pts) > 0:\n vehicles_loc[k]=common_pts\n count += len(ind)\n #print(newimage_name, x,y,i,j,arr[:,0:1],arr[:,1:],common_pts,arr[:,:][common_pts].tolist())\n #print(arr[:,0:1], i,i+windowsize, (arr[:,0:1] >= i) & (arr[:,0:1] <= i+windowsize)[0],arr[:,1:], j, j+windowsize,(arr[:,1:] >= j) & (arr[:,1:] <= j+windowsize)[1],vehicles_loc[k])\n if len(vehicles_loc.keys()) == 1:\n vehicles_loc = None\n else:\n vehicles_loc['num_vehicles'] = count\n return vehicles_loc",
"_____no_output_____"
],
[
"classes = [\"van_rv\",\"unknown\",\"truck\",\"bus\",\"trailer_small\",\"specialized\",\"trailer_large\",\"small\"]",
"_____no_output_____"
]
],
[
[
"### Generate images with Sliding window with overlap while looking for vehicle annotations that exist in each sub image",
"_____no_output_____"
]
],
[
[
"def sliding_window_with_overlap( image_path,class_loc, output_directory,window_width:int, overlap=0.1 ):\n answers = []\n filename, filext = os.path.splitext(os.path.basename(image_path) )\n #print(filename)\n assert filename and filext, \"Please check filename and file extension!\"\n im = cv2.imread(str(image_path))\n \n #output_directory = os.path.join(os.getcwd(),\"temp\")\n if not os.path.isdir(output_directory):\n os.mkdir(output_directory)\n if not os.path.isdir(output_directory):\n os.mkdir(output_directory)\n print(output_directory)\n \n #print(len(class_loc))\n assert im.shape, \"Image file could not be opened! Please check the image details and try again.\"\n imgheight, imgwidth, _ = im.shape\n print(imgheight, imgwidth)\n window_width = window_width\n window_height = window_width #the window height as per aspect ratio of the image, we only give a window width. int(window_width * imgheight/imgwidth)\n\n assert window_width > 0 and window_height > 0, \"Window height and width must be greater than 0. Please check rows and columns values.\"\n h,w,_ = im.shape\n \n #get points of each stride\n x_points = get_slide_points(imgwidth, window_width, overlap=overlap)\n y_points = get_slide_points(imgheight, window_height, overlap=overlap)\n print(len(x_points))\n print(len(y_points))\n count = 0\n for x_counter, i in enumerate(y_points, 1):\n for y_counter,j in enumerate(x_points, 1):\n \n # when generating images without locations, uncomment following code \n #cropped = im[i:i+window_height, j:j+window_width]\n #assert cropped.shape, \"crop failed, please check again\"\n #print(i,j,x_counter,y_counter)\n #print(len(vehicle_locs.values()))\n #try:\n\n #cv2.imwrite(os.path.join(output_directory, newimage_name), cropped)\n #assert os.path.exists(os.path.join(output_directory, newimage_name)), \"Cropped image \"+newimage_name+\" not saved!\"\n# except Exception:\n# raise(Exception())\n file = filename.replace(\"_image\",\"\").replace(\"_\",\"-\")\n newimage_name = file+\"-\"+str(j)+\"-\"+str(i)+\".png\"\n vehicle_locs = get_locations_from_image(i,j,class_loc, window_width,newimage_name)\n \n # Cropped images only if vehicle locations exist for a given cropped image\n if vehicle_locs:\n answers.append(vehicle_locs)\n #print(vehicle_locs, answers)\n count += 1\n cropped = im[i:i+window_height, j:j+window_width]\n assert cropped.shape, \"crop failed, please check again\"\n cv2.imwrite(os.path.join(output_directory, newimage_name), cropped)\n assert os.path.exists(os.path.join(output_directory, newimage_name)), \"Cropped image \"+newimage_name+\" not saved!\"\n #print(i,j,x_counter,y_counter)\n #print(len(vehicle_locs.values()))\n #print(vehicle_locs)\n is_valid = validate_slices_with_vehicles(output_directory, count, (window_width, window_height))\n assert is_valid, \"Validation failed for cropped sub-images! Please check and try again.\"\n return answers",
"_____no_output_____"
]
],
[
[
"### The following cell is for Selwyn dataset ",
"_____no_output_____"
]
],
[
[
"outputdirname = \"task2\"\npath = Path(r'C:\\Users\\exx\\Documents\\lab')\n\n#get new folder's storage entry folder, there on, folders likely similar ?\nfiledir = os.path.join(os.path.join(r'C:\\Users\\exx\\Documents\\lab'), \"LINZ\",\"Final\",\"001_selwyn-0125m-urban-aerial-photos-2012-2013\")\n\nmain_folders = [os.path.join(filedir,name) for name in os.listdir(filedir)]\nfor f in main_folders:\n this_key = None\n \n for root, dir, files in os.walk(f):\n #ignore ipynb_checkpoints folders\n if re.search(\".ipynb_checkpoints\",os.path.basename(Path(root))):\n continue\n if len(dir) != 0:\n #check if Annotation galleries exist\n galleries = [ d for d in dir if re.search(\"\\d+\\sFinal Annotation Galleries\",str(d))]\n #check if main image file exists 000X_000X_image.png exists ?\n image_files = [ file for file in files if re.search(\"\\d+(_)\\d+(_)image.png\",file.lower())]\n annotation_files = [ file for file in files if re.search(\"\\d+(_)\\d+(_)annotations.json\",file)]\n #if dir is empty, we continue\n #valid folders and files exists ?\n if len(galleries) > 0 and len(image_files) > 0 and len(annotation_files)>0: #and \"0001_0001\" in image_files[0]:\n \n #print(root)\n imagefilepath = Path(root).joinpath( image_files[0])\n print(imagefilepath)\n \n foldername = str(os.path.splitext(os.path.basename(imagefilepath))[0]).replace(\"_image\",\"\")\n annotationsfile = Path(root, annotation_files[0])\n \n class_loc, answerdict = add_answers( annotationsfile, image_files[0])\n print(foldername)\n #print(class_loc, answerdict)\n \n if not os.path.exists(os.path.join(path, outputdirname)):\n os.mkdir(os.path.join(path, outputdirname))\n \n outputdirpath = os.path.join(path, outputdirname, \"test4\")\n if not os.path.exists(outputdirpath):\n os.mkdir(outputdirpath)\n p = os.path.join(outputdirpath, foldername)\n if not os.path.exists(p):\n os.mkdir(p)\n # print(\"p\",p,annotationsfile)\n \n answers = sliding_window_with_overlap(imagefilepath,class_loc, p, window_width=300, overlap=0.2)\n #print(answers)\n \n result = pd.DataFrame.from_dict(answers)\n result.to_csv(os.path.join(outputdirpath,foldername+\".csv\"), index=False)",
"C:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0001\\0001\\0001_0001_image.png\n0001_0001\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0001_0001\n11141 24174\n102\n48\n14\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0001_0001 14\n14 14\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0001\\0002\\0001_0002_image.png\n0001_0002\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0001_0002\n13134 23314\n98\n56\n31\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0001_0002 31\n31 31\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0001\\0003\\0001_0003_image.png\n0001_0003\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0001_0003\n12441 14432\n61\n53\n61\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0001_0003 61\n61 61\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0001\\0004\\0001_0004_image.png\n0001_0004\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0001_0004\n12896 14433\n61\n55\n84\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0001_0004 84\n84 84\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0001\\0005\\0001_0005_image.png\n0001_0005\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0001_0005\n15603 12988\n55\n66\n11\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0001_0005 11\n11 11\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0001\\0006\\0001_0006_image.png\n0001_0006\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0001_0006\n18483 12988\n55\n78\n20\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0001_0006 20\n20 20\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0002\\0001\\0002_0001_image.png\n0002_0001\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0002_0001\n36460 11520\n49\n153\n272\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0002_0001 272\n272 272\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0003\\0001\\0003_0001_image.png\n0003_0001\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0003_0001\n12918 17361\n74\n55\n233\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0003_0001 233\n233 233\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0003\\0002\\0003_0002_image.png\n0003_0002\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0003_0002\n12918 19094\n81\n55\n257\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0003_0002 257\n257 257\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0003\\0003\\0003_0003_image.png\n0003_0003\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0003_0003\n13179 18934\n80\n56\n298\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0003_0003 298\n298 298\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0003\\0004\\0003_0004_image.png\n0003_0004\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0003_0004\n13178 19094\n81\n56\n104\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0003_0004 104\n104 104\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0004\\0001\\0004_0001_image.png\n0004_0001\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0001\n16000 16000\n68\n68\n360\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0001 360\n360 360\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0004\\0002\\0004_0002_image.png\n0004_0002\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0002\n16000 13377\n57\n68\n444\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0002 444\n444 444\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0004\\0003\\0004_0003_image.png\n0004_0003\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0003\n13274 16000\n68\n57\n795\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0003 795\n795 795\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0004\\0004\\0004_0004_image.png\n0004_0004\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0004\n13274 13377\n57\n57\n1203\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0004 1203\n1203 1203\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0004\\0005\\0004_0005_image.png\n0004_0005\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0005\n18694 12420\n53\n79\n212\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0005 212\n212 212\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0004\\0006\\0004_0006_image.png\n0004_0006\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0006\n18694 11394\n49\n79\n502\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0006 502\n502 502\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0004\\0007\\0004_0007_image.png\n0004_0007\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0007\n21574 13299\n57\n91\n209\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0004_0007 209\n209 209\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0005\\0001\\0005_0001_image.png\n0005_0001\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0005_0001\n14400 20400\n86\n61\n902\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0005_0001 902\n902 902\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0005\\0002\\0005_0002_image.png\n0005_0002\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0005_0002\n14400 20597\n87\n61\n801\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0005_0002 801\n801 801\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0005\\0003\\0005_0003_image.png\n0005_0003\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0005_0003\n14400 20207\n85\n61\n520\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0005_0003 520\n520 520\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0006\\0001\\0006_0001_image.png\n0006_0001\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0006_0001\n15145 21321\n90\n64\n505\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0006_0001 505\n505 505\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0006\\0002\\0006_0002_image.png\n0006_0002\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0006_0002\n15866 16320\n69\n67\n173\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0006_0002 173\n173 173\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0006\\0003\\0006_0003_image.png\n0006_0003\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0006_0003\n20108 16321\n69\n85\n80\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0006_0003 80\n80 80\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0006\\0004\\0006_0004_image.png\n0006_0004\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0006_0004\n20099 20558\n87\n85\n521\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0006_0004 521\n521 521\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0007\\0001\\0007_0001_image.png\n0007_0001\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0007_0001\n18535 19291\n82\n78\n257\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0007_0001 257\n257 257\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0007\\0002\\0007_0002_image.png\n0007_0002\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0007_0002\n18536 18340\n78\n78\n40\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0007_0002 40\n40 40\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0008\\0001\\0008_0001_image.png\n0008_0001\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0008_0001\n14486 13386\n57\n62\n347\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0008_0001 347\n347 347\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0008\\0002\\0008_0002_image.png\n0008_0002\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0008_0002\n19468 21120\n89\n82\n121\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0008_0002 121\n121 121\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0008\\0003\\0008_0003_image.png\n0008_0003\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0008_0003\n19468 21120\n89\n82\n180\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0008_0003 180\n180 180\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0008\\0004\\0008_0004_image.png\n0008_0004\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0008_0004\n19285 10818\n46\n82\n145\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0008_0004 145\n145 145\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0008\\0005\\0008_0005_image.png\n0008_0005\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0008_0005\n9595 21741\n92\n41\n295\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0008_0005 295\n295 295\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0009\\0001\\0009_0001_image.png\n0009_0001\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0009_0001\n17738 11342\n49\n75\n416\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0009_0001 416\n416 416\nExported sub-images count look good!\nC:\\Users\\exx\\Documents\\lab\\LINZ\\Final\\001_selwyn-0125m-urban-aerial-photos-2012-2013\\0009\\0002\\0009_0002_image.png\n0009_0002\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0009_0002\n17280 14382\n61\n73\n69\nC:\\Users\\exx\\Documents\\lab\\task2\\test4\\0009_0002 69\n69 69\nExported sub-images count look good!\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e720127955d41a8a3962443144cbf52bc65ae82e | 9,203 | ipynb | Jupyter Notebook | 7.16.ipynb | bbqbbq666/Python | 92666be703abf95ff6a527bcfbd9249a03b4d7c8 | [
"Apache-2.0"
] | null | null | null | 7.16.ipynb | bbqbbq666/Python | 92666be703abf95ff6a527bcfbd9249a03b4d7c8 | [
"Apache-2.0"
] | null | null | null | 7.16.ipynb | bbqbbq666/Python | 92666be703abf95ff6a527bcfbd9249a03b4d7c8 | [
"Apache-2.0"
] | null | null | null | 19.415612 | 80 | 0.475062 | [
[
[
"# 基本程序设计\n- 一切代码输入,请使用英文输入法",
"_____no_output_____"
]
],
[
[
"print(\"Hello World!\")",
"Hello World!\n"
]
],
[
[
"## 编写一个简单的程序\n- 圆公式面积: area = radius \\* radius \\* 3.1415",
"_____no_output_____"
],
[
"### 在Python里面不需要定义数据的类型",
"_____no_output_____"
],
[
"## 控制台的读取与输入\n- input 输入进去的是字符串\n- eval",
"_____no_output_____"
],
[
"- 在jupyter用shift + tab 键可以跳出解释文档",
"_____no_output_____"
],
[
"## 变量命名的规范\n- 由字母、数字、下划线构成\n- 不能以数字开头 \\*\n- 标识符不能是关键词(实际上是可以强制改变的,但是对于代码规范而言是极其不适合)\n- 可以是任意长度\n- 驼峰式命名",
"_____no_output_____"
],
[
"## 变量、赋值语句和赋值表达式\n- 变量: 通俗理解为可以变化的量\n- x = 2 \\* x + 1 在数学中是一个方程,而在语言中它是一个表达式\n- test = test + 1 \\* 变量在赋值之前必须有值",
"_____no_output_____"
],
[
"## 同时赋值\nvar1, var2,var3... = exp1,exp2,exp3...",
"_____no_output_____"
],
[
"## 定义常量\n- 常量:表示一种定值标识符,适合于多次使用的场景。比如PI\n- 注意:在其他低级语言中如果定义了常量,那么,该常量是不可以被改变的,但是在Python中一切皆对象,常量也是可以被改变的",
"_____no_output_____"
],
[
"## 数值数据类型和运算符\n- 在Python中有两种数值类型(int 和 float)适用于加减乘除、模、幂次\n<img src = \"../Photo/01.jpg\"></img>",
"_____no_output_____"
],
[
"## 运算符 /、//、**",
"_____no_output_____"
],
[
"## 运算符 %",
"_____no_output_____"
],
[
"## EP:\n- 25/4 多少,如果要将其转变为整数该怎么改写\n- 输入一个数字判断是奇数还是偶数\n- 进阶: 输入一个秒数,写一个程序将其转换成分和秒:例如500秒等于8分20秒\n- 进阶: 如果今天是星期六,那么10天以后是星期几? 提示:每个星期的第0天是星期天",
"_____no_output_____"
],
[
"## 科学计数法\n- 1.234e+2\n- 1.234e-2",
"_____no_output_____"
],
[
"## 计算表达式和运算优先级\n<img src = \"../Photo/02.png\"></img>\n<img src = \"../Photo/03.png\"></img>",
"_____no_output_____"
],
[
"## 增强型赋值运算\n<img src = \"../Photo/04.png\"></img>",
"_____no_output_____"
],
[
"## 类型转换\n- float -> int\n- 四舍五入 round",
"_____no_output_____"
],
[
"## EP:\n- 如果一个年营业税为0.06%,那么对于197.55e+2的年收入,需要交税为多少?(结果保留2为小数)\n- 必须使用科学计数法",
"_____no_output_____"
],
[
"# Project\n- 用Python写一个贷款计算器程序:输入的是月供(monthlyPayment) 输出的是总还款数(totalpayment)\n",
"_____no_output_____"
],
[
"# Homework\n- 1\n<img src=\"../Photo/06.png\"></img>",
"_____no_output_____"
]
],
[
[
"c=float(input('Enter a degree in Celsius:'))\nf=(9/5)*c+32\nprint('%d Celsius is %.1f Fahrenheit'%(c,f))",
"Enter a degree in Celsius:43\n43 Celsius is 109.4 Fahrenheit\n"
]
],
[
[
"- 2\n<img src=\"../Photo/07.png\"></img>",
"_____no_output_____"
]
],
[
[
"import math\nradius,length=eval(input('Enter the radius and length of a cylinder:'))\narea=radius**2*math.pi\nvolume=area*length\nprint('The area is %.4f'%area)\nprint('The volume is %.1f'%volume)",
"Enter the radius and length of a cylinder:5.5,12\nThe area is 95.0332\nThe volume is 1140.4\n"
]
],
[
[
"- 3\n<img src=\"../Photo/08.png\"></img>",
"_____no_output_____"
]
],
[
[
"yc=float(input('Enter a value for feet:'))\nm=float(yc*0.305)\nprint('%.1f feet is %.4f meters'%(yc,m))",
"Enter a value for feet:16.5\n16.500000 feet is 5.0325 meters\n"
]
],
[
[
"- 4\n<img src=\"../Photo/10.png\"></img>",
"_____no_output_____"
]
],
[
[
"M=float(input('Enter the amount of water in kilograms:'))\ninitial=float(input('Enter the initial temperature:'))\nfinal=float(input('Enter the final temperature:'))\nQ=M*(final-initial)*4184\nprint('The energy needed is %.1f'%Q)",
"Enter the amount of water in kilograms:55.5\nEnter the initial temperature:3.5\nEnter the final temperature:10.5\nThe energy needed is 1625484.0\n"
]
],
[
[
"- 5\n<img src=\"../Photo/11.png\"></img>",
"_____no_output_____"
]
],
[
[
"ce,nlv=eval(input('Enter balance and interest rate (e.g., 3 for 3%):'))\nlx=ce*(nlv/1200)\nprint('The interest is %.5f'%lx)",
"Enter balance and interest rate (e.g., 3 for 3%):1000,3.5\nThe interest is 2.91667\n"
]
],
[
[
"- 6\n<img src=\"../Photo/12.png\"></img>",
"_____no_output_____"
]
],
[
[
"v0,v1,t=eval(input('Enter v0, v1 and t:'))\na=(v1-v0)/t\nprint('The average acceleration is %.4f'%a)",
"Enter v0, v1 and t:5.5,50.9,4.5\nThe average acceleration is 10.0889\n"
]
],
[
[
"- 7 进阶\n<img src=\"../Photo/13.png\"></img>",
"_____no_output_____"
]
],
[
[
"money=input('Enter the monthly saving amount:')\nx=1+0.00417\nb=0\nfor a in range(6):\n b=(float(money)+float(b))*x\n\nprint('After the sixth month,the account value is %.2f'%b) ",
"Enter the monthly saving amount:100\nAfter the sixth month,the account value is 608.82\n"
]
],
[
[
"- 8 进阶\n<img src=\"../Photo/14.png\"></img>",
"_____no_output_____"
]
],
[
[
"number=int(input('Enter a number between 0 and 1000:'))\nif(number<10):\n print(number)\nelif(number>=10 and number<100):\n a=int(number/10)\n b=number%10\n print(a+b)\nelif(number>=100 and number<1000):\n x=int(number/100)\n y=int((number/10)%10)\n z=number%10\n print(x+y+z)\nelse :\n print('数值超出范围!!!')",
"Enter a number between 0 and 1000:123\n6\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",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e72030637601ef3467df728cf13a7ac0a3a98173 | 248,051 | ipynb | Jupyter Notebook | 07/integration.ipynb | banjakos/phys105a | 61b18ddb3dbdb0bc3495dfb6159fc9470b3aeac5 | [
"BSD-Source-Code"
] | 3 | 2021-01-14T00:29:24.000Z | 2021-01-26T22:34:22.000Z | 07/integration.ipynb | banjakos/phys105a | 61b18ddb3dbdb0bc3495dfb6159fc9470b3aeac5 | [
"BSD-Source-Code"
] | null | null | null | 07/integration.ipynb | banjakos/phys105a | 61b18ddb3dbdb0bc3495dfb6159fc9470b3aeac5 | [
"BSD-Source-Code"
] | 1 | 2021-04-13T20:03:43.000Z | 2021-04-13T20:03:43.000Z | 232.693246 | 27,312 | 0.913643 | [
[
[
"## PHYS 105A: Introduction to Scientific Computing\n\n# Numerical Integration of Functions\n\nChi-kwan Chan",
"_____no_output_____"
],
[
"## Importance of Integration in Physics\n\n* Physical (dynamic) systems are very often described by ordinary differential equations, examples include Newton's second law:\n $f = m a = m \\frac{dx^2}{dt^2}$.\n \n* For fields, their are described by partial differential equations.\n\n* In order to predict how physical systems behave, we need to integrate these diffrential equations.",
"_____no_output_____"
],
[
"## Nmerical Integration of Functions\n\n* But before we learn how to solve generic ODEs, let's learn a simple special case:\n $I = \\int_a^b f(x) dx$.\n\n* Note that this integration is equivalent to solving for the value $I \\equiv y(b)$ of the differential equation $dy/dx = f(x)$ with the boundary condition $y(a) = 0$.\n\n* By doing so, we will learn the important concept of convergence.",
"_____no_output_____"
],
[
"## Analytical Example\n\n* Numerical integration can help us solve problems without analytical solutions.\n\n* But to help our understanding, we will first use an example with analytical solution.\n\n* Let's consider $f(x) = e^{x}$.\n\n* The indefinite integration is $\\int f(x) dx = e^{x} + C$, where $C$ is a constant.\n\n* The definite integral is $\\int_a^b f(x) dx = e^{b} - e^{a}$.",
"_____no_output_____"
]
],
[
[
"# It is useful to plot the function for visualization.\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef f(x):\n return np.exp(x)\n\nx = np.linspace(0, 1, 129) # define a fine grid for plotting\ny = f(x) # sample function f on the grid\n\nplt.plot(x, y)\nplt.fill_between(x, y, alpha=0.33)",
"_____no_output_____"
]
],
[
[
"## Riemann Sums\n\n* When we first learn about ingegration, we usually learn about the Riemann sum first.\n\n $I \\approx S \\equiv \\sum_{i = 1}^n f(x_i^*) \\Delta x_i$\n \n where $\\Delta x_i = x_i - x_{i-1}$.\n \n* If $x_i^* = x_{i-1}$ for all $i$, then $S$ is called the left Reimann Sum.\n\n* If $x_i^* = x_i$ for all $i$, then $S$ is called the right Reimann Sum.\n\n* If $x_i^* = (x_{i-1} + x_i)/2$ for all $i$, then $S$ is called the middle Reimann Sum.\n\n* There are other Riemann Sums such as the supper and lower Riemann (Darboux) sums. But we won't discuss them here. They are useful for prove mathemtical theories but less useful in numerical analysis.\n\n* In the limit $\\Delta x_i \\rightarrow 0$, the Riemann Sums converge to the integral.",
"_____no_output_____"
]
],
[
[
"# Graphically, this is the left Reimann Sum\n\nX = np.linspace(0, 1, 9) # define a coarse grid for the sum\nY = f(X) # sample function f on the grid\n\nplt.plot(x, y)\nplt.scatter(X[:-1], Y[:-1], color='r')\nplt.fill_between(X, Y, step='post', color='r', alpha=0.33)",
"_____no_output_____"
],
[
"# And this is the right Reimann Sum\n\nplt.plot(x, y)\nplt.scatter(X[1:], Y[1:], color='r')\nplt.fill_between(X, Y, step='pre', color='r', alpha=0.33)",
"_____no_output_____"
],
[
"# And this is the middle Reimann Sum\n\nX = np.linspace(0, 1, 9)\nX = 0.5 * (X[:-1] + X[1:])\nY = f(X)\n\nplt.plot(x, y)\nplt.scatter(X, Y, color='r')\nplt.fill_between(np.concatenate([[0], X, [1]]), \n np.concatenate([Y[:1], Y, Y[-1:]]), \n step='mid', color='r', alpha=0.33)",
"_____no_output_____"
],
[
"# We can easily compute the Riemann sums numerically!\n#\n# Here's the left Riemann sum.\n\nN = 8\nD = 1 / N\nX = [D * i for i in range(N)]\nS = np.sum(f(X) * D)\n\nprint('Left Riemann Sum:', S)\n\n# And we can compare it with the true answer\n\nI = f(1) - f(0)\nprint('Analytical solution:', I)\n\n# The difference is\nprint('Error:', abs(I - S))",
"Left Riemann Sum: 1.6131259778856117\nAnalytical solution: 1.718281828459045\nError: 0.10515585057343335\n"
],
[
"# Here's the right Riemann sum.\n\nN = 8\nD = 1 / N\nX = [D * (i+1) for i in range(N)] # note the (i+1) here\nS = np.sum(f(X) * D)\n\nprint('Right Riemann Sum:', S)\n\n# And we can compare it with the true answer\n\nI = f(1) - f(0)\nprint('Analytical solution:', I)\n\n# The difference is\nprint('Error:', abs(I - S))",
"Right Riemann Sum: 1.827911206442992\nAnalytical solution: 1.718281828459045\nError: 0.10962937798394701\n"
],
[
"# Here's the middle Riemann sum.\n\nN = 8\nD = 1 / N\nX = [D * (i+0.5) for i in range(N)] # note the (i+0.5) here\nS = np.sum(f(X) * D)\n\nprint('Middle Riemann Sum:', S)\n\n# And we can compare it with the true answer\n\nI = f(1) - f(0)\nprint('Analytical solution:', I)\n\n# The difference is\nprint('Error:', abs(I - S))",
"Middle Riemann Sum: 1.717163664995687\nAnalytical solution: 1.718281828459045\nError: 0.001118163463358135\n"
]
],
[
[
"* For this particular case, the middle Riemann sum gives us much accurate solution!\n\n* This may be clear from the figures already.\n\n* However, if we refine the step size, clearly the errors in the left and right Riemann sums will reduce as well.\n\n* How does the error depend on the step size?",
"_____no_output_____"
]
],
[
[
"# Let's define a function with different parameters\n# to compute the different types of Riemann Sum.\n\ndef RiemannSum(f, N=8, a=0, b=1, t='mid'):\n D = (b-a) / N\n if t[0] == 'l':\n X = [D*(i ) + a for i in range(N)]\n elif t[0] == 'r':\n X = [D*(i+1 ) + a for i in range(N)]\n else:\n X = [D*(i+0.5) + a for i in range(N)]\n return np.sum(f(np.array(X))) * D",
"_____no_output_____"
],
[
"# Let's now define a different numbers of grid points.\n\nNs = [8, 16, 32, 64, 128, 256, 512, 1024]\n\n# And compute the Riemann sums using the different methods\nerr_l = [abs(RiemannSum(f, N, t='l') - I) for N in Ns]\nerr_m = [abs(RiemannSum(f, N, t='m') - I) for N in Ns]\nerr_r = [abs(RiemannSum(f, N, t='r') - I) for N in Ns]\n\n# It is cool that the error in the middle Riemann sum, even with\n# only 8 points, is compariable to the left and right Riemann sums\n# using ~ 100 points!\n# It is even more impressive that when we use ~ 1000 points in the\n# middle Riemann sum, the error is just ~ 1e-7!\nplt.loglog(Ns, err_l, '+--', color='r', label='left')\nplt.loglog(Ns, err_m, 'o-', color='g', label='middle')\nplt.loglog(Ns, err_r, 'x:', color='b', label='right')\nplt.xlabel('Number of sampling points')\nplt.ylabel('Absolute errors')\nplt.legend()",
"_____no_output_____"
]
],
[
[
"* It is cool that the error in the middle Riemann sum, even with only 8 points, is compariable to the left and right Riemann sums using ~ 100 points!\n\n* It is even more impressive that when we use ~ 1000 points in the middle Riemann sum, the error is just ~ 1e-7!\n\n* Is this generically true?\n\n* We may create the same convergence plots for different functions.",
"_____no_output_____"
]
],
[
[
"# Test with different functions, this is half cycle of sin()\n\ndef g(x):\n return np.sin(x * np.pi / 2)\n\nX = np.linspace(0, 1, 11)\nX = 0.5 * (X[:-1] + X[1:])\nY = g(X)\n\nplt.plot(x, g(x))\nplt.scatter(X, Y, color='r')\nplt.fill_between(np.concatenate([[0], X, [1]]), \n np.concatenate([Y[:1], Y, Y[-1:]]), \n step='mid', color='r', alpha=0.33)",
"_____no_output_____"
],
[
"# And compute the Riemann sums using the different methods\nerr_l = [abs(RiemannSum(g, N, t='l') - 2 / np.pi) for N in Ns]\nerr_m = [abs(RiemannSum(g, N, t='m') - 2 / np.pi) for N in Ns]\nerr_r = [abs(RiemannSum(g, N, t='r') - 2 / np.pi) for N in Ns]\n\n# It is cool that the error in the middle Riemann sum, even with\n# only 8 points, is compariable to the left and right Riemann sums\n# using ~ 100 points!\n# It is even more impressive that when we use ~ 1000 points in the\n# middle Riemann sum, the error is just ~ 1e-7!\nplt.loglog(Ns, err_l, '+--', color='r', label='left')\nplt.loglog(Ns, err_m, 'o-', color='g', label='middle')\nplt.loglog(Ns, err_r, 'x:', color='b', label='right')\nplt.xlabel('Number of sampling points')\nplt.ylabel('Absolute errors')\nplt.legend()",
"_____no_output_____"
],
[
"# Test with different functions, this is a quarter circle\n\ndef h(x):\n return np.sqrt(1 - x * x)\n\nX = np.linspace(0, 1, 11)\nX = 0.5 * (X[:-1] + X[1:])\nY = h(X)\n\nplt.plot(x, h(x))\nplt.scatter(X, Y, color='r')\nplt.fill_between(np.concatenate([[0], X, [1]]), \n np.concatenate([Y[:1], Y, Y[-1:]]), \n step='mid', color='r', alpha=0.33)\nplt.gca().set_aspect('equal')",
"_____no_output_____"
],
[
"# And compute the Riemann sums using the different methods\nerr_l = [abs(RiemannSum(h, N, t='l') - np.pi/4) for N in Ns]\nerr_m = [abs(RiemannSum(h, N, t='m') - np.pi/4) for N in Ns]\nerr_r = [abs(RiemannSum(h, N, t='r') - np.pi/4) for N in Ns]\n\n# It is cool that the error in the middle Riemann sum, even with\n# only 8 points, is compariable to the left and right Riemann sums\n# using ~ 100 points!\n# It is even more impressive that when we use ~ 1000 points in the\n# middle Riemann sum, the error is just ~ 1e-7!\nplt.loglog(Ns, err_l, '+--', color='r', label='left')\nplt.loglog(Ns, err_m, 'o-', color='g', label='middle')\nplt.loglog(Ns, err_r, 'x:', color='b', label='right')\nplt.xlabel('Number of sampling points')\nplt.ylabel('Absolute errors')\nplt.legend()",
"_____no_output_____"
]
],
[
[
"* Although the detail errors are different for different curves, the general trends are the same.\n\n * When we increase the number of sampling points by 2, or decrease the size of the step by 2, left and right Riemann sums cuts the error by 1/2.\n \n * When we increase the number of sampling points by 2, or decrease the size of the step by 2, middle Riemann sums cuts the error by 1/4!\n \n* In general, we say the middle Riemann sum converge faster than the left and right Riemann sums.\n\n* However, using the different Riemann sum to discuss numerical integration, while it is formally correct, it is difficult to generalize. This is espeically true for the middle Riemann sum that requires a different set of sampling points.\n\n* Starting in the next slide, we will use the notation used in the numerical recipes.",
"_____no_output_____"
],
[
"## Trapezoidal Rule:\n\n* We will now stick with the \"vertex\" formulation, i.e. $x_i = a + i \\Delta x$.\n\n* Instead of considering the middle Reiman sum, we will use the following apprxoimation.\n\n $\\int_{x_0}^{x_1} f(x) dx =\n h \\left[\\frac{1}{2} f_0 + \\frac{1}{2} f_1\\right] + \\mathcal{O}(h^3 f'')$\n \n* This is called the trapezoidal rule.\n\n* The error term $\\mathcal{O}(\\ )$ reprsents that the true answer differs from the estimate by an amount that is proportional to $h^3$ and $f''$.\n\n* If $f$ is linear, i.e., $f'' = 0$, then the trapezoidal is be extract.",
"_____no_output_____"
]
],
[
[
"# Test with different functions, this is a quarter circle\n\nX = np.linspace(0, 1, 3)\nY = g(X)\n\nplt.plot(x, g(x))\nplt.scatter(X, Y, color='r')\nplt.fill_between(X, g(X), color='r', alpha=0.33)",
"_____no_output_____"
],
[
"# We can how program the trapezoidal rule and test it\n\ndef trapezoidal(f, N=8, a=0, b=1):\n X, D = np.linspace(a, b, N+1, retstep=True)\n return np.sum(f(X[1:])+f(X[:-1])) * 0.5 * D\n\n# And compute the Riemann sums using the different methods\nerr_m = [abs(RiemannSum(g, N, t='m') - 2 / np.pi) for N in Ns]\nerr_t = [abs(trapezoidal(g, N) - 2 / np.pi) for N in Ns]\n\nplt.loglog(Ns, err_m, 'o-', color='g', label='middle')\nplt.loglog(Ns, err_t, '+:', color='r', label='trapezoidal')\nplt.xlabel('Number of sampling points')\nplt.ylabel('Absolute errors')\nplt.legend()",
"_____no_output_____"
]
],
[
[
"## Simpson’s Rule\n\n* Given that the trapezoidal rule is extact for lienar functions, i.e., first order polynomials, one natural question is if we can construct a rule that is exact for second order polynomials.\n\n* It turns out that we can. The result is called the Simpson's rule:\n\n $\\int_{x_0}^{x_2} f(x) dx =\n h \\left[\\frac{1}{3} f_0 + \\frac{4}{3} f_1 + \\frac{1}{3} f_2\\right] + \\mathcal{O}(h^5 f^{(4)})$\n \n* Note that this formulate integrate up to $x_2$.\n\n* If we want to integrate to $x_1$ instead, this formulate increase the number of function evaluation.\n \n* The error term $\\mathcal{O}(\\ )$ suggests a much rapider convegent rate.",
"_____no_output_____"
]
],
[
[
"# We can how program the Simpson rule and test it\n\ndef Simpson(f, N=8, a=0, b=1):\n X, D = np.linspace(a, b, N+1, retstep=True)\n S = 0\n for i in range(N//2):\n l = X[2*i]\n m = X[2*i+1]\n r = X[2*i+2]\n S += D * (f(l) + 4*f(m) + f(r)) / 3\n return S\n\n# And compute the Riemann sums using the different methods\nerr_m = [abs(RiemannSum(g, N, t='m') - 2 / np.pi) for N in Ns]\nerr_t = [abs(trapezoidal(g, N) - 2 / np.pi) for N in Ns]\nerr_S = [abs(Simpson(g, N) - 2 / np.pi) for N in Ns]\n\nplt.loglog(Ns, err_m, 'o-', color='g', label='middle')\nplt.loglog(Ns, err_t, '+:', color='r', label='trapezoidal')\nplt.loglog(Ns, err_S, 'x:', color='b', label='Simpson')\n\nplt.xlabel('Number of sampling points')\nplt.ylabel('Absolute errors')\nplt.legend()",
"_____no_output_____"
],
[
"# We can even generalize it to the Bode's rule\n\ndef Bode(f, N=8, a=0, b=1):\n X, D = np.linspace(a, b, N+1, retstep=True)\n S = 0\n for i in range(N//4):\n x0 = X[4*i]\n x1 = X[4*i+1]\n x2 = X[4*i+2]\n x3 = X[4*i+3]\n x4 = X[4*i+4]\n S += D * (14*f(x0) + 64*f(x1) + 24*f(x2) + 64*f(x3) + 14*f(x4)) / 45\n return S\n\n# And compute the Riemann sums using the different methods\nerr_m = [abs(RiemannSum(g, N, t='m') - 2 / np.pi) for N in Ns]\nerr_t = [abs(trapezoidal(g, N) - 2 / np.pi) for N in Ns]\nerr_S = [abs(Simpson(g, N) - 2 / np.pi) for N in Ns]\nerr_B = [abs(Bode(g, N) - 2 / np.pi) for N in Ns]\n\nplt.loglog(Ns, err_m, 'o-', color='g', label='middle')\nplt.loglog(Ns, err_t, '+:', color='r', label='trapezoidal')\nplt.loglog(Ns, err_S, 'x:', color='b', label='Simpson')\nplt.loglog(Ns, err_B, 'o:', color='k', label='Bode')\n\nplt.xlabel('Number of sampling points')\nplt.ylabel('Absolute errors')\nplt.legend()",
"_____no_output_____"
]
],
[
[
"## Final comments\n\n* Based on the previous examples, by increasing the order of the approximations, it is possible to construct numerical integration that converges very rapidly.\n\n* For double precision floating point values, the machine accruacy is $\\sim 10^{-16}$. We saw with Bode's rule, we are already reaching that limit for $\\sim 256$ sampling points.\n\n* In practice, for smooth functions, it is even possible to develop numerical integrators that converge exponentially!\n\n* However, if the function is not smooth, i.e., with discontinuity, then formally the convergent rate is only first order. Hence, refining the sampling points near the discontinuity is the only method to provide accurate integration.\n\n* Also, the approximations we introduce in this lecture includes the *end points* of the function. It will be difficult to apply these numerical methods to, e.g., improper integral, or functions with singularity.\n\n* For the assignment that we will do in two weeks, we will learn how to modify our integrators to exclude the end points, and use them for improper integral and functions with singularity.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
e7203475ba1b9ea42af8ca65f38797565e03875c | 76,931 | ipynb | Jupyter Notebook | demo_nmt_seq2seq.ipynb | wanwanbeen/nn_basic | f743606aaee1a2661f420b59a89210934dadeb81 | [
"MIT"
] | null | null | null | demo_nmt_seq2seq.ipynb | wanwanbeen/nn_basic | f743606aaee1a2661f420b59a89210934dadeb81 | [
"MIT"
] | null | null | null | demo_nmt_seq2seq.ipynb | wanwanbeen/nn_basic | f743606aaee1a2661f420b59a89210934dadeb81 | [
"MIT"
] | null | null | null | 81.581124 | 35,320 | 0.723986 | [
[
[
"# Neural Machine Translation\n\n## Requirements:\n* Python 2.7\n* PyTorch\n* NumPy\n* NLTK\n* Data: download [German-English](http://www.manythings.org/anki/deueng.zip) and extract as deu.txt",
"_____no_output_____"
]
],
[
[
"from io import open\nfrom unicodedata import normalize\nimport string\nimport re\nimport random\nimport os\n\nimport numpy as np\nimport nltk\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\n\nimport matplotlib.pyplot as plt\nimport warnings\n%matplotlib inline\nwarnings.filterwarnings('ignore')\nos.environ['CUDA_VISIBLE_DEVICES']='0'\n\nfile_name = './deu.txt'\ntoken_PAD = 0\ntoken_BEGIN = 1\ntoken_END = 2\nMIN_WORD_COUNT = 10\nMIN_SENTENCE_LENGTH = 3\nMAX_SENTENCE_LENGTH = 30",
"_____no_output_____"
]
],
[
[
"### Define functions to read sentence pairs from deu.txt \n* deu.txt is downloaded and unzipped to current directory",
"_____no_output_____"
]
],
[
[
"#####################################################################################\n# clean sentence string read from deu.txt\n#####################################################################################\ndef clean_string(sentence): \n sentence = normalize('NFD', sentence).encode('ascii', 'ignore').decode('UTF-8')\n sentence = sentence.lower().strip() \n sentence = re.sub(r'[^\\w\\s]', r' ', sentence)\n return ' '.join(sentence.split())\n\n#####################################################################################\n# read sentence pairs from deu.txt and remove too long / too short sentence pairs\n#####################################################################################\ndef read_string(file_name):\n lines = open(file_name, encoding='utf-8').read().strip().split('\\n')\n pairs = [[clean_string(s) for s in l.split('\\t')] for l in lines]\n pairs = [list(reversed(p)) for p in pairs]\n\n pairs_new = []\n for pair in pairs:\n if min([len(pair[0]), len(pair[1])]) > MIN_SENTENCE_LENGTH and \\\n max([len(pair[0]), len(pair[1])]) < MAX_SENTENCE_LENGTH:\n pairs_new.append(pair)\n return np.array(pairs_new), len(pairs), len(pairs_new)\n\n#####################################################################################\n# tokenize German and English vocabulary\n#####################################################################################\nclass tokenizer:\n def __init__(self, name):\n self.name = name\n self.index_dict = {token_BEGIN: \"TBEGIN\", token_END: \"TEND\", token_PAD: \"TPAD\"}\n self.word_dict = {}\n self.word_count = {}\n self.word_num = 3 \n self.trimmed = False\n\n def read_sentences(self, sentences):\n for sentence in sentences:\n for word in sentence.split(' '):\n self.read_word(word)\n\n def read_word(self, word):\n if word not in self.word_dict:\n self.index_dict[self.word_num] = word\n self.word_dict[word] = self.word_num\n self.word_count[word] = 1 \n self.word_num += 1\n else:\n self.word_count[word] += 1 \n \n def trim_word(self, min_count):\n if self.trimmed: return\n self.trimmed = True \n keep_words = []\n \n for k, v in self.word_count.items():\n if v >= min_count:\n keep_words.append(k)\n \n self.index_dict = {token_BEGIN: \"TBEGIN\", token_END: \"TEND\", token_PAD: \"TPAD\"}\n self.word_dict = {} \n self.word_count = {}\n self.word_num = 3 \n\n for word in keep_words:\n self.read_word(word)\n\n#####################################################################################\n# remove sentence pairs with rare words\n#####################################################################################\ndef clean_pairs(pairs, input_lang, output_lang):\n keep_pairs = np.zeros(pairs.shape[0])\n for i in range(pairs.shape[0]):\n input_sentence = pairs[i,0]\n output_sentence = pairs[i,1]\n keep_input = True\n keep_output = True\n for word in input_sentence.split(' '):\n if word not in input_lang.word_dict:\n keep_input = False\n break\n for word in output_sentence.split(' '):\n if word not in output_lang.word_dict:\n keep_output = False\n break\n if keep_input and keep_output:\n keep_pairs[i] = 1\n return np.squeeze(pairs[np.argwhere(keep_pairs == 1), :])",
"_____no_output_____"
]
],
[
[
"### Display number of pairs processed, and split into train vs. validation vs. test\n* sentences too long / too short / have rare words are removed",
"_____no_output_____"
]
],
[
[
"pairs, size_ori, size_new = read_string(file_name)\nprint('Read and select sentences with: {} < sentence length < {}'.format(MIN_SENTENCE_LENGTH, MAX_SENTENCE_LENGTH))\nprint('Original number of total pairs = {}'.format(size_ori))\nprint('Selected number of total pairs = {}'.format(size_new))\n\ninput_lang = tokenizer('German')\ninput_lang.read_sentences(pairs[:, 0])\noutput_lang = tokenizer('English')\noutput_lang.read_sentences(pairs[:, 1])\nprint('------------------------------------')\nprint('{}: original vocabulary size = {}'.format(input_lang.name, input_lang.word_num))\nprint('{}: original vocabulary size = {}'.format(output_lang.name, output_lang.word_num))\n\ninput_lang.trim_word(MIN_WORD_COUNT)\noutput_lang.trim_word(MIN_WORD_COUNT)\nprint('------------------------------------')\nprint('Remove sentences with rare words (count < {})'.format(MIN_WORD_COUNT))\nprint('{}: trimmed vocabulary size = {}'.format(input_lang.name, input_lang.word_num))\nprint('{}: trimmed vocabulary size = {}'.format(output_lang.name, output_lang.word_num))\n\npairs = clean_pairs(pairs, input_lang, output_lang)\nnp.random.seed(0)\nrandord = np.random.permutation(range(pairs.shape[0])).tolist()\npairs_train = pairs[randord[:int(pairs.shape[0]*0.6)],:]\npairs_val = pairs[randord[int(pairs.shape[0]*0.6):int(pairs.shape[0]*0.8)],:]\npairs_test = pairs[randord[int(pairs.shape[0]*0.8):],:]\n\nprint('------------------------------------')\nprint('Trimmed Number of total pairs = {}'.format(pairs.shape[0]))\nprint('Number of training pairs = {}'.format(pairs_train.shape[0]))\nprint('Number of validation pairs = {}'.format(pairs_val.shape[0]))\nprint('Number of test pairs = {}'.format(pairs_test.shape[0]))",
"Read and select sentences with: 3 < sentence length < 30\nOriginal number of total pairs = 159204\nSelected number of total pairs = 52711\n------------------------------------\nGerman: original vocabulary size = 11405\nEnglish: original vocabulary size = 7207\n------------------------------------\nRemove sentences with rare words (count < 10)\nGerman: trimmed vocabulary size = 1889\nEnglish: trimmed vocabulary size = 1651\n------------------------------------\nTrimmed Number of total pairs = 30679\nNumber of training pairs = 18407\nNumber of validation pairs = 6136\nNumber of test pairs = 6136\n"
]
],
[
[
"### Define functions to pad sentences for training mini batch",
"_____no_output_____"
]
],
[
[
"#####################################################################################\n# convert sentence words into a list of indexes\n#####################################################################################\ndef sentence_index(lang, sentence):\n return [lang.word_dict[word] for word in sentence.split(' ')] + [token_END]\n\n#####################################################################################\n# pad sentence for mini batch training\n#####################################################################################\ndef sentence_padding(sentence, max_length):\n sentence += [token_PAD for i in range(max_length - len(sentence))]\n return sentence\n\n#####################################################################################\n# generate random batch for training\n#####################################################################################\ndef batch_generator(pairs, batch_size):\n input_seqs = []\n output_seqs = []\n for i in range(batch_size):\n pair = random.choice(pairs)\n input_seqs.append(sentence_index(input_lang, pair[0]))\n output_seqs.append(sentence_index(output_lang, pair[1]))\n \n seq_pairs = sorted(zip(input_seqs, output_seqs), key=lambda p: len(p[0]), reverse=True)\n input_seqs, output_seqs = zip(*seq_pairs)\n \n input_lengths = [len(s) for s in input_seqs]\n output_lengths = [len(s) for s in output_seqs]\n input_seqs = [sentence_padding(s, max(input_lengths)) for s in input_seqs]\n output_seqs = [sentence_padding(s, max(output_lengths)) for s in output_seqs]\n\n input_batch = Variable(torch.LongTensor(input_seqs)).transpose(0, 1).cuda()\n output_batch = Variable(torch.LongTensor(output_seqs)).transpose(0, 1).cuda()\n \n return input_batch, input_lengths, output_batch, output_lengths\n\n#####################################################################################\n# identify sentence before padding\n#####################################################################################\ndef sentence_mask(sentence_length, max_len=None):\n if max_len is None:\n max_len = sentence_length.data.max()\n batch_size = sentence_length.size(0)\n seq_range = torch.range(0, max_len - 1).long()\n seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, max_len)\n seq_range_expand = Variable(seq_range_expand)\n if sentence_length.is_cuda:\n seq_range_expand = seq_range_expand.cuda()\n seq_length_expand = (sentence_length.unsqueeze(1)\n .expand_as(seq_range_expand))\n return seq_range_expand < seq_length_expand\n\n#####################################################################################\n# compute cross_entropy loss on unpadded sentence\n#####################################################################################\ndef sentence_cross_entropy(logits, target, length):\n length = Variable(torch.LongTensor(length)).cuda()\n logits_flat = logits.view(-1, logits.size(-1))\n log_probs_flat = F.log_softmax(logits_flat, dim=1)\n target_flat = target.view(-1, 1)\n losses_flat = -torch.gather(log_probs_flat, dim=1, index=target_flat)\n losses = losses_flat.view(*target.size())\n mask = sentence_mask(sentence_length=length, max_len=target.size(1))\n losses = losses * mask.float()\n loss = losses.sum() / length.float().sum()\n return loss",
"_____no_output_____"
]
],
[
[
"### Define encoder",
"_____no_output_____"
]
],
[
[
"#####################################################################################\n# define encoder: \n# word embedding -> lstm\n#####################################################################################\n# encoder model\nclass Encoder(nn.Module):\n def __init__(self, input_size, hidden_size, n_layers=1, dropout=0.1):\n super(Encoder, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.n_layers = n_layers\n self.dropout = dropout\n \n self.embedding = nn.Embedding(input_size, hidden_size)\n self.lstm = nn.LSTM(hidden_size, hidden_size, n_layers, dropout=self.dropout, bidirectional=True)\n \n def forward(self, input_batch, input_lengths):\n embedded = self.embedding(input_batch)\n packed = torch.nn.utils.rnn.pack_padded_sequence(embedded, input_lengths)\n outputs, hidden = self.lstm(packed)\n outputs, output_lengths = torch.nn.utils.rnn.pad_packed_sequence(outputs) \n outputs = outputs[:, :, :self.hidden_size] + outputs[:, : ,self.hidden_size:] \n return outputs, hidden",
"_____no_output_____"
]
],
[
[
"### Define decoder with attention",
"_____no_output_____"
]
],
[
[
"#####################################################################################\n# define decoder: \n# ((word embedding -> lstm) + encoder output)-> attention -> concat -> relu -> fc\n#####################################################################################\n# attention model\nclass Attention(nn.Module):\n def __init__(self, method_name, hidden_size):\n super(Attention, self).__init__() \n self.method_name = method_name\n self.hidden_size = hidden_size\n self.attention = nn.Linear(self.hidden_size, hidden_size)\n self.v = nn.Parameter(torch.FloatTensor(1, hidden_size))\n\n def forward(self, hidden, encoder_outputs):\n max_length = encoder_outputs.size(0)\n batch_size = encoder_outputs.size(1)\n\n attention_energy = Variable(torch.zeros(batch_size, max_length)).cuda()\n for nb in range(batch_size):\n for nl in range(max_length):\n attention_energy[nb, nl] = self.score(hidden[:, nb], encoder_outputs[nl, nb].unsqueeze(0))\n return F.softmax(attention_energy).unsqueeze(1)\n \n def score(self, hidden, encoder_output): \n if self.method_name == 'general': \n energy = hidden.dot(self.attention(encoder_output)) \n elif self.method_name == 'concat':\n self.attention = nn.Linear(self.hidden_size * 2, hidden_size)\n energy = self.v.dot(self.attention(torch.cat((hidden, encoder_output), 1)))\n else:\n energy = hidden.dot(encoder_output) \n return energy\n\n# decoder model\nclass Decoder(nn.Module):\n def __init__(self, attention_method, hidden_size, output_size, n_layers=1, dropout=0.1):\n super(Decoder, self).__init__()\n\n self.attention_method = attention_method\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n self.dropout = dropout\n\n self.embedding = nn.Embedding(output_size, hidden_size)\n self.lstm = nn.LSTM(hidden_size, hidden_size, n_layers, dropout=dropout)\n self.attention = Attention(attention_method, hidden_size)\n self.fc1 = nn.Linear(hidden_size * 2, hidden_size)\n self.relu = nn.ReLU(inplace=True)\n self.fc2 = nn.Linear(hidden_size, output_size)\n\n def forward(self, input_batch, last_hidden, encoder_outputs):\n\n batch_size = input_batch.size(0)\n embedded = self.embedding(input_batch).view(1, batch_size, self.hidden_size) \n \n rnn_output, hidden = self.lstm(embedded, last_hidden)\n\n attention_weights = self.attention(rnn_output, encoder_outputs)\n context = attention_weights.bmm(encoder_outputs.transpose(0, 1)) \n\n rnn_output = rnn_output.squeeze(0) \n context = context.squeeze(1) \n concat_input = torch.cat((rnn_output, context), 1)\n concat_output = self.relu(self.fc1(concat_input))\n\n output = self.fc2(concat_output)\n return output, hidden, attention_weights",
"_____no_output_____"
]
],
[
[
"### Define training function",
"_____no_output_____"
]
],
[
[
"#####################################################################################\n# define training: use teacher forcing for training\n#####################################################################################\ndef train(input_batch, input_lengths, output_batch, output_lengths, \n encoder, decoder, encoder_optimizer, decoder_optimizer, criterion):\n \n loss = 0 \n encoder_optimizer.zero_grad()\n decoder_optimizer.zero_grad()\n \n encoder_outputs, encoder_hidden = encoder(input_batch, input_lengths)\n decoder_input = Variable(torch.LongTensor([token_BEGIN] * batch_size)).cuda()\n decoder_hidden = (encoder_hidden[0][:decoder.n_layers], encoder_hidden[1][:decoder.n_layers])\n\n max_output_length = max(output_lengths)\n all_decoder_outputs = Variable(torch.zeros(max_output_length, batch_size, decoder.output_size)).cuda()\n\n for t in range(max_output_length):\n decoder_output, decoder_hidden, decoder_Attention = decoder(decoder_input, decoder_hidden, encoder_outputs)\n all_decoder_outputs[t] = decoder_output\n decoder_input = output_batch[t] \n\n loss = sentence_cross_entropy(\n all_decoder_outputs.transpose(0, 1).contiguous(), \n output_batch.transpose(0, 1).contiguous(), \n output_lengths\n )\n loss.backward() \n encoder_optimizer.step()\n decoder_optimizer.step()\n \n return loss.data[0]",
"_____no_output_____"
]
],
[
[
"### Define evaluatioin function",
"_____no_output_____"
]
],
[
[
"#####################################################################################\n# define evaluation function: record loss and bleu score\n#####################################################################################\ndef evaluate(input_lang, output_lang, pairs, encoder, decoder, max_length = MAX_SENTENCE_LENGTH):\n \n output_sentences = []\n bleu_scores = []\n losses = []\n for pair in pairs:\n\n input_batch = [sentence_index(input_lang, pair[0])]\n input_lengths = [len(s) for s in input_batch]\n input_batch = Variable(torch.LongTensor(input_batch), volatile=True).transpose(0, 1).cuda()\n\n output_batch = [sentence_index(output_lang, pair[1])]\n output_lengths = [len(s) for s in output_batch] \n output_batch = [sentence_padding(s, max_length) for s in output_batch]\n output_batch = Variable(torch.LongTensor(output_batch), volatile=True).transpose(0, 1).cuda()\n\n encoder.train(False)\n decoder.train(False)\n\n encoder_outputs, encoder_hidden = encoder(input_batch, input_lengths)\n decoder_input = Variable(torch.LongTensor([token_BEGIN]), volatile=True).cuda()\n decoder_hidden = (encoder_hidden[0][:decoder.n_layers], encoder_hidden[1][:decoder.n_layers])\n\n decoded_words = []\n decoder_attentions = torch.zeros(max_length + 1, max_length + 1)\n all_decoder_outputs = Variable(torch.zeros(max_length, 1, decoder.output_size)).cuda()\n\n for n_curr in range(max_length):\n decoder_output, decoder_hidden, _ = decoder(decoder_input, decoder_hidden, encoder_outputs)\n all_decoder_outputs[n_curr] = decoder_output\n\n _, top_index = decoder_output.data.topk(1)\n index_curr = top_index[0][0]\n if index_curr == token_END:\n decoded_words.append('TEND')\n break\n else:\n decoded_words.append(output_lang.index_dict[index_curr])\n\n decoder_input = Variable(torch.LongTensor([index_curr])).cuda()\n\n loss = sentence_cross_entropy(all_decoder_outputs.transpose(0, 1).contiguous(),\n output_batch.transpose(0, 1).contiguous(), output_lengths)\n\n encoder.train(True)\n decoder.train(True)\n \n output_sentence = ' '.join(decoded_words[:-1])\n output_sentences.append(output_sentence)\n reference = [pair[1].split(' ')]\n hypothesis = output_sentence.split(' ')\n bleu_scores.append(nltk.translate.bleu_score.sentence_bleu(reference,hypothesis)) \n losses.append(loss.data[0])\n \n return output_sentences, losses, bleu_scores",
"_____no_output_____"
]
],
[
[
"### Define hyperparameters and initialize model\n* print summary of encoder and decoder",
"_____no_output_____"
]
],
[
[
"attention_method = 'general'\nhidden_size = 256\nn_layers = 2\ndropout = 0.1\nbatch_size = 300\n\nencoder_learning_rate = 0.001\ndecoder_learning_rate = 0.005\nn_epochs = 100\niter_epoch = 10 \niter_max = n_epochs * iter_epoch\n\n# initialize models\nencoder = Encoder(input_lang.word_num, hidden_size, n_layers, dropout=dropout).cuda()\ndecoder = Decoder(attention_method, hidden_size, output_lang.word_num, n_layers, dropout=dropout).cuda()\n\n# initialize optimizers and criterion\nencoder_optimizer = optim.Adam(encoder.parameters(), lr=encoder_learning_rate)\ndecoder_optimizer = optim.Adam(decoder.parameters(), lr=decoder_learning_rate)\ncriterion = nn.CrossEntropyLoss()\n\nprint(encoder)\nprint(decoder)",
"Encoder(\n (embedding): Embedding(1889, 256)\n (lstm): LSTM(256, 256, num_layers=2, dropout=0.1, bidirectional=True)\n)\nDecoder(\n (embedding): Embedding(1651, 256)\n (lstm): LSTM(256, 256, num_layers=2, dropout=0.1)\n (attention): Attention(\n (attention): Linear(in_features=256, out_features=256, bias=True)\n )\n (fc1): Linear(in_features=512, out_features=256, bias=True)\n (relu): ReLU(inplace)\n (fc2): Linear(in_features=256, out_features=1651, bias=True)\n)\n"
]
],
[
[
"### Begin training",
"_____no_output_____"
]
],
[
[
"#####################################################################################\n# training process:\n# save best models of encoder and decoder, based on validation loss\n#####################################################################################\nLOSS_train = []\nBLEU_train = []\nLOSS_val = []\nBLEU_val = []\n\nniter = 0\nhistory_loss_best = 10**6\nhistory_tolerance = 0\nbest_epoch = 0\n\nwhile niter < iter_max: \n input_batch, input_lengths, output_batch, output_lengths = batch_generator(pairs_train, batch_size)\n loss_curr = train(input_batch, input_lengths, output_batch, output_lengths,\n encoder, decoder, encoder_optimizer, decoder_optimizer, criterion)\n \n if niter % iter_epoch == 0:\n _, loss_train, bleu_train = evaluate(\n input_lang, output_lang, pairs_train, encoder, decoder, MAX_SENTENCE_LENGTH) \n _, loss_val, bleu_val = evaluate(\n input_lang, output_lang, pairs_val, encoder, decoder, MAX_SENTENCE_LENGTH) \n \n LOSS_train.append(sum(loss_train)/len(loss_train))\n BLEU_train.append(sum(bleu_train)/len(bleu_train))\n LOSS_val.append(sum(loss_val)/len(loss_val))\n BLEU_val.append(sum(bleu_val)/len(bleu_val))\n \n nepoch = niter/iter_epoch\n \n if nepoch > 20 and LOSS_val[nepoch] < history_loss_best and history_tolerance <= 10:\n torch.save(encoder.state_dict(), './model_encoder.pt')\n torch.save(decoder.state_dict(), './model_decoder.pt')\n history_loss_best = LOSS_val[nepoch] \n history_tolerance = 0\n best_epoch = nepoch\n print('Epoch {} train loss = {:.2f} bleu = {:.3f} | val loss = {:.2f} bleu = {:.3f} best model!'.format(\n nepoch, LOSS_train[-1], BLEU_train[-1], LOSS_val[-1], BLEU_val[-1]))\n else:\n if nepoch > 20: history_tolerance += 1\n print('Epoch {} train loss = {:.2f} bleu = {:.3f} | val loss = {:.2f} bleu = {:.3f}'.format(\n nepoch, LOSS_train[-1], BLEU_train[-1], LOSS_val[-1], BLEU_val[-1]))\n \n niter += 1",
"Epoch 0 train loss = 7.36 bleu = 0.048 | val loss = 7.37 bleu = 0.045\nEpoch 1 train loss = 6.36 bleu = 0.023 | val loss = 6.38 bleu = 0.022\nEpoch 2 train loss = 5.71 bleu = 0.247 | val loss = 5.75 bleu = 0.242\nEpoch 3 train loss = 5.34 bleu = 0.344 | val loss = 5.40 bleu = 0.340\nEpoch 4 train loss = 5.09 bleu = 0.410 | val loss = 5.15 bleu = 0.404\nEpoch 5 train loss = 4.69 bleu = 0.497 | val loss = 4.77 bleu = 0.485\nEpoch 6 train loss = 4.37 bleu = 0.542 | val loss = 4.44 bleu = 0.536\nEpoch 7 train loss = 4.12 bleu = 0.569 | val loss = 4.23 bleu = 0.563\nEpoch 8 train loss = 4.07 bleu = 0.576 | val loss = 4.19 bleu = 0.571\nEpoch 9 train loss = 3.90 bleu = 0.583 | val loss = 4.07 bleu = 0.578\nEpoch 10 train loss = 3.68 bleu = 0.600 | val loss = 3.87 bleu = 0.591\nEpoch 11 train loss = 3.60 bleu = 0.605 | val loss = 3.82 bleu = 0.597\nEpoch 12 train loss = 3.42 bleu = 0.620 | val loss = 3.69 bleu = 0.610\nEpoch 13 train loss = 3.27 bleu = 0.630 | val loss = 3.57 bleu = 0.618\nEpoch 14 train loss = 3.18 bleu = 0.641 | val loss = 3.55 bleu = 0.624\nEpoch 15 train loss = 2.93 bleu = 0.660 | val loss = 3.35 bleu = 0.638\nEpoch 16 train loss = 2.92 bleu = 0.666 | val loss = 3.41 bleu = 0.638\nEpoch 17 train loss = 2.71 bleu = 0.679 | val loss = 3.22 bleu = 0.655\nEpoch 18 train loss = 2.66 bleu = 0.688 | val loss = 3.25 bleu = 0.652\nEpoch 19 train loss = 2.48 bleu = 0.700 | val loss = 3.08 bleu = 0.663\nEpoch 20 train loss = 2.42 bleu = 0.708 | val loss = 3.08 bleu = 0.665\nEpoch 21 train loss = 2.36 bleu = 0.719 | val loss = 3.14 bleu = 0.673 best model!\nEpoch 22 train loss = 2.30 bleu = 0.730 | val loss = 3.07 bleu = 0.683 best model!\nEpoch 23 train loss = 2.26 bleu = 0.732 | val loss = 3.06 bleu = 0.678 best model!\nEpoch 24 train loss = 2.08 bleu = 0.745 | val loss = 2.94 bleu = 0.689 best model!\nEpoch 25 train loss = 2.05 bleu = 0.755 | val loss = 3.01 bleu = 0.689\nEpoch 26 train loss = 2.02 bleu = 0.762 | val loss = 3.01 bleu = 0.695\nEpoch 27 train loss = 1.92 bleu = 0.768 | val loss = 2.98 bleu = 0.700\nEpoch 28 train loss = 1.93 bleu = 0.772 | val loss = 3.01 bleu = 0.697\nEpoch 29 train loss = 1.85 bleu = 0.778 | val loss = 3.00 bleu = 0.700\nEpoch 30 train loss = 1.76 bleu = 0.789 | val loss = 2.97 bleu = 0.705\nEpoch 31 train loss = 1.72 bleu = 0.793 | val loss = 2.97 bleu = 0.705\nEpoch 32 train loss = 1.72 bleu = 0.798 | val loss = 3.00 bleu = 0.708\nEpoch 33 train loss = 1.66 bleu = 0.806 | val loss = 3.01 bleu = 0.710\nEpoch 34 train loss = 1.62 bleu = 0.809 | val loss = 3.05 bleu = 0.707\nEpoch 35 train loss = 1.58 bleu = 0.816 | val loss = 3.08 bleu = 0.709\nEpoch 36 train loss = 1.56 bleu = 0.817 | val loss = 3.08 bleu = 0.711\nEpoch 37 train loss = 1.51 bleu = 0.824 | val loss = 3.03 bleu = 0.713\nEpoch 38 train loss = 1.47 bleu = 0.828 | val loss = 3.05 bleu = 0.717\nEpoch 39 train loss = 1.45 bleu = 0.829 | val loss = 3.08 bleu = 0.719\nEpoch 40 train loss = 1.36 bleu = 0.837 | val loss = 3.08 bleu = 0.717\nEpoch 41 train loss = 1.36 bleu = 0.837 | val loss = 3.09 bleu = 0.718\nEpoch 42 train loss = 1.32 bleu = 0.845 | val loss = 3.11 bleu = 0.717\nEpoch 43 train loss = 1.33 bleu = 0.845 | val loss = 3.10 bleu = 0.716\nEpoch 44 train loss = 1.28 bleu = 0.850 | val loss = 3.14 bleu = 0.722\nEpoch 45 train loss = 1.24 bleu = 0.852 | val loss = 3.10 bleu = 0.720\nEpoch 46 train loss = 1.17 bleu = 0.861 | val loss = 3.14 bleu = 0.724\nEpoch 47 train loss = 1.16 bleu = 0.866 | val loss = 3.12 bleu = 0.721\nEpoch 48 train loss = 1.15 bleu = 0.866 | val loss = 3.18 bleu = 0.722\nEpoch 49 train loss = 1.08 bleu = 0.875 | val loss = 3.18 bleu = 0.725\nEpoch 50 train loss = 1.10 bleu = 0.873 | val loss = 3.28 bleu = 0.726\nEpoch 51 train loss = 1.08 bleu = 0.874 | val loss = 3.28 bleu = 0.719\nEpoch 52 train loss = 1.05 bleu = 0.877 | val loss = 3.17 bleu = 0.724\nEpoch 53 train loss = 1.04 bleu = 0.880 | val loss = 3.26 bleu = 0.720\nEpoch 54 train loss = 1.00 bleu = 0.881 | val loss = 3.20 bleu = 0.724\nEpoch 55 train loss = 0.98 bleu = 0.887 | val loss = 3.25 bleu = 0.725\nEpoch 56 train loss = 0.94 bleu = 0.891 | val loss = 3.30 bleu = 0.723\nEpoch 57 train loss = 0.97 bleu = 0.891 | val loss = 3.29 bleu = 0.724\nEpoch 58 train loss = 0.93 bleu = 0.894 | val loss = 3.33 bleu = 0.724\nEpoch 59 train loss = 0.90 bleu = 0.897 | val loss = 3.29 bleu = 0.723\nEpoch 60 train loss = 0.92 bleu = 0.901 | val loss = 3.37 bleu = 0.728\nEpoch 61 train loss = 0.87 bleu = 0.904 | val loss = 3.43 bleu = 0.726\nEpoch 62 train loss = 0.84 bleu = 0.904 | val loss = 3.44 bleu = 0.722\nEpoch 63 train loss = 0.82 bleu = 0.909 | val loss = 3.39 bleu = 0.724\nEpoch 64 train loss = 0.79 bleu = 0.913 | val loss = 3.39 bleu = 0.727\nEpoch 65 train loss = 0.86 bleu = 0.907 | val loss = 3.46 bleu = 0.723\nEpoch 66 train loss = 0.81 bleu = 0.910 | val loss = 3.45 bleu = 0.730\nEpoch 67 train loss = 0.81 bleu = 0.911 | val loss = 3.45 bleu = 0.726\nEpoch 68 train loss = 0.83 bleu = 0.911 | val loss = 3.50 bleu = 0.725\nEpoch 69 train loss = 0.81 bleu = 0.913 | val loss = 3.51 bleu = 0.724\nEpoch 70 train loss = 0.82 bleu = 0.913 | val loss = 3.54 bleu = 0.727\nEpoch 71 train loss = 0.79 bleu = 0.913 | val loss = 3.51 bleu = 0.724\nEpoch 72 train loss = 0.77 bleu = 0.916 | val loss = 3.52 bleu = 0.727\nEpoch 73 train loss = 0.75 bleu = 0.920 | val loss = 3.55 bleu = 0.727\nEpoch 74 train loss = 0.75 bleu = 0.919 | val loss = 3.59 bleu = 0.726\nEpoch 75 train loss = 0.73 bleu = 0.924 | val loss = 3.53 bleu = 0.729\nEpoch 76 train loss = 0.74 bleu = 0.921 | val loss = 3.65 bleu = 0.729\nEpoch 77 train loss = 0.71 bleu = 0.923 | val loss = 3.55 bleu = 0.732\nEpoch 78 train loss = 0.65 bleu = 0.928 | val loss = 3.58 bleu = 0.732\nEpoch 79 train loss = 0.69 bleu = 0.929 | val loss = 3.58 bleu = 0.729\nEpoch 80 train loss = 0.67 bleu = 0.929 | val loss = 3.66 bleu = 0.730\nEpoch 81 train loss = 0.67 bleu = 0.930 | val loss = 3.60 bleu = 0.730\nEpoch 82 train loss = 0.69 bleu = 0.927 | val loss = 3.64 bleu = 0.725\nEpoch 83 train loss = 0.68 bleu = 0.928 | val loss = 3.54 bleu = 0.731\nEpoch 84 train loss = 0.67 bleu = 0.928 | val loss = 3.61 bleu = 0.728\nEpoch 85 train loss = 0.66 bleu = 0.930 | val loss = 3.65 bleu = 0.728\nEpoch 86 train loss = 0.65 bleu = 0.931 | val loss = 3.64 bleu = 0.729\nEpoch 87 train loss = 0.68 bleu = 0.929 | val loss = 3.74 bleu = 0.727\nEpoch 88 train loss = 0.67 bleu = 0.930 | val loss = 3.72 bleu = 0.728\nEpoch 89 train loss = 0.65 bleu = 0.933 | val loss = 3.71 bleu = 0.731\nEpoch 90 train loss = 0.62 bleu = 0.936 | val loss = 3.70 bleu = 0.730\nEpoch 91 train loss = 0.61 bleu = 0.939 | val loss = 3.69 bleu = 0.728\nEpoch 92 train loss = 0.59 bleu = 0.940 | val loss = 3.71 bleu = 0.730\nEpoch 93 train loss = 0.59 bleu = 0.939 | val loss = 3.72 bleu = 0.729\nEpoch 94 train loss = 0.59 bleu = 0.939 | val loss = 3.72 bleu = 0.730\nEpoch 95 train loss = 0.57 bleu = 0.941 | val loss = 3.70 bleu = 0.731\nEpoch 96 train loss = 0.59 bleu = 0.938 | val loss = 3.72 bleu = 0.728\nEpoch 97 train loss = 0.56 bleu = 0.941 | val loss = 3.71 bleu = 0.731\nEpoch 98 train loss = 0.59 bleu = 0.940 | val loss = 3.73 bleu = 0.732\nEpoch 99 train loss = 0.56 bleu = 0.942 | val loss = 3.78 bleu = 0.732\n"
]
],
[
[
"### Plot training vs. validation loss",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(12, 5))\nplt.subplot(121)\nplt.plot(range(n_epochs), LOSS_train, 'ro-', label='Training')\nplt.plot(range(n_epochs), LOSS_val, 'gd-', label='Validation')\nplt.title('Loss vs. Epoch')\nplt.xlabel('Number of Epoch')\nplt.ylabel('Loss')\nplt.grid()\nplt.legend()\nplt.subplot(122)\nplt.plot(range(n_epochs), BLEU_train, 'ro-', label='Training')\nplt.plot(range(n_epochs), BLEU_val, 'gd-', label='Validation')\nplt.title('BLEU vs. Epoch')\nplt.xlabel('Number of Epoch')\nplt.ylabel('BLEU')\nplt.grid()\nplt.legend()",
"_____no_output_____"
]
],
[
[
"### Begin evaluating",
"_____no_output_____"
]
],
[
[
"#####################################################################################\n# test process:\n# evaluate on test set using the best models saved\n#####################################################################################\nencoder.load_state_dict(torch.load('./model_encoder.pt'))\ndecoder.load_state_dict(torch.load('./model_decoder.pt'))\noutput_sentences, loss_test, bleu_test = evaluate(\n input_lang, output_lang, pairs_test, encoder, decoder, MAX_SENTENCE_LENGTH) \n\nprint(\"Test loss = {}\".format(sum(loss_test)/len(loss_test)))\nprint(\"Test BLEU = {:.3f}\".format(sum(bleu_test)/len(bleu_test)))\n\nloss_sort = np.argsort(loss_test)\nfor example in range(5):\n sentence_german = pairs_test[loss_sort[example],0]\n sentence_english = pairs_test[loss_sort[example],1]\n sentence_translated = output_sentences[loss_sort[example]]\n print('Example #{}'.format(example+1))\n print('Input German = {}'.format(sentence_german))\n print('Reference English = {}'.format(sentence_english))\n print('Translated English = {}'.format(sentence_translated))",
"Test loss = 2.99136037543\nTest BLEU = 0.685\nExample #1\nInput German = weit du wo er wohnt\nReference English = do you know where he lives\nTranslated English = do you know where he lives\nExample #2\nInput German = wisst ihr wo er wohnt\nReference English = do you know where he lives\nTranslated English = do you know where he lives\nExample #3\nInput German = wo hast du tom gefunden\nReference English = where did you find tom\nTranslated English = where did you find tom\nExample #4\nInput German = bist du wach\nReference English = are you awake\nTranslated English = are you awake\nExample #5\nInput German = ich brauche ein neues auto\nReference English = i need a new car\nTranslated English = i need a new car\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7204bd250076c54d814eff8ed8c0d8f8d3b273c | 121,766 | ipynb | Jupyter Notebook | docs/examples/15_minutes_to_QCoDeS.ipynb | jakeogh/Qcodes | 3042317038e89264d481b212c9640c4d6b356c88 | [
"MIT"
] | null | null | null | docs/examples/15_minutes_to_QCoDeS.ipynb | jakeogh/Qcodes | 3042317038e89264d481b212c9640c4d6b356c88 | [
"MIT"
] | 1 | 2022-03-01T10:15:12.000Z | 2022-03-01T10:15:12.000Z | docs/examples/15_minutes_to_QCoDeS.ipynb | jakeogh/Qcodes | 3042317038e89264d481b212c9640c4d6b356c88 | [
"MIT"
] | null | null | null | 73.044991 | 17,084 | 0.741061 | [
[
[
"# 15 minutes to QCoDeS\n\nThis short introduction is aimed for potential and new users to get the feel of the software. This is a fully functioning Jupyter notebook that will execute simple measurements using dummy instruments. Before you start with your first code using QCoDeS, make sure you have properly set up the Python environment as explained in [this document](../start/index.rst#installation). If you would like to follow this as an interactive notebook, you may [download it from github](https://github.com/QCoDeS/Qcodes/blob/master/docs/examples/15_minutes_to_QCoDeS.ipynb) to run on your local system, or you may use~ the \"launch binder\" link to use it via a web interface.",
"_____no_output_____"
],
[
"## Introduction\n\nQCoDeS is a python-based data acquisition and handling framework to facilitate experiments in nanoelectronics. As highly configurable open source project, we envision that this system may suite the needs of a diverse range of experimental setups, acting as a common system for regular experimental work across the community.\n\nThis guide offers a practical overview of QCoDeS, going from installation to experimental data handling in a single notebook. Along the way links are provided to assist you in the configuration of this software's features for your experiments.",
"_____no_output_____"
],
[
"## Installation\n\nQCoDeS is readily installed via pip or conda package managers in your preferred environment. These are other installation options are further detailed [in our installation guide](../start/index.rst#installation).\n\nInstall via pip:\n\n> pip install qcodes\n\nInstall via conda:\n\n> conda -c conda-forge install qcodes",
"_____no_output_____"
],
[
"## Module imports\n\nA wide range of modules are available for QCoDeS, but for this example we will only import what is needed for a simple measurement.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport qcodes as qc\nfrom qcodes import (\n Measurement,\n experiments,\n initialise_or_create_database_at,\n load_by_run_spec,\n load_or_create_experiment,\n)\n\n## Dummy instruments for generating synthetic data\nfrom qcodes.tests.instrument_mocks import (\n DummyInstrument, \n DummyInstrumentWithMeasurement\n)\n\n## Multidimensional scanning module\nfrom qcodes.utils.dataset.doNd import (\n dond, \n LinSweep\n)\n\n## Integrated plotting module\nfrom qcodes.dataset.plotting import plot_dataset\n\n## Using interactive widget\nfrom qcodes.interactive_widget import experiments_widget\n\n",
"_____no_output_____"
]
],
[
[
"## Instruments\n\n`Instrument` class in QCoDeS is responsible for holding connections to hardware and controlling the instruments by its built in methods. For more information on instrument class we refer to the [detailed description here](writing_drivers/Instruments.ipynb) or the corresponding [api documentation](../api/instrument/index.rst). \n\nLet us, now, create two dummy instruments: a digital-to-analog converter (`dac`) with two channels, and a digital multimeter (`dmm`) to measure the signals produced: \n",
"_____no_output_____"
]
],
[
[
"# A dummy signal generator with two parameters ch1 and ch2\ndac = DummyInstrument('dac', gates=['ch1', 'ch2'])\n\n# A dummy digital multimeter that generates a synthetic data depending\n# on the values set on the setter_instr, in this case the dummy dac\ndmm = DummyInstrumentWithMeasurement('dmm', setter_instr=dac)",
"_____no_output_____"
]
],
[
[
"All instruments feature methods to enable you to inspect their configuration. We refer to this as a ``snapshot``. For convenience, methods are provided for a human readable version allowing us to take a glance at our digital multimeter:",
"_____no_output_____"
]
],
[
[
"dmm.print_readable_snapshot()",
"dmm:\n\tparameter value\n--------------------------------------------------------------------------------\nIDN :\tNone \nv1 :\t0 (V)\nv2 :\t0 (V)\n"
]
],
[
[
"As we can see here, our dummy multimeter, `dmm`, has two `Parameters` (v1 and v2), that correspond the two channels of our dummy signal generator `dac`. ",
"_____no_output_____"
],
[
"## Parameters\n\nA QCoDeS `Parameter` is a value from an instrument that may get and/or set values by methods. Intuitively this is how QCoDeS communicates with most instrumentation, for example a digital multimeter contains settings (e.g. mode, range) and provide data (e.g. voltage, current). These methods are defined by [instrument drivers](index.rst#drivers), that utilize the [parameter API](../api/parameters/parameter.rst). \n\nIn this example we are using dummy instruments with trivial `set` and `get` methods to generate synthetic data. \n\nFor the `dac`, these settable `Parameters` are added in the instantiation of the `DummyInstrument` class (i.e. `ch1` and `ch2`).\n\n\n> dac = DummyInstrument('dac', **gates=['ch1', 'ch2']**)\n\n\nSimilarly, the dummy digital multimeter, `dmm`, has gettable `Parameters` added by the instantiation of the `DummyInstrumentWithMeasurement` class defined by the output channels of the setter instrument (i.e. the dac). \n\n\n> dmm = DummyInstrumentWithMeasurement('dmm', **setter_instr=dac**)\n\n\nInstruments may vary in their instantiation (e.g. gates vs. setter_inst), but the `parameters` are the common interface for measurements in QCoDeS. \n\nFor convenience QCoDeS provides a variety of parameter classes built in to accommodate a range of instruments: \n\n - `Parameter` : Represents a single value at a given time (e.g. voltage, current), please refer to the [example parameter notebook](Parameters/Parameters.ipynb).\n \n - `ParameterWithSetpoints`: Represents an array of values of all the same type that are returned all at once (e.g. a voltage vs. time waveform). This class is detailed in our [parameter with setpoint notebook](Parameters/Simple-Example-of-ParameterWithSetpoints.ipynb) along with experimental use cases.\n\n - `DelegateParameter`: It is intended for proxy-ing other parameters and is detailed in the [parameter API](../api/parameters/parameter.rst). You can use different label, unit, etc in the delegated parameter as compared to the source parameter.\n\nThese built in parameter classes are typically used as a wrapper for instrument communications. The user-facing `set` and `get` methods calling instrument facing `set_raw` and `get_raw` methods. Further examples of these parameters are discussed in our example [notebook on Parameters](index.rst#parameters).",
"_____no_output_____"
],
[
"### Example of setting and getting parameters\n\nIn most cases, a settable parameter accepts its value as an argument of a simple function call. For our example, we will set the a value of 1.1 for the `ch1` parameter of our signal generator, `dac`, by providing the value to the instrument channel:",
"_____no_output_____"
]
],
[
[
"dac.ch1(1.1)",
"_____no_output_____"
]
],
[
[
"Similarly, a gettable parameter will often return its value with a simple function call. In our example, we will read the value of our digital multimeter, `dmm`, like so:",
"_____no_output_____"
]
],
[
[
"dmm.v1()",
"_____no_output_____"
]
],
[
[
"## Stations \n\nA station is a collection of all the instruments and devices present in your experiment. As mentioned earlier, it can be thought of as a bucket where you can add your `Instruments`, `Parameters` and other components. Each of these terms has a definite meaning in QCoDeS and shall be explained in later sections. Once a station is properly configured, you can use its instances to access these components. We refer to tutorial on [Station](Station.ipynb) for more details.\n\nTo organize our dummy instruments, we will first instantiate a station as so:",
"_____no_output_____"
]
],
[
[
"station = qc.Station()",
"_____no_output_____"
]
],
[
[
"### Adding instruments to the station\n\nEvery instrument that you are working with during an experiment should be added to a `Station`. \n\nHere, we add the `dac` and `dmm` instruments by using our station's `add_component()` method: ",
"_____no_output_____"
]
],
[
[
"station.add_component(dac)\nstation.add_component(dmm)",
"_____no_output_____"
]
],
[
[
"### Inspecting the station\n\nFor any experiment it is essential to have a record of the instrumental setup. To enable this, a `Station` has a `snapshot` method which provides a dictionary of its `Instruments` and their properties (e.g. `Parameters`) in a recursive manner.\n\nThis data is typically saved with every experiment run with QCoDeS, but the `snapshot` method may be used on a station to inspect its status:\n",
"_____no_output_____"
]
],
[
[
"# Remove the ``_ = `` part to see the full snapshot\n_ = station.snapshot()",
"_____no_output_____"
]
],
[
[
"This generates a lengthy output. While we will truncate it for this tutorial, the nested dictionaries offer a human- and machine-readable description of the station and its attached instruments:\n\n```\n{'instruments': {'dmm': {'functions': {},\n 'submodules': {},\n '__class__': 'qcodes.tests.instrument_mocks.DummyInstrumentWithMeasurement',\n 'parameters': {'IDN': {'__class__': 'qcodes.instrument.parameter.Parameter',\n [...]\n 'inter_delay': 0,\n 'instrument': 'qcodes.tests.instrument_mocks.DummyInstrumentWithMeasurement',\n 'instrument_name': 'dmm',\n 'unit': ''},\n 'v1': {'__class__': 'qcodes.tests.instrument_mocks.DmmExponentialParameter',\n 'full_name': 'dmm_v1',\n 'value': 5.136319425854842,\n 'raw_value': 5.136319425854842,\n 'ts': '2021-03-29 18:47:16',\n 'label': 'Gate v1',\n 'name': 'v1',\n 'post_delay': 0,\n 'vals': '<Numbers -800<=v<=400>',\n 'inter_delay': 0,\n 'instrument': 'qcodes.tests.instrument_mocks.DummyInstrumentWithMeasurement',\n 'instrument_name': 'dmm',\n 'unit': 'V'},\n [...]\n```",
"_____no_output_____"
],
[
"### Saving and loading configurations.\n\nThe instantiation of the instruments, that is, setting up the proper initial values of the corresponding parameters and similar pre-specifications of a measurement constitutes the initialization portion of the code. In general, this portion can be quite long and tedious to maintain. These (and more) concerns can be solved by a [YAML configuration file](Station.ipynb#Using-Station-with-YAML-configuration-files) of the `Station` object. Further options for stations are detailed in the [station example](Station.ipynb#Default-Station).\n",
"_____no_output_____"
],
[
"## Databases and experiments.\n\nWith `Station` a working station, the next step is to set up a `database` in order to save our data to. In QCoDeS, we implement a SQLite3 database for this purpose. \n\n### Initialize or create a database\n\nBefore starting a measurement, we first initialize a database. The location of the database is specified by the configuration object of the QCoDeS installation. The database is created with the latest supported version complying with the QCoDeS version that is currently under use. If a database already exists but an upgrade has been done to the QCoDeS, then that database can continue to be used and it is going to be upgraded to the latest version automatically at first connection.\n\nThe initialization (or creation) of the database at a particular location is achieved via static function:",
"_____no_output_____"
]
],
[
[
"initialise_or_create_database_at(\"~/experiments_for_15_mins.db\")",
"Upgrading database; v0 -> v1: : 0it [00:00, ?it/s]\nUpgrading database; v1 -> v2: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 499.80it/s]\nUpgrading database; v2 -> v3: : 0it [00:00, ?it/s]\nUpgrading database; v3 -> v4: : 0it [00:00, ?it/s]\nUpgrading database; v4 -> v5: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 297.70it/s]\nUpgrading database; v5 -> v6: : 0it [00:00, ?it/s]\nUpgrading database; v6 -> v7: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 111.92it/s]\nUpgrading database; v7 -> v8: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 506.74it/s]\nUpgrading database; v8 -> v9: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 333.44it/s]\n"
]
],
[
[
"By default, QCoDeS only supports a single active database. The current database location is stored in the configuration data (i.e. qcodes.config). ",
"_____no_output_____"
]
],
[
[
"qc.config.core.db_location",
"_____no_output_____"
]
],
[
[
"### Load or create an experiment\n\nAfter initializing the database we create an `Experiment` object. This object contains the names of the experiment and sample, and acts as a manager for data acquired during measurement. The `load_or_create_experiment` function will return an existing experiment with the same name, but if no experiments are found, it will create a new one.\n\nFor this example, we will call our experiment `tutorial_exp`:\n",
"_____no_output_____"
]
],
[
[
"tutorial_exp = load_or_create_experiment(\n experiment_name=\"tutorial_exp\",\n sample_name=\"synthetic data\"\n)",
"_____no_output_____"
]
],
[
[
"The path of the database for the `experiment` is the defined path in the QCoDeS configuration. First, `Experiment` loads the database in that path (or it creates one if there is no database in that path), and then saves the created experiment in that database. If an experiment with this name and sample name already exists this will be set as the default experiment for the rest of the session. Although loading or creating a database with the experiment is a user-friendly feature, we recommend users to initialize their database as shown earlier. This practice allows better control of the experiments and databases for measurements, avoiding unexpected outcomes in data management.\n\nThe method shown above to load or create the experiment is the most versatile one. However there are other options discussed in the guide on databases.",
"_____no_output_____"
],
[
"## Measurement Context Manager\n\nThe `Measurement` object is used to obtain data from instruments in QCoDeS, as such it is instantiated with both an `experiment` (to handle data) and `station` to control the instruments. If these arguments are absent, the most recent experiment and station are used as defaults. A keyword argument `name` can also be set as any string value, this string will be used to identify the resulting dataset. ",
"_____no_output_____"
]
],
[
[
"context_meas = Measurement(exp=tutorial_exp, station=station, name='context_example')",
"_____no_output_____"
]
],
[
[
"It is possible to instantiate a `measurement` prior to creating or loading an experiment, but this is not advisable.\n\n1. If the initialized `database` does not contain an `experiment`, then the instantiation will raise an error and halt your work.\n2. If the database already contains an `experiment`, then the instantiated `measurement` will be added to the most recent `experiment` in the database without raising an error message or warning. This will lead to poor data management.\n",
"_____no_output_____"
],
[
"### Registering parameters to measure\n\nQCoDeS features the ability to store the relationship between parameters (i.e. parameter `y` is dependent on `x`). This feature allows the intent of the measurement to be clearly recorded in the experimental records. In addition, the parameter dependency is used to define the coordinate axes when plotting the data using QCoDeS. The parameters which are being measured are first registered with the `measurement`. When registering a dependent parameter (i.e. y(x)) the independent parameter is declared as a setpoint. As a consequence, independent parameters must be registered prior to their corresponding dependent parameters. \n\nIn our example, ``dac.ch1`` is the independent parameter and ``dmm.v1`` is the dependent parameter. So we register ``dmm.v1`` with the setpoint as ``dac.ch1``. ",
"_____no_output_____"
]
],
[
[
"# Register the independent parameter...\ncontext_meas.register_parameter(dac.ch1)\n# ...then register the dependent parameter\ncontext_meas.register_parameter(dmm.v1, setpoints=(dac.ch1,))",
"_____no_output_____"
]
],
[
[
"### Example measurement loop\n\nThe QCoDeS measurement module provides a context manager for registering parameters to measure and store results. Within the context manager, measured data is periodically saved to the database as a background process.\n\nTo conduct a simple measurement, we can create a simple loop inside the context manager which will control the instruments, acquire data, and store the results. \n\n> This is the a more user-configurable approach for acquiring data in QCoDeS. For more examples and details, refer to [Performing measurements using QCoDeS parameters and DataSet example](./DataSet/Performing-measurements-using-qcodes-parameters-and-dataset.ipynb)\n",
"_____no_output_____"
]
],
[
[
"# Time for periodic background database writes\ncontext_meas.write_period = 2\n\nwith context_meas.run() as datasaver:\n for set_v in np.linspace(0, 25, 10):\n dac.ch1.set(set_v)\n get_v = dmm.v1.get()\n datasaver.add_result((dac.ch1, set_v),\n (dmm.v1, get_v))\n\n # Convenient to have for plotting and data access\n dataset = datasaver.dataset",
"Starting experimental run with id: 1. \n"
]
],
[
[
"The `meas.run` method returns a context manager to control data acquisition and storage. Entering the context provides a `DataSaver` object, which we will store as the `datasaver` variable. Using a simple loop structure, we can use instruments' `set` and `get` methods to control the instrument and acquire data respectively. Then, we use the ``add_result`` method to validate the size of all the data points and store them intermittently into a write cache. Within every write-period of the measurement, the data of this cache is flushed to the database in the background.",
"_____no_output_____"
],
[
"## Using the doNd multi-dimensional measurement utility \n\nQcodes also includes functions to produce multidimensional data sets with [optimized data handling](DataSet/Using_doNd_functions_in_comparison_to_Measurement_context_manager_for_performing_measurements.ipynb); of these, ``dond`` (i.e. do n-dimensional is facilitates collecting multidimensional data. Similar optimizations can be made using the measurement context (see [measuring with shaped data](DataSet/Performing-measurements-using-qcodes-parameters-and-dataset.ipynb#Specifying-shape-of-measurement)), but this approach simplifies the setup and readability of the code. \n\n> This is a more user-friendly way of acquiring multi-dimensional data in QCoDeS.\n\nWe will first set up the measurement by defining the sweeps for each independent parameters, in our case the two channels of ``dac``:",
"_____no_output_____"
]
],
[
[
"# Setting up a doNd measurement\nsweep_1 = LinSweep(dac.ch1, -1, 1, 20, 0.01)\nsweep_2 = LinSweep(dac.ch2, -1, 1, 20, 0.01)",
"_____no_output_____"
]
],
[
[
"\nThis linear sweeps for `dac.ch1` and `dac.ch2` are defined by the endpoints of the sweep (-1 to 1 V), the number of steps (20) and a time delay between each step (0.01 s). This delay time is used to allow real instruments to equilibrate between each step in the sweep. Multiple types of sweeps are [included with QCoDeS](DataSet/Using_doNd_functions_in_comparison_to_Measurement_context_manager_for_performing_measurements.ipynb) to enable a variety of sampling schemes. \n\n> When using `dond` we do not register parameters, this is done automatically by the function. With dond every dependent parameter depends on all sweep parameters.",
"_____no_output_____"
]
],
[
[
"dond(\n sweep_1, # 1st independent parameter\n sweep_2, # 2nd independent parameter\n dmm.v1, # 1st dependent parameter\n dmm.v2, # 2nd dependent parameter\n measurement_name=\"dond_example\", # Set the measurement name\n exp=tutorial_exp, # Set the experiment to save data to.\n show_progress=True # Optional progress bar\n)\n",
"Starting experimental run with id: 2. Using 'qcodes.utils.dataset.doNd.dond'\n"
]
],
[
[
"The ``dond`` function features a number of options (e.g. plotting, database write period, multithreading) which are further detailed in our [example notebooks](DataSet/Using_doNd_functions_in_comparison_to_Measurement_context_manager_for_performing_measurements.ipynb#Handling-plot,-experiment,-and-measurement_name-with-doNd). For simple measurements, [do1d](DataSet/Using_doNd_functions_in_comparison_to_Measurement_context_manager_for_performing_measurements.ipynb#do1d) and [do2d](DataSet/Using_doNd_functions_in_comparison_to_Measurement_context_manager_for_performing_measurements.ipynb#do2d) provide a simpler interface with similar functionality for 1d and 2d acquisitions.",
"_____no_output_____"
],
[
"## Exploring datasets and databases\n\nIn this section we detail methods and functions for working with `DataSets`. In QCoDeS, all measured results are generally packaged and stored in the database as a `DataSet` object. While it isn't essential for running QCoDeS, we provide a [detailed walktrough notebook](DataSet/DataSet-class-walkthrough.ipynb) to assist users in developing new data analysis methods.",
"_____no_output_____"
],
[
"### List all datasets in a database.",
"_____no_output_____"
],
[
"The most direct way of finding our data is the `experiments` function; this queries the currently initialized `database` and prints the `experiments` and `datasets` contained inside. ",
"_____no_output_____"
]
],
[
[
"experiments()",
"_____no_output_____"
]
],
[
[
"While this example database contains only a few experiments this number may grow significantly as you perform measurements on your nanoelectronic devices. \n\nWhile our example database contains only few experiments, in reality the database will contain several experiments containing many datasets. Often, you would like to load a dataset from a particular experiment for further analysis. Here we shall explore different ways to find and retrieve already measured dataset from the database.",
"_____no_output_____"
],
[
"### List all the datasets in an experiment\n\nAn experiment also contains the `datasets` produced by its `measurements`. Using the `data_sets` method we can print a list of these `datasets`, the parameters recorded, and the type of data obtained for each parameter.",
"_____no_output_____"
]
],
[
[
"tutorial_exp.data_sets()",
"_____no_output_____"
]
],
[
[
"### Load the data set using one or more specifications",
"_____no_output_____"
],
[
"In order to plot or analyze data, we will need to retrieve the `datasets`. While this can be done directly from the `experiment`, instrument environments are typically not used for analysis. Moreover, we may wish to compare data from separate `experiments` requiring us to load datasets separately.\n\nIn QCoDeS, `datasets` can be obtained using simple criteria via the `load_by_run_spec` function. For this example we will load our previous 1d and 2d datasets by their name and database id number: ",
"_____no_output_____"
]
],
[
[
"dataset_1d = load_by_run_spec(experiment_name='tutorial_exp', captured_run_id=1)\ndataset_2d = load_by_run_spec(experiment_name='tutorial_exp', captured_run_id=2)",
"_____no_output_____"
]
],
[
[
"While the arguments are optional, the function call will raise an error if more than one run matching the supplied specifications is found. If such an error occurs, the traceback will contain the specifications of the runs, as well. More examples of refined search criteria for data extraction are provided in [this example notebook](DataSet/Extracting-runs-from-one-DB-file-to-another.ipynb#Uniquely-identifying-and-loading-runs).\n",
"_____no_output_____"
],
[
"### Plotting datasets\n\nNumerical data is typically difficult to understand when tabulated, so we would want to visualize it as a plot. QCoDeS includes an integrated plotting function, `plot_dataset`, that neatly visualizes our 1d and 2d `datasets`:",
"_____no_output_____"
]
],
[
[
"# Plotting 1d dataset\nplot_dataset(dataset_1d)",
"_____no_output_____"
]
],
[
[
"With 1d data a simple line plot will be generated with the dependent and independent parameters set to the respective X and Y axes. This works nicely because of the integration of the `instrument` (providing units) and the predefined dependency between `parameters` measured.",
"_____no_output_____"
]
],
[
[
"# Plotting 2d dataset as heatmaps\nplot_dataset(dataset_2d)\n",
"_____no_output_____"
]
],
[
[
"With 2d data heat maps will be generated with the independent parameters set to the X and Y axes and the dependent parameter set as the color scale. Similar to the 1d case, this automatic visualization depends on the predefined `parameters` provided to the `dond` function. \n\n>For more detailed examples of plotting QCoDeS datasets, we have articles covering a variety of data types:\n>\n> - [Offline plotting tutorial](DataSet/Offline%20Plotting%20Tutorial.ipynb)\n> - [Offline plotting with categorical data](DataSet/Offline%20plotting%20with%20categorical%20data.ipynb)\n> - [Offline plotting with complex data](DataSet/Offline%20plotting%20with%20complex%20data.ipynb)",
"_____no_output_____"
],
[
"### QCoDeS measurements live plotting with Plottr\n\nPlottr supports and is recommended for live plotting QCoDeS measurements. This enables a direct visualization of an ongoing measurement to facilitate experimentalists. [How to use plottr with QCoDeS for live plotting](plotting/How-to-use-Plottr-with-QCoDeS-for-live-plotting.ipynb) notebook contains more information.",
"_____no_output_____"
],
[
"### Get data of specific parameter of a dataset\n\nWhen designing a new analysis method for your nanoelectronic measurements, it may be useful to extract the data from an individual parameter obtained in a dataset. Using the `get_parameter_data` method included in `DataSet` we obtain a dictionary of the data for a single parameter.\n\n> Note that this method behaves differently for independent (e.g. `dac_ch1`) or dependent (e.g. `dmm_v1`) parameters:",
"_____no_output_____"
]
],
[
[
"# All data for all parameters\ndataset_1d.get_parameter_data()",
"_____no_output_____"
],
[
"# Data for independent parameter\ndataset_1d.get_parameter_data('dac_ch1')",
"_____no_output_____"
],
[
"# Data for dependent parameter\ndataset_1d.get_parameter_data('dmm_v1')",
"_____no_output_____"
]
],
[
[
"We refer reader to [exporting data section of the performing measurements using QCoDeS parameters and dataset](DataSet/Performing-measurements-using-qcodes-parameters-and-dataset.ipynb#Accessing-and-exporting-the-measured-data) and [Accessing data in DataSet notebook](DataSet/Accessing-data-in-DataSet.ipynb) for further information on `get_parameter_data` method.",
"_____no_output_____"
],
[
"### Export data to pandas dataframe\n\nSimilarly, data stored within a QCoDeS database may be exported as pandas dataframes for analysis. This is accomplished by the `to_pandas_dataframe` method included in `DataSet`.",
"_____no_output_____"
]
],
[
[
"df = dataset_1d.to_pandas_dataframe()\ndf.head()",
"_____no_output_____"
]
],
[
[
"### Export data to xarray",
"_____no_output_____"
],
[
"It's also possible to export data stored within a QCoDeS `dataset` to an `xarray.DataSet`. This can be achieved as so:",
"_____no_output_____"
]
],
[
[
"xr_dataset = dataset_1d.to_xarray_dataset()\nxr_dataset",
"_____no_output_____"
]
],
[
[
"We refer to [example notebook on working with pandas](DataSet/Working-With-Pandas-and-XArray.ipynb) and [Accessing data in DataSet notebook](DataSet/Accessing-data-in-DataSet.ipynb) for further information.",
"_____no_output_____"
],
[
"### Explore the data using an interactive widget",
"_____no_output_____"
],
[
"Going beyond text-based review, we have also included a graphical widget to allow the easy exploration of our databases, with an interface for viewing the station snapshot, adding notes, or producing plots of the selected day. \n\n> This widget uses [ipywidgets](https://ipywidgets.readthedocs.io/) to display an interactive elements and is only available when run in a Jupyter notebook. However, we do provide a quick, non-interactive demonstration video below as well.\n\nHere we will load our example database that we initialized earlier.",
"_____no_output_____"
]
],
[
[
"experiments_widget(sort_by=\"timestamp\")",
"_____no_output_____"
]
],
[
[
"Here's a short video that summarizes the looks and the features:\n\n",
"_____no_output_____"
],
[
"## Further Reading",
"_____no_output_____"
],
[
"### QCoDeS configuration \n\nQCoDeS uses a JSON based configuration system. It is shipped with a default configuration. The default config file should not be overwritten. If you have any modifications, you should save the updated config file on your home directory or in the current working directory of your script/notebook. The QCoDeS config system first looks in the current directory for a config file and then in the home directory for one and only then - if no config files are found - it falls back to using the default one. The default config is located in `qcodes.config`. To know how to change and save the config please refer to the [documentation on config](Configuring_QCoDeS.ipynb).",
"_____no_output_____"
],
[
"### QCoDeS instrument drivers\nWe support and provide drivers for most of the instruments currently in use at the Microsoft stations. However, if more functionalities than the ones which are currently supported by drivers are required, one may update the driver or request the features form QCoDeS team. You are more than welcome to contribute and if you would like to have a quick overview on how to write instrument drivers, please refer to the [this notebook](writing_drivers/Instruments.ipynb) as well as the other [example notebooks on writing drivers](index.rst#writing-drivers).",
"_____no_output_____"
],
[
"### QCoDeS logging\n\nIn every measurement session, it is highly recommended to have QCoDeS logging turned on. This will allow you to have all the logs in case troubleshooting is required. This feature is detailed further in an [example notebook](logging/logging_example.ipynb) that describes all the logging features.",
"_____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"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7207ef9645a73be1f433556cac0d7f81a6f92fa | 8,350 | ipynb | Jupyter Notebook | Linear Algebra practice.ipynb | joshfuchs/IntroDataScience | 3a12eece20d18ba16fa03d07a06747050d34e501 | [
"MIT"
] | null | null | null | Linear Algebra practice.ipynb | joshfuchs/IntroDataScience | 3a12eece20d18ba16fa03d07a06747050d34e501 | [
"MIT"
] | null | null | null | Linear Algebra practice.ipynb | joshfuchs/IntroDataScience | 3a12eece20d18ba16fa03d07a06747050d34e501 | [
"MIT"
] | null | null | null | 17.505241 | 407 | 0.432814 | [
[
[
"# Linear Algebra practice\n\nBased on Intro to Linear Algebra for ML from ML Mastery",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
],
[
"v = np.array([1,2,3])\nprint(v)",
"[1 2 3]\n"
],
[
"b = np.array([4,5,6])\nprint(v*b)",
"[ 4 10 18]\n"
],
[
"print(v+b)",
"[5 7 9]\n"
],
[
"print(v-b)",
"[-3 -3 -3]\n"
],
[
"print(v/b)",
"[0.25 0.4 0.5 ]\n"
],
[
"print(b % v)",
"[0 1 0]\n"
],
[
"print(np.dot(v,b))",
"32\n"
],
[
"print(np.cross(v,b))",
"[-3 6 -3]\n"
]
],
[
[
"# Matrices",
"_____no_output_____"
]
],
[
[
"matrix_a = np.array([[1,2,3], [4,5,6]])",
"_____no_output_____"
],
[
"print(matrix_a)",
"[[1 2 3]\n [4 5 6]]\n"
],
[
"matrix_b = np.array([[5,6,7], [7,8,9]])",
"_____no_output_____"
],
[
"print(matrix_b)",
"[[5 6 7]\n [7 8 9]]\n"
],
[
"print(matrix_a + matrix_b)",
"[[ 6 8 10]\n [11 13 15]]\n"
],
[
"print(matrix_a.dot(matrix_b))",
"_____no_output_____"
],
[
"matrix_c = np.array([[1,2], [3,4], [5,6]])",
"_____no_output_____"
],
[
"print(matrix_a.dot(matrix_c))",
"[[22 28]\n [49 64]]\n"
],
[
"print(np.dot(matrix_a, matrix_c))",
"[[22 28]\n [49 64]]\n"
],
[
"print(np.cross(matrix_a, matrix_b))",
"[[-4 8 -4]\n [-3 6 -3]]\n"
],
[
"P = np.array([[8,2], [3,9], [5,6]])\nprint(P)\nQ = P.T\nprint(Q)",
"[[8 2]\n [3 9]\n [5 6]]\n[[8 3 5]\n [2 9 6]]\n"
],
[
"R = np.array([[1.0,2.0], [3.0,4.0]])\nS = np.linalg.inv(R)\nprint(S)",
"[[-2. 1. ]\n [ 1.5 -0.5]]\n"
],
[
"# determinant\nprint(np.linalg.det(R))",
"-2.0000000000000004\n"
],
[
"# trace\nprint(np.trace(P))",
"17\n"
],
[
"# rank\nprint(np.linalg.matrix_rank(R))",
"2\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"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"
]
] |
e720884574ca872ec8dc5d31b539297e88856187 | 4,490 | ipynb | Jupyter Notebook | day2.ipynb | tomashedlund/aoc2015 | 03860bd3379608e5f5372749826119b43030b4d8 | [
"MIT"
] | null | null | null | day2.ipynb | tomashedlund/aoc2015 | 03860bd3379608e5f5372749826119b43030b4d8 | [
"MIT"
] | null | null | null | day2.ipynb | tomashedlund/aoc2015 | 03860bd3379608e5f5372749826119b43030b4d8 | [
"MIT"
] | null | null | null | 23.264249 | 115 | 0.400445 | [
[
[
"import pandas as pd\nimport numpy as np",
"_____no_output_____"
],
[
"data = pd.read_csv(\"C:\\\\Users\\\\TOHED\\\\Desktop\\\\2015d2.txt\", names=[\"content\"])",
"_____no_output_____"
],
[
"data = data.content.str.split('x',expand=True).add_prefix('column_')",
"_____no_output_____"
],
[
"data.column_0 = data.column_0.astype('int32')\ndata.column_1 = data.column_1.astype('int32')\ndata.column_2 = data.column_2.astype('int32')\ndata.head()",
"_____no_output_____"
],
[
"paper = 0\nfor index, row in data.iterrows():\n lw = row.column_0 * row.column_1\n wh = row.column_1 * row.column_2\n lh = row.column_0 * row.column_2\n paper += 2*lw + 2*wh + 2*lh + min(lw, wh, lh)\nprint(paper)",
"1588178\n"
],
[
"paper = 0\nfor index, row in data.iterrows():\n sides = (row.column_0 + row.column_1 + row.column_2 - max(row.column_0, row.column_1, row.column_2))*2\n bow = row.column_0 * row.column_1 * row.column_2\n paper += bow + sides\nprint(paper)",
"3783758\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7208f21df23fbb8482d38c955ba3822ebfd459e | 36,226 | ipynb | Jupyter Notebook | 0_Intro.ipynb | burgamacha/DS-Masterclass | 8c4cce6528e6900bf423d181b0e99d4e441e137c | [
"MIT"
] | 1 | 2021-04-09T01:14:36.000Z | 2021-04-09T01:14:36.000Z | 0_Intro.ipynb | burgamacha/DS-Masterclass | 8c4cce6528e6900bf423d181b0e99d4e441e137c | [
"MIT"
] | null | null | null | 0_Intro.ipynb | burgamacha/DS-Masterclass | 8c4cce6528e6900bf423d181b0e99d4e441e137c | [
"MIT"
] | null | null | null | 36,226 | 36,226 | 0.923011 | [
[
[
"# **Data Science in Python workshop**\n\n### Bryce Macher, Applied Science @ Discovery Channel\n\n_\n_\n_ \n\n** teaching materials in these notebooks are solely the property of Bryce Macher, and cannot be used for other workshops or courses other than by the author or by license. Students are open to review these notebooks at any time, but with attribution of credit back to the author. ",
"_____no_output_____"
],
[
"This workshop will focus on exposing you to basic python, and using that exposure to create a machine learning model both from scratch and using industry-standard tooling. \n\n**At the end of the workshop, you will be able to:**\n- Define the different types of 'data science' currently practiced in industry and academia\n- Identify basic python data types and explore how to leverage them in an applied science setting\n- Conduct hypothesis tests and quantitatively describe data\n- Analyze and manipulate data for both analysis and ML\n- Implement algorithmic notation in python, translating and applying mathematical formulae to a business problem\n- Identify industry-standard tooling for more rapidly transforming algorithms into models\n\n**You will walk away from the workshop with:** \n- A new or fresh understanding of data science\n- A kick-start to self-guided learning journey through data science\n- Code notebooks for use reviewing and relearning, or as the start of a data science portfolio",
"_____no_output_____"
],
[
"# What Is Data Science? ",
"_____no_output_____"
],
[
"<p><img height = \"500px\" src=\"https://kainos-prod-assets.s3.amazonaws.com/uploads/2019/04/data_science.png\" align=\"left\" hspace=\"10px\" vspace=\"0px\"></p>\n\n**What Is Data Science in Practice?**\nData Science is the collision of three skill sets. While some \"unicorns\" who are skilled in all three areas exist, most of us are a 2/3 stack engineers, who just google the rest of the area we don't know as much about. \n\n_\n\n**What is Data Science as a Career?**\nTwo primary subfields: \n- Decision Science: Focused on providing predictive and prescriptive information to a business to make operational decisions. There is a stronger emphasis on maths and business in this subfield. Two examples: revenue forecasting, or identifying trends occurring in social media posts about a specific brand. \n- Applied Science: Focused on creating customer-facing application features powered by machine learning. Math and Computer Science are dominant knowledge domains in this space. Two examples: recommendation engines for driving consumer behavior, predictive text in email\n\n",
"_____no_output_____"
],
[
"## What does that actually mean? \n\n[](https://www.youtube.com/watch?v=MpLHMKTolVw \"Video Title\")",
"_____no_output_____"
],
[
"## The Tools\n\n- SQL, NoSQL for data querying and working at scale\n- Python, R for data manipulation, statistical inference, and machine learning modeling\n- Tableau, powerBI, D3.js for creating visualizations for downstream and upstream stakeholders\n- Go, Java for turning ML models into automated AI capabilities (e.g., 'deployment')\n\n",
"_____no_output_____"
],
[
"<p><img alt=\"Colaboratory logo\" height=\"45px\" src=\"/img/colab_favicon.ico\" align=\"left\" hspace=\"10px\" vspace=\"0px\"></p>\n\n# Today's tool: Google Colab\n\n<h1>What is Colaboratory?</h1>\n\nColaboratory, or \"Colab\" for short, allows you to write and execute Python in your browser, with \n- Zero configuration required\n- Free access to GPUs\n- Easy sharing\n\nWhether you're a **student**, a **data scientist** or an **AI researcher**, Colab can make your work easier. Watch [Introduction to Colab](https://www.youtube.com/watch?v=inN8seMm7UI) to learn more, or just get started below!",
"_____no_output_____"
],
[
"Our focus will be on just establishing your python skills - this is a 'gateway' language into other languages that you can combine with python to supercharge data science projects. \n\nWhat other languages should you learn after this? Depends on your career trajectory! \n- Analytics will be best served focusing on python, R, and SQL \n- Applied science will need to focus on python, spark in scala, and Go",
"_____no_output_____"
],
[
"## Data science\n\nWith Colab you can harness the full power of popular Python libraries to analyze and visualize data. The code cell below uses **numpy** to generate some random data, and uses **matplotlib** to visualize it. We'll go over this in depth today. For now: to edit the code, just click the cell and start editing.\n\nYou can either hit the play button in the upper left corner of the cell to run the code, or use the keyboard shortcut `shift`+`enter`. You'll see it output a visualization.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom matplotlib import pyplot as plt\n\nys = 200 + np.random.randn(100)\nx = [x for x in range(len(ys))]\n\nplt.plot(x, ys, '-')\nplt.fill_between(x, ys, 195, where=(ys > 195), facecolor='g', alpha=0.6)\n\nplt.title(\"Sample Visualization\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"Now we're ready to get started with learning actual code!",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7209e96878a3084c0bd7acfb693c20751769e9a | 251,736 | ipynb | Jupyter Notebook | examples/knmi-climate-scenario2014/rhine-temp-response.ipynb | RETURN-project/eucp | 926a53271d25910b4e3f85db3c152b6f8c04b08b | [
"Apache-2.0"
] | null | null | null | examples/knmi-climate-scenario2014/rhine-temp-response.ipynb | RETURN-project/eucp | 926a53271d25910b4e3f85db3c152b6f8c04b08b | [
"Apache-2.0"
] | 1 | 2020-08-12T10:09:14.000Z | 2020-08-12T14:25:53.000Z | examples/knmi-climate-scenario2014/rhine-temp-response.ipynb | RETURN-project/eucp | 926a53271d25910b4e3f85db3c152b6f8c04b08b | [
"Apache-2.0"
] | 2 | 2019-03-06T15:41:12.000Z | 2019-10-09T20:06:15.000Z | 193.643077 | 201,552 | 0.864199 | [
[
[
"# Local temperature response\n\n*The local temperature response per GCM/RCP combination in the 2071 -- 2100 timespan, relative to the 1976 -- 2005 timespan, as function of the global temperature response over the same periods.*\n\nThis notebook attempts to recreate Figure 2 from Van den Hurk et al.[<sup>1</sup>](#fn1), also used in the [KNMI '14 climate scenarios](http://www.climatescenarios.nl/).\n\nThe data used is CMIP 5 data, which is locally available where this notebook was developed.\n\nIris is our main analysis toolkit, with a few standard libraries such as numpy, pandas and matplotlib.\n\nThere are a few caveats to note in the data analysis, mainly done for simplicity:\n- the data is not gridded to a common grid. It is assumed that either all data grids are the same, or there is negligible difference between the grids. It also means that the area of interest, the Rhine basin, will not exactly match the data grids. Again, this should result in a neglible difference.\n- the various available subsets for models are averaged. \n- For some, we are unable to perform this averaging, notable for EC-EARTH, MIROC-ESM-CHEM and HadGEM2-ES. These datasets are left out in further analysis.\n\nOur final results are similar to, but do not exactly match, those by Van den Hurk et al. In paricular, the coefficient of determination, R<sup>2</sup> is smaller for each season. (We also note one model with negative local relative temperature. This is the FIO-ESM model, not used in Van den Hurk et al). We have made several assumptions in the analysis procedure below, which may not precisely correspond to those used by Van den Hurk et al., hence this can explain the differences. Also, our final dataset includes more models and datasets overall than used by Van den Hurk (compare our table near the end with their Table 4 in the Appendix).\n\nA practical note: we have not always included the output of a cell, by putting a semi-colon at the end of the last cell line, as this would become a rather lengthy output and clog up the notebook. It makes it, however, easier for the (interactive) reader to simply remove the semi-colon and see the results.\n\n<span id=\"#fn1\">[1] Van den Hurk, B., Van Oldenborth, G., Lenderink, G., Hazeleger, W., Haarsma, R., de Vries, H., 2014: Drivers of mean climate change around the Netherlands derived from CMIP5. Clim Dyn., 42, 1683--1697. [doi:10.1007/s00382-013-1707-y](https://link.springer.com/article/10.1007/s00382-013-1707-y).</span>",
"_____no_output_____"
],
[
"## Basic imports and settings",
"_____no_output_____"
]
],
[
[
"import warnings\nfrom copy import deepcopy\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom collections.abc import Iterable\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nfrom cftime import datetime, DatetimeNoLeap, DatetimeJulian, Datetime360Day\nimport iris\nimport iris.coord_categorisation\nfrom iris.util import unify_time_units\nfrom iris.experimental.equalise_cubes import equalise_attributes\n\n%matplotlib inline",
"_____no_output_____"
],
[
"cmip5dir = Path(\"_data/cmip5\")\nvar = \"tas\"\nseasons = ['djf', 'mam', 'jja', 'son']\ncoords = {\n 'rhinebasin': {'w': 6, 'e': 9, 'n': 52, 's': 47}\n}",
"_____no_output_____"
]
],
[
[
"The RCPs and models are derived dynamically, directly from the available subdirectories in the file system.",
"_____no_output_____"
]
],
[
[
"rcps = sorted([int(path.stem[3:]) for path in cmip5dir.glob(\"rcp*\")])\nrcps",
"_____no_output_____"
],
[
"modelnames = sorted({path.stem for path in cmip5dir.glob(f\"rcp*/Amon/{var}/*\")}, key=lambda s: s.casefold())\nmodelnames ;",
"_____no_output_____"
]
],
[
[
"## Set the area and time constraints\n\nThe area constraint is simply based on the \"rectangular\" grid defined above.\n\nThe time constraint is somewhat more problematic: not all datasets use the same style calendar. Therefore, there are multiple variations for the start and end of the timespan set, and a simple if-else chain tests which variation is appropriate. Since this test all happens inside the lambda function, it will slow down things a bit (since this check would happen for every time stamp); to improve the speed, one could define multiple constraints, one for each calendar style, then check the calendar style of the input data beforehand, and apply the appropriate time constraint to the dataset.",
"_____no_output_____"
]
],
[
[
"coord = coords['rhinebasin']\nrhine = iris.Constraint(\n longitude=lambda c: coord['w'] <= c <= coord['e'],\n latitude=lambda c: coord['s'] <= c <= coord['n'])\nrhine",
"_____no_output_____"
],
[
"start1 = DatetimeNoLeap(2071, 1, 1)\nstop1 = DatetimeNoLeap(2099, 12, 31)\nstart2 = DatetimeJulian(2071, 1, 1)\nstop2 = DatetimeJulian(2099, 12, 31)\nstart3 = Datetime360Day(2071, 1, 1)\nstop3 = Datetime360Day(2099, 12, 30)\nstart4 = datetime(2071, 1, 1)\nstop4 = datetime(2100, 12, 31)\ntimespan = iris.Constraint(time=lambda cell: \n start1 <= cell.point <= stop1 if isinstance(cell.point, DatetimeNoLeap) \n else start2 <= cell.point <= stop2 if isinstance(cell.point, DatetimeJulian)\n else start3 <= cell.point <= stop3 if isinstance(cell.point, Datetime360Day)\n else start4 <= cell.point <= stop4)",
"_____no_output_____"
]
],
[
[
"## Load and extract the data\n\nThis is where all the actual work happens; everything else is just bookkeeping.\n\nWe create a function for this, since we'll be doing this for all combinations of RCPs and models; and, in fact, for the historical values as well.\n\nThe dataset is loaded, or possibly multiple datasets, for cases where the data is spread across multiple files (this spread over multiple files is often across time, but we'll ignore any time limits in the dataset initially, and only bother with that when we extract the relevant timespan. Thanks to Iris's lazy loading, this is still relatively cheap, since it avoids loading the full dataset (just the time dimension dataset)).\n\nTwo Iris utilities functions are used, `equalise_attributes` and `unify_time_units`, which equalise attributes such as creation timestamps (which are unimportant for our actual data), so that Iris can properly concatenate all the cubes. Iris does the appropriate thing, concatenating cubes along the time axes (by noting the longitude and latitude coordinates are the same). Note that in a lot of cases, there will simply be one cube loaded anyway, and concatenation is not necessary: we can just use that cube.\n\nWe then extract the relevant area and timespan. Multiple areas can be provided (in our case, the Rhine basin area and the global world), and we loop over these areas, performing the extraction on copies of the original data (in our specific case, we could first extract the global area, and then the local area, which avoids a copy, but it's rarely guaranteed one area lies within another. This wouldn't work if, say, Australia was included in the list of areas). Note that \"global\" is defined by having an area of `None`. Any other areas and timespan are given by Iris constraints, defined above.\n\nOnce we have our extract cube, we add seasons, over which we'll aggregate and calculate the mean seasonal value over the timespan.\n\nWe also average the area into a single point, with appropriately weighting for the curved Earth.\n\nThe output for a single area is then a single cube, with 4 datapoints: one value for each season.\n\nThe returned value is these 4-datapoint cubes appended into a list, one per area. We'll need to manually keep track of which list index corresponds to which area.\n\nFor datasets that don't cover the relevant timespan (it's assumed all datasets cover the globe, and thus all areas of interest), `None` is returned.",
"_____no_output_____"
]
],
[
[
"def load_cube(paths, timespan, areas=None):\n if not isinstance(areas, Iterable) or isinstance(areas, (str, bytes)):\n areas = [areas]\n cubes = iris.load([str(path) for path in paths], constraints='air_temperature')\n equalise_attributes(cubes)\n unify_time_units(cubes)\n try:\n cube = cubes.concatenate_cube()\n except iris.exceptions.ConcatenateError as exc:\n warnings.warn(str(exc) + \"\\nfor: \" + str(paths))\n cube = cubes[0] # iris.load always returns a cubelist, so just take the first element\n \n results = []\n for area in areas:\n excube = cube.copy()\n if area:\n excube = excube.extract(area)\n excube = excube.extract(timespan)\n if excube is None:\n results.append(None)\n continue\n \n iris.coord_categorisation.add_season(excube, 'time', name='season')\n \n weights = iris.analysis.cartography.area_weights(excube)\n excube_av = excube.collapsed(['latitude', 'longitude'], iris.analysis.MEAN, weights=weights)\n excube_season = excube_av.aggregated_by('season', iris.analysis.MEAN)\n results.append(excube_season)\n\n return results",
"_____no_output_____"
],
[
"columns = {f\"RCP {rcp/10:0.1f}\": 0 for rcp in rcps}\ncolumns['Name'] = modelnames\ndf = pd.DataFrame(columns)\ndf.index.rename('Label', inplace=True)\ndf.head()",
"_____no_output_____"
]
],
[
[
"## Loop over all models\n\nThis loops over all possible models, across all RCP variations and across all model subsets.\n\nResults which do not contain the relevant timespan (and thus include `None` instead of a cube, see above) are discarded.\nModels that do not contain any result (in any of their subsets) are completely removed.\n\nThe data structure the results are stored in is a nested dictionary. This is perhaps not the most directly insightful, but since not every model is available for every RCP value, and since the number of subsets varies per model, this is the most flexible way to store our values.\n\nThe levels of the dictionary are \"rcp\", then \"model\", then the subset, then a list of results per area, then each list item being a cube with 4 seasonal-averaged values. For example, `temp[85]['ACCESS1-0']['1i1p1'][1][2]` would get the summer temperature (`[2]`: the third element of the cube, since the summer is the third season) of the Rhine basin, for the subset 1i1p1 for model ACCESS1-0 for RCP 8.5.\n\nTo show progress, we print every RCP iteration, and optionally every model iteration.",
"_____no_output_____"
]
],
[
[
"%%time\n# This takes about 40 minutes\n\ntemp = {}\nfor rcp in rcps:\n print(\"== RCP:\", rcp, \"==\")\n temp[rcp] = {}\n subdir = cmip5dir / f\"rcp{rcp}/Amon/{var}\"\n for model in modelnames:\n temp[rcp][model] = {}\n modeldir = subdir / model\n for rdir in modeldir.glob(\"r*\"):\n paths = list(rdir.glob(\"*.nc\"))\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", UserWarning)\n results = load_cube(paths, timespan, areas=[None, rhine])\n # Skip cubes that don't contain the appropriate timespan for any of the regions\n if any(result is None for result in results):\n continue\n temp[rcp][model][rdir.stem] = results\n # Remove cubes that didn't have any appropriate data\n nvalues = len(temp[rcp][model].values())\n if nvalues == 0:\n del temp[rcp][model]\n #print(model, \":\", nvalues, \"value(s)\")",
"== RCP: 26 ==\n== RCP: 45 ==\n== RCP: 60 ==\n== RCP: 85 ==\nCPU times: user 12min 30s, sys: 33.4 s, total: 13min 3s\nWall time: 13min\n"
]
],
[
[
"## Read the historical data\n\nReading the historical data is very similar to the above code. We first set a new time constraint: 1976 until 2005.",
"_____no_output_____"
]
],
[
[
"start1 = DatetimeNoLeap(1976, 1, 1)\nstop1 = DatetimeNoLeap(2005, 12, 31)\nstart2 = DatetimeJulian(1976, 1, 1)\nstop2 = DatetimeJulian(2005, 12, 31)\nstart3 = Datetime360Day(1976, 1, 1)\nstop3 = Datetime360Day(2005, 12, 30)\nstart4 = datetime(1976, 1, 1)\nstop4 = datetime(2005, 12, 31)\ntimespan = iris.Constraint(time=lambda cell: \n start1 <= cell.point <= stop1 if isinstance(cell.point, DatetimeNoLeap) \n else start2 <= cell.point <= stop2 if isinstance(cell.point, DatetimeJulian)\n else start3 <= cell.point <= stop3 if isinstance(cell.point, Datetime360Day)\n else start4 <= cell.point <= stop4)",
"_____no_output_____"
]
],
[
[
"We don't need to iterate over different RCPs. Other than that, we can use the same code, just with one iteration level less.",
"_____no_output_____"
]
],
[
[
"%%time\n# this takes about 20 minutes\n\nhisttemp = defaultdict(dict)\nbasedir = cmip5dir / f\"historical/Amon/{var}\"\nfor model in modelnames:\n modeldir = basedir / model\n for subset in modeldir.glob(\"r*\"):\n paths = subset.glob(\"*.nc\")\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", UserWarning)\n results = load_cube(paths, timespan, areas=[None, rhine])\n if any(result is None for result in results):\n continue\n histtemp[model][subset.stem] = results\n nvalues = len(histtemp[model].values())\n if nvalues == 0:\n del histtemp[model]\n print(model, \":\", nvalues, \"value(s)\")",
"ACCESS1-0 : 3 value(s)\nACCESS1-3 : 3 value(s)\nbcc-csm1-1 : 3 value(s)\nbcc-csm1-1-m : 3 value(s)\nBNU-ESM : 1 value(s)\nCanCM4 : 10 value(s)\nCanESM2 : 5 value(s)\nCCSM4 : 8 value(s)\nCESM1-BGC : 1 value(s)\nCESM1-CAM5 : 3 value(s)\nCESM1-CAM5-1-FV2 : 4 value(s)\nCESM1-WACCM : 7 value(s)\nCMCC-CESM : 1 value(s)\nCMCC-CM : 1 value(s)\nCMCC-CMS : 1 value(s)\nCNRM-CM5 : 10 value(s)\nCSIRO-Mk3-6-0 : 10 value(s)\nCSIRO-Mk3L-1-2 : 3 value(s)\nEC-EARTH : 7 value(s)\nFGOALS-g2 : 5 value(s)\nFGOALS-s2 : 2 value(s)\nFIO-ESM : 3 value(s)\nGFDL-CM2p1 : 10 value(s)\nGFDL-CM3 : 5 value(s)\nGFDL-ESM2G : 1 value(s)\nGFDL-ESM2M : 1 value(s)\nGISS-E2-H : 18 value(s)\nGISS-E2-H-CC : 1 value(s)\nGISS-E2-R : 26 value(s)\nGISS-E2-R-CC : 1 value(s)\nHadCM3 : 10 value(s)\nHadGEM2-AO : 1 value(s)\nHadGEM2-CC : 3 value(s)\nHadGEM2-ES : 5 value(s)\ninmcm4 : 1 value(s)\nIPSL-CM5A-LR : 6 value(s)\nIPSL-CM5A-MR : 3 value(s)\nIPSL-CM5B-LR : 1 value(s)\nMIROC-ESM : 3 value(s)\nMIROC-ESM-CHEM : 1 value(s)\nMIROC4h : 3 value(s)\nMIROC5 : 5 value(s)\nMPI-ESM-LR : 3 value(s)\nMPI-ESM-MR : 3 value(s)\nMRI-CGCM3 : 5 value(s)\nMRI-ESM1 : 1 value(s)\nNorESM1-M : 3 value(s)\nNorESM1-ME : 2 value(s)\nCPU times: user 9min 8s, sys: 22.4 s, total: 9min 31s\nWall time: 9min 27s\n"
]
],
[
[
"## Calculate the average tempearture\n\nWe average over the different subsets for each model/RCP combination. We do this by using the iris `merge_cube` option: it will merge across a common, increasing coordinate. We add a new \"subset\" coordinate for this purpose, then merge the list of cubes into one, then average across this subset coordinate.\n\nSome merges fail; for now, these are thrown out and ignored (with a short message printed).\n\nThe averaged cube is stored in the `avtemp` variable.\n\nThis is also the point where we add the historical data to the original `temp` dictionary, as a special kind of RCP. We alos make a backup (deep copy) of the original data, since we don't want to re-read all the data if we make a mistake below.",
"_____no_output_____"
]
],
[
[
"# Add the historical temperatures to the other temperature dict, and make a copy of the whole thing.\ntemp['historical'] = histtemp\nbackup = deepcopy(temp)",
"_____no_output_____"
],
[
"# Start from this cell (the data backup) if a mistake was made anywhere below\ntemp = deepcopy(backup)",
"_____no_output_____"
],
[
"# Average results over subsets\n# Skip failed merges\navtemp = defaultdict(dict)\nfor rcp in temp.keys():\n for model in temp[rcp].keys():\n avtemp[rcp][model] = []\n values = list(temp[rcp][model].values())\n for iregion in range(len(values[0])):\n data = np.array([value[iregion].data for value in values])\n #print(data)\n cubes = iris.cube.CubeList([value[iregion] for value in values])\n if rcp != 'historical':\n df.loc[df['Name'] == model, f\"RCP {int(rcp)/10:0.1f}\"] = len(cubes)\n\n for i, cube in enumerate(cubes):\n coordnames = [coord.long_name for coord in cube.coords()]\n if 'subset' in coordnames:\n cube.remove_coord('subset') \n cube.add_aux_coord(iris.coords.AuxCoord(i, long_name='subset', units='no_unit'))\n equalise_attributes(cubes)\n try:\n cube = cubes.merge_cube()\n except iris.exceptions.MergeError as exc:\n print('Failed to merge cubes for', model, \" -- \", rcp)\n continue\n # We don't need to average if there was only 1 cube (subset) to begin with. \n # In fact, Iris will complain and throw an exception if we try to average across a dimension with just 1 point.\n if len(cubes) > 1:\n cube = cube.collapsed(['subset'], iris.analysis.MEAN)\n avtemp[rcp][model].append(cube)\navtemp ;",
"/opt/conda/lib/python3.7/site-packages/iris/coords.py:1357: UserWarning: Collapsing a non-contiguous coordinate. Metadata may not be fully descriptive for 'subset'.\n warnings.warn(msg.format(self.name()))\n/opt/conda/lib/python3.7/site-packages/iris/coords.py:1357: UserWarning: Collapsing a non-contiguous coordinate. Metadata may not be fully descriptive for 'latitude'.\n warnings.warn(msg.format(self.name()))\n"
]
],
[
[
"Show what data we actually have",
"_____no_output_____"
]
],
[
[
"df[['Name', 'RCP 2.6', 'RCP 4.5', 'RCP 6.0', 'RCP 8.5']]",
"_____no_output_____"
]
],
[
[
"## Calculate relative temperature responses\n\nWe now need to calculate the relative temperature responses, by subtracting the historical averages.\n\nFor convenience later on (plotting), we also juggle our dictionary \"order\" around: since there will be separate subplots for each season, and each plot will have separate colours per RPC, we move these keys to the front. Our new dict, `reltemp`, now follows the order \"season\", \"rcp\", \"region\", \"model\" (note that the region corresponds to x and y on the plots). See also the last line in the cell below.",
"_____no_output_____"
]
],
[
[
"# Calculate relative temperatures\n# Also flip the season and region to more outer keys\n\n# in `temp` and `avtemp`, the regions are list-based; they'll now be dict based, using the 'global' and 'local' keywords\n# Ditto for the seasons: cube access is by index `i`, dict access by abbrevation.\nregions = ['global', 'local'] \nreltemp = {}\nfor i, season in enumerate(seasons): \n reltemp[season] = {}\n for rcp in rcps:\n reltemp[season][rcp] = {region: {} for region in regions}\n for model in avtemp[rcp].keys():\n for region, pred, hist in zip(regions, avtemp[rcp][model], avtemp['historical'][model]):\n reltemp[season][rcp][region][model] = pred[i] - hist[i]",
"_____no_output_____"
]
],
[
[
"## Plots\n\nWe create the plots in the style of Van den Hurk et al., with some minor modifications:\n- the identical substring for each subplot is moved out of the individual titles, into the main title\n- the axis labels and tick labels are shared\n- the x and y scales are identical across the figures\n\nWe also calculate the best fit and R<sup>2</sup> in the plotting loop, so that we can directly plot the result as well.\n\nThe plotting requires a nested loop:\n- an outer loop to step through the four subplots, one for each season\n- an inner loop to step through the individual RCPs, so each set of RCP data points is plotted in its own colour.\n\nThere are some Matplotlib technicalities as well to consider:\n- the linear fit is done first, so that the individual data points can be overplot on top of the fitted lines. This requires an extra inner loop, to collect the data points of the individual RCPs into a single array before fitting.\n- matplotlib does not have an option to provide each data point with a numeric symbol. Therefore, the opacity for the data points is turned to zero, and we annotate each point with the relevant number (centered at the point position)\n- matplotlib normally uses a symbol or line (in the relevant colour) with black text for the legend. By setting `markersize` to 0, the symbol is not plotted. We set the label text with the appropriate colour, since this defaults to black.\n- Matplotlib allows for LaTeX inside labels and titles (text in general), provided LaTeX is installed\n- A subplot counter `i` is used to determine which subplots get axis labels or a legend.",
"_____no_output_____"
]
],
[
[
"plt.style.use('bmh')\n\n# Fix the colours, to be similar to the KNMI figure\ncolors = ['green', 'blue', 'orange', 'red']\n\nfig, axes = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(12, 12), gridspec_kw={'hspace': 0.2, 'wspace': 0.1})\nplt.suptitle(\"Local versus global temperature response for 2071-2100\", y=0.95, fontsize=20)\naxes = axes.flatten()\nfor iplot, (season, ax) in enumerate(zip(seasons, axes)):\n \n # Linear fit\n xtot = []\n ytot = []\n for rcp in rcps:\n xtot.append([cube.data for cube in reltemp[season][rcp]['global'].values()])\n ytot.append([cube.data for cube in reltemp[season][rcp]['local'].values()])\n x = np.concatenate(xtot)\n y = np.concatenate(ytot)\n coeffs, covar = np.polyfit(x, y, 1, cov=True)\n stderrs = np.sqrt([covar[0,0], covar[1,1]])\n poly = np.poly1d(coeffs)\n \n yfit = poly(x)\n r2 = np.sum((yfit - y.mean())**2) / np.sum((y - y.mean())**2) \n plt.text(0.1, 0.86, f\"slope = ${coeffs[0]:.2f} \\pm {stderrs[0]:.2f}$\", fontsize=14, transform=ax.transAxes)\n plt.text(0.1, 0.78, f\"$R^2 = {r2:.3f}$\", fontsize=14, transform=ax.transAxes)\n x = [-0.5, 5]\n ax.plot(x, poly(x), '-', color='black')\n poly = np.poly1d([1, 0])\n ax.plot(x, poly(x), '--', color='#333333')\n\n # Plot individual RCPs\n for ircp, rcp in enumerate(rcps):\n names = [name for name in reltemp[season][rcp]['global'].keys()]\n x = xtot[ircp]\n y = ytot[ircp]\n xtot.append(np.array(x))\n ytot.append(np.array(y))\n inames = [i for i, name in enumerate(modelnames) if name in names]\n plot = ax.plot(x, y, 'o', label=f\"RCP {rcp/10:.1f}\", alpha=0, color=colors[ircp])\n # Alternative way to obtain the plot colours, if we had let Matplotlib use its defaults\n #color = plot[0].get_color()\n for iname, xx, yy in zip(inames, x, y):\n ax.annotate(f\"{iname+1:02d}\", (xx, yy), color=colors[ircp], fontsize=12, horizontalalignment='center', verticalalignment='center')\n \n # subplot details\n ax.set_title(season.upper(), fontsize=16)\n ax.axis([-0.5, 5, -2, 9]) \n if iplot in [2, 3]:\n ax.set_xlabel('$\\Delta \\\\mathrm{T}_{\\\\mathrm{global}} [\\mathrm{K}]$', fontsize=14)\n if iplot in [0, 2]:\n ax.set_ylabel('$\\Delta \\\\mathrm{T}_{\\\\mathrm{local}}[\\mathrm{K}]$', fontsize=14)\n if iplot == 0:\n legend = ax.legend(loc='lower right', frameon=False, markerscale=0)\n for color, text in zip(colors, legend.get_texts()):\n text.set_color(color)\n \n# Save the figure to file as well\nplt.savefig('temp-response-rhine.png')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e720a73917a5c4263a9400cf59cf9f7745ebfa0b | 1,903 | ipynb | Jupyter Notebook | tensorflow/book_caicloud/chapter_8_1.ipynb | colinzuo/personal_study | bc8444693b1aa0df1ca79a485cb93da4567b4c64 | [
"Apache-2.0"
] | null | null | null | tensorflow/book_caicloud/chapter_8_1.ipynb | colinzuo/personal_study | bc8444693b1aa0df1ca79a485cb93da4567b4c64 | [
"Apache-2.0"
] | null | null | null | tensorflow/book_caicloud/chapter_8_1.ipynb | colinzuo/personal_study | bc8444693b1aa0df1ca79a485cb93da4567b4c64 | [
"Apache-2.0"
] | null | null | null | 22.388235 | 91 | 0.498161 | [
[
[
"import numpy as np",
"_____no_output_____"
],
[
"X = [1, 2]\nstate = [0.0, 0.0]\nw_cell_state = np.asarray([[0.1, 0.2], [0.3, 0.4]])\nw_cell_input = np.asarray([0.5, 0.6])\nb_cell = np.asarray([0.1, -0.1])\n\nw_output = np.asarray([[1.0], [2.0]])\nb_output = 0.1\n\nfor i in range(len(X)):\n before_activation = np.dot(state, w_cell_state) + X[i] * w_cell_input + b_cell\n state = np.tanh(before_activation)\n \n final_output = np.dot(state, w_output) + b_output\n \n print('before activation: ', before_activation)\n print('state: ', state)\n print('output: ', final_output)",
"before activation: [ 0.6 0.5]\nstate: [ 0.53704957 0.46211716]\noutput: [ 1.56128388]\nbefore activation: [ 1.2923401 1.39225678]\nstate: [ 0.85973818 0.88366641]\noutput: [ 2.72707101]\n"
]
]
] | [
"code"
] | [
[
"code",
"code"
]
] |
e720af1e47e8786173356f5299c9ee2dea51048b | 169,151 | ipynb | Jupyter Notebook | Python/scikit-learn/03-unsupervised_learning/data_preprocessing_scaling.ipynb | statKim/TIL | 3297d09023d97653773b35160794d3324b95c111 | [
"MIT"
] | null | null | null | Python/scikit-learn/03-unsupervised_learning/data_preprocessing_scaling.ipynb | statKim/TIL | 3297d09023d97653773b35160794d3324b95c111 | [
"MIT"
] | null | null | null | Python/scikit-learn/03-unsupervised_learning/data_preprocessing_scaling.ipynb | statKim/TIL | 3297d09023d97653773b35160794d3324b95c111 | [
"MIT"
] | null | null | null | 407.592771 | 73,712 | 0.939598 | [
[
[
"# Data Preprocessing and Scaling",
"_____no_output_____"
]
],
[
[
"import setting_location # 상위 경로에 있는 module import하기 위한 설정\n%matplotlib inline\nfrom preamble import * # 사용자 정의 모듈 import\nplt.rcParams['image.cmap'] = \"gray\"\nplt.rcParams['axes.xmargin'] = 0.05\nplt.rcParams['axes.ymargin'] = 0.05",
"_____no_output_____"
],
[
"mglearn.plots.plot_scaling()",
"_____no_output_____"
]
],
[
[
"### 데이터 전처리 방법 - 데이터 변환",
"_____no_output_____"
]
],
[
[
"from sklearn.datasets import load_breast_cancer\nfrom sklearn.model_selection import train_test_split\ncancer = load_breast_cancer()\n\nX_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target,\n random_state=1)\nprint(X_train.shape)\nprint(X_test.shape)",
"(426, 30)\n(143, 30)\n"
]
],
[
[
"#### Min-Max Scaler\n- 데이터의 **min=0**, **max=1**로 scaling",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import MinMaxScaler\n\nscaler = MinMaxScaler() # Min-Max Scaler 생성",
"_____no_output_____"
],
[
"scaler.fit(X_train) # Min-Max scaler 기준 정의(train set으로 min-max scaler를 정의함)",
"_____no_output_____"
],
[
"# 데이터 변환 -> scaling\nX_train_scaled = scaler.transform(X_train)\n\n# 스케일이 조정된 후 데이터셋의 속성을 출력합니다\nprint(\"변환된 후 크기: {}\".format(X_train_scaled.shape))\nprint(\"스케일 조정 전 특성별 최소값:\\n {}\".format(X_train.min(axis=0)))\nprint(\"스케일 조정 전 특성별 최대값:\\n {}\".format(X_train.max(axis=0)))\nprint(\"스케일 조정 후 특성별 최소값:\\n {}\".format(X_train_scaled.min(axis=0)))\nprint(\"스케일 조정 후 특성별 최대값:\\n {}\".format(X_train_scaled.max(axis=0)))",
"변환된 후 크기: (426, 30)\n스케일 조정 전 특성별 최소값:\n [ 6.981 9.71 43.79 143.5 0.053 0.019 0. 0. 0.106\n 0.05 0.115 0.36 0.757 6.802 0.002 0.002 0. 0.\n 0.01 0.001 7.93 12.02 50.41 185.2 0.071 0.027 0.\n 0. 0.157 0.055]\n스케일 조정 전 특성별 최대값:\n [ 28.11 39.28 188.5 2501. 0.163 0.287 0.427 0.201\n 0.304 0.096 2.873 4.885 21.98 542.2 0.031 0.135\n 0.396 0.053 0.061 0.03 36.04 49.54 251.2 4254.\n 0.223 0.938 1.17 0.291 0.577 0.149]\n스케일 조정 후 특성별 최소값:\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.]\n스케일 조정 후 특성별 최대값:\n [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.\n 1. 1. 1. 1. 1. 1.]\n"
],
[
"# 테스트 데이터 변환 - train set으로 정의된 scaler로 데이터를 변환한 것\nX_test_scaled = scaler.transform(X_test)\n\n# 스케일이 조정된 후 테스트 데이터의 속성을 출력합니다\nprint(\"스케일 조정 후 특성별 최소값:\\n{}\".format(X_test_scaled.min(axis=0)))\nprint(\"스케일 조정 후 특성별 최대값:\\n{}\".format(X_test_scaled.max(axis=0)))",
"스케일 조정 후 특성별 최소값:\n[ 0.034 0.023 0.031 0.011 0.141 0.044 0. 0. 0.154 -0.006\n -0.001 0.006 0.004 0.001 0.039 0.011 0. 0. -0.032 0.007\n 0.027 0.058 0.02 0.009 0.109 0.026 0. 0. -0. -0.002]\n스케일 조정 후 특성별 최대값:\n[0.958 0.815 0.956 0.894 0.811 1.22 0.88 0.933 0.932 1.037 0.427 0.498\n 0.441 0.284 0.487 0.739 0.767 0.629 1.337 0.391 0.896 0.793 0.849 0.745\n 0.915 1.132 1.07 0.924 1.205 1.631]\n"
]
],
[
[
"#### 동일한 방법(정의된 Scaler)으로 train, test set 스케일을 조정!!!",
"_____no_output_____"
],
[
"matplotlib 3.0 버전에서는 `scatter` 함수에 색깔을 지정할 때 하나의 RGB 포맷 문자열이나 `Colormap`의 리스트를 지정해야 합니다. 경고를 피하기 위해 `mglearn`에서 만든 `ListedColormap` 객체의 `colors` 속성의 원소를 직접 선택하여 RGB 포맷 문자열을 지정합니다.",
"_____no_output_____"
]
],
[
[
"from sklearn.datasets import make_blobs\n# 연습용 데이터셋 생성\nX, _ = make_blobs(n_samples=50, centers=5, random_state=4, cluster_std=2)\n\n# train, test set으로 분리\nX_train, X_test = train_test_split(X, random_state=5, test_size=.1)\n\n# scatter plot\nfig, axes = plt.subplots(1, 3, figsize=(13, 4))\naxes[0].scatter(X_train[:, 0], X_train[:, 1],\n c=mglearn.cm2.colors[0], label=\"훈련 세트\", s=60)\naxes[0].scatter(X_test[:, 0], X_test[:, 1], marker='^',\n c=mglearn.cm2.colors[1], label=\"테스트 세트\", s=60)\naxes[0].legend(loc='upper left')\naxes[0].set_title(\"원본 데이터\")\n\n# Min-Max Scaler를 사용해 스케일을 조정\nscaler = MinMaxScaler()\nscaler.fit(X_train)\nX_train_scaled = scaler.transform(X_train)\nX_test_scaled = scaler.transform(X_test)\n\n# scaling된 데이터로 산점도\naxes[1].scatter(X_train_scaled[:, 0], X_train_scaled[:, 1],\n c=mglearn.cm2.colors[0], label=\"훈련 세트\", s=60)\naxes[1].scatter(X_test_scaled[:, 0], X_test_scaled[:, 1], marker='^',\n c=mglearn.cm2.colors[1], label=\"테스트 세트\", s=60)\naxes[1].set_title(\"스케일 조정된 데이터\")\n\n# 테스트 세트의 스케일을 따로 조정합니다\n# 테스트 세트의 최솟값은 0, 최댓값은 1이 됩니다\n# 이는 예제를 위한 것으로 절대로 이렇게 사용해서는 안됩니다\ntest_scaler = MinMaxScaler()\ntest_scaler.fit(X_test)\nX_test_scaled_badly = test_scaler.transform(X_test)\n\n# 잘못 조정된 데이터의 산점도를 그립니다\naxes[2].scatter(X_train_scaled[:, 0], X_train_scaled[:, 1],\n c=mglearn.cm2.colors[0], label=\"training set\", s=60)\naxes[2].scatter(X_test_scaled_badly[:, 0], X_test_scaled_badly[:, 1],\n marker='^', c=mglearn.cm2.colors[1], label=\"test set\", s=60)\naxes[2].set_title(\"잘못 조정된 데이터\")\n\nfor ax in axes:\n ax.set_xlabel(\"특성 0\")\n ax.set_ylabel(\"특성 1\")\nfig.tight_layout()",
"_____no_output_____"
]
],
[
[
"#### Standardization\n\n- 데이터의 **평균=0**, **분산=1**로 변환\n\n- $ z = \\frac{x - \\mu}{\\sigma} $",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\n\n# 메소드 체이닝(chaining)을 사용하여 fit과 transform을 연달아 호출합니다\nX_scaled = scaler.fit(X_train).transform(X_train)\n# 위와 동일하지만 더 효율적입니다\nX_scaled_d = scaler.fit_transform(X_train)",
"_____no_output_____"
]
],
[
[
"## Supervised Learning에 적용",
"_____no_output_____"
],
[
"사이킷런 0.20 버전에서 `SVC` 클래스의 `gamma` 매개변수 옵션에 `auto`외에 `scale`이 추가되었습니다. `auto`는 `1/n_features`, 즉 특성 개수의 역수입니다. `scale`은 `1/(n_features * X.std())`로 스케일 조정이 되지 않은 특성에서 더 좋은 결과를 만듭니다. 사이킷런 0.22 버전부터는 `gamma` 매개변수의 기본값이 `auto`에서 `scale`로 변경됩니다. 서포트 벡터 머신을 사용하기 전에 특성을 표준화 전처리하면 `scale`과 `auto`는 차이가 없습니다. 경고를 피하기 위해 명시적으로 `auto` 옵션을 지정합니다.",
"_____no_output_____"
]
],
[
[
"from sklearn.svm import SVC\n\nX_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target,\n random_state=0)\n\nsvm = SVC(gamma='auto', C=100)\nsvm.fit(X_train, y_train)\nprint(\"테스트 세트 정확도: {:.2f}\".format(svm.score(X_test, y_test)))",
"테스트 세트 정확도: 0.63\n"
],
[
"# 0~1 사이로 스케일 조정(Min-Max Scaling)\nscaler = MinMaxScaler()\nscaler.fit(X_train)\nX_train_scaled = scaler.transform(X_train)\nX_test_scaled = scaler.transform(X_test)\n\n# 조정된 데이터로 SVM 학습\nsvm.fit(X_train_scaled, y_train)\n\n# 스케일 조정된 테스트 세트의 정확도\nprint(\"스케일 조정된 테스트 세트의 정확도: {:.2f}\".format(svm.score(X_test_scaled, y_test)))",
"스케일 조정된 테스트 세트의 정확도: 0.97\n"
],
[
"# 평균 0, 분산 1을 갖도록 스케일 조정(Standardization)\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nscaler.fit(X_train)\nX_train_scaled = scaler.transform(X_train)\nX_test_scaled = scaler.transform(X_test)\n\n# 조정된 데이터로 SVM 학습\nsvm.fit(X_train_scaled, y_train)\n\n# 스케일 조정된 테스트 세트의 정확도\nprint(\"SVM test accuracy: {:.2f}\".format(svm.score(X_test_scaled, y_test)))",
"SVM test accuracy: 0.96\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
e720b73872267c13f297a8377dffe8e8ea844b57 | 4,061 | ipynb | Jupyter Notebook | ipynb/Mongolia.ipynb | RobertRosca/oscovida.github.io | d609949076e3f881e38ec674ecbf0887e9a2ec25 | [
"CC-BY-4.0"
] | null | null | null | ipynb/Mongolia.ipynb | RobertRosca/oscovida.github.io | d609949076e3f881e38ec674ecbf0887e9a2ec25 | [
"CC-BY-4.0"
] | null | null | null | ipynb/Mongolia.ipynb | RobertRosca/oscovida.github.io | d609949076e3f881e38ec674ecbf0887e9a2ec25 | [
"CC-BY-4.0"
] | null | null | null | 28.398601 | 162 | 0.508742 | [
[
[
"# Mongolia\n\n* Homepage of project: https://oscovida.github.io\n* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Mongolia.ipynb)",
"_____no_output_____"
]
],
[
[
"import datetime\nimport time\n\nstart = datetime.datetime.now()\nprint(f\"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}\")",
"_____no_output_____"
],
[
"%config InlineBackend.figure_formats = ['svg']\nfrom oscovida import *",
"_____no_output_____"
],
[
"overview(\"Mongolia\");",
"_____no_output_____"
],
[
"# load the data\ncases, deaths, region_label = get_country_data(\"Mongolia\")\n\n# compose into one table\ntable = compose_dataframe_summary(cases, deaths)\n\n# show tables with up to 500 rows\npd.set_option(\"max_rows\", 500)\n\n# display the table\ntable",
"_____no_output_____"
]
],
[
[
"# Explore the data in your web browser\n\n- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Mongolia.ipynb)\n- and wait (~1 to 2 minutes)\n- Then press SHIFT+RETURN to advance code cell to code cell\n- See http://jupyter.org for more details on how to use Jupyter Notebook",
"_____no_output_____"
],
[
"# Acknowledgements:\n\n- Johns Hopkins University provides data for countries\n- Robert Koch Institute provides data for within Germany\n- Open source and scientific computing community for the data tools\n- Github for hosting repository and html files\n- Project Jupyter for the Notebook and binder service\n- The H2020 project Photon and Neutron Open Science Cloud ([PaNOSC](https://www.panosc.eu/))\n\n--------------------",
"_____no_output_____"
]
],
[
[
"print(f\"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and \"\n f\"deaths at {fetch_deaths_last_execution()}.\")",
"_____no_output_____"
],
[
"# to force a fresh download of data, run \"clear_cache()\"",
"_____no_output_____"
],
[
"print(f\"Notebook execution took: {datetime.datetime.now()-start}\")\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
e720d12549ba6e6cd7ae8d84b791951947c6bf26 | 4,589 | ipynb | Jupyter Notebook | Pro Python Day-3_File_handling.ipynb | ratnasankeerthanreddy/Introduction-to-Python | 965f35225ed9f4b2beeeb46bc2d92af07a09c560 | [
"MIT"
] | null | null | null | Pro Python Day-3_File_handling.ipynb | ratnasankeerthanreddy/Introduction-to-Python | 965f35225ed9f4b2beeeb46bc2d92af07a09c560 | [
"MIT"
] | null | null | null | Pro Python Day-3_File_handling.ipynb | ratnasankeerthanreddy/Introduction-to-Python | 965f35225ed9f4b2beeeb46bc2d92af07a09c560 | [
"MIT"
] | null | null | null | 20.127193 | 136 | 0.458924 | [
[
[
"# File Handling",
"_____no_output_____"
],
[
"### Write a Python program to read an entire text file.",
"_____no_output_____"
]
],
[
[
"file = open('demo.txt')\nfile_read = file.read()\nfile_read",
"_____no_output_____"
]
],
[
[
"### Write a Python program to read first n lines of a file.",
"_____no_output_____"
]
],
[
[
"N = 5\nwith open(\"demo.txt\", \"r\") as file: \n for i in range(N):\n line = next(file).strip()\n print(line)",
"hi\nhello\n\nhellow world\npython\n"
]
],
[
[
"### Write a Python program to append text to a file and display the text.",
"_____no_output_____"
]
],
[
[
"def Appendtext(fname):\n with open(fname,'a+') as f:\n f.write('appending line 1,\\n ')\n f.write('appending line 2. ')\n f.close()\n# y=open('file1.txt')\n# print(y.read())\nAppendtext('demo.txt')\n\nx= open('demo.txt')\nprint(x.read())",
"hi\nhello\n\nhellow world\npython\n\npython for data sceine\n gts\nglobal technology\nhi\nbye\nfile\ntext file\nappending line 1, appending line 2. appending line 1,\n appending line 2. \n"
]
],
[
[
"### Write a Python program to read last n lines of a file.",
"_____no_output_____"
]
],
[
[
"def read_lastnlines(fname,n):\n with open('demo.txt') as f:\n for line in (f.readlines() [-n:]):\n print(line)\n\nread_lastnlines('demo.txt',3)",
"text file\n\nappending line 1, appending line 2. appending line 1,\n\n appending line 2. \n"
]
],
[
[
"### Write a Python program to read a file line by line and store it into a list.",
"_____no_output_____"
]
],
[
[
"with open(\"demo.txt\") as f:\n lst = f.readlines()\nlst = [x.strip() for x in lst] \nlst",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e720e081a4d35ca61fcd7b88c60c6524d4c3fdcd | 3,529 | ipynb | Jupyter Notebook | OLD/01_detailed_install.ipynb | beckmart/neuropointillist | 505ec3f4603425a2aad3776155cbd3a5d78c2085 | [
"MIT"
] | 3 | 2018-08-09T19:44:20.000Z | 2021-06-02T16:43:50.000Z | OLD/01_detailed_install.ipynb | beckmart/neuropointillist | 505ec3f4603425a2aad3776155cbd3a5d78c2085 | [
"MIT"
] | 10 | 2018-08-09T06:41:05.000Z | 2018-08-10T21:45:52.000Z | OLD/01_detailed_install.ipynb | beckmart/neuropointillist | 505ec3f4603425a2aad3776155cbd3a5d78c2085 | [
"MIT"
] | 3 | 2018-08-08T20:39:09.000Z | 2018-08-09T13:58:22.000Z | 30.422414 | 361 | 0.619156 | [
[
[
"## Installing Neuropointillist on your local machine (for macs)\n\nMake sure you have the necessary programs and packages installed.\n\nInstructions adapted from: http://ibic.github.io/neuropointillist/installation.html\n\nNeeded programs:\n* R\n* Python 2.7 or later\n\nNote that you only need to install the Python and R packages once on your local machine; after they have been installed, neuropointillist will be able to load them as needed:\n\nNeeded Python packages\n* argparse (for R's argparse package)\n* json (for R's argparse package)\n* nibabel\n\nThe simplest way to install python packages is through pip ([instructions for download here](https://pip.pypa.io/en/stable/); note that pip installs automatically with [Anaconda/miniconda](https://conda.io/docs/user-guide/install/index.html)):\n\n```\npip install argparse\npip install json\npip install nibabel\n```",
"_____no_output_____"
],
[
"Needed R packages\n* argparse\n* doParallel\n* Rniftilib\n* nlme (if you're using the tutorial's model)\n* neuropointillist\n\nThe simplest way to install the first 4 R packages is to open R and run the following commands:",
"_____no_output_____"
],
[
"```\ninstall.packages(\"argparse\")\ninstall.packages(\"doParallel\")\n#Rniftilib must be installed from the source\ninstall.packages(\"http://ascopa.server4you.net/ubuntu/ubuntu/pool/universe/r/r-cran-rniftilib/r-cran-rniftilib_0.0-35.r79.orig.tar.xz\", repos=NULL)\ninstall.packages(\"nlme\")\n```",
"_____no_output_____"
],
[
"To install the neuropointillist package, you must first clone the neuropointillist repository to your local machine. To do this in Terminal, navigate to the folder you want to put the repository in and run the following:",
"_____no_output_____"
],
[
"`git clone https://github.com/IBIC/neuropointillist.git`",
"_____no_output_____"
],
[
"Then in Terminal, cd into the neuropointillist folder you just cloned. There should be yet another neuropointillist folder in this folder. Make sure you're in the first neuropointillist folder but not the second. In other words, if the folder structure looks like ~/Desktop/neuropointillist/neuropointillist, you should be in ~/Desktop/neuropointillist\n\nOpen R and run the following to install the neuropointillist package:",
"_____no_output_____"
],
[
"`install.packages(\"neuropointillist\", repos=NULL, type=\"source\")`",
"_____no_output_____"
],
[
"Now your computer should be set up to run neuropointillist!",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e720f1d86bc5dbf1493a33da973be1457cea95bc | 3,204 | ipynb | Jupyter Notebook | .ipynb_checkpoints/Hacker's Guide to NN's-checkpoint.ipynb | shivam-singhal/nn_implementations | 962314e31a34fb386dc34a94e05d32ea68abad0b | [
"MIT"
] | null | null | null | .ipynb_checkpoints/Hacker's Guide to NN's-checkpoint.ipynb | shivam-singhal/nn_implementations | 962314e31a34fb386dc34a94e05d32ea68abad0b | [
"MIT"
] | null | null | null | .ipynb_checkpoints/Hacker's Guide to NN's-checkpoint.ipynb | shivam-singhal/nn_implementations | 962314e31a34fb386dc34a94e05d32ea68abad0b | [
"MIT"
] | null | null | null | 23.386861 | 161 | 0.525281 | [
[
[
"# Chapter 1: Real-valued Circuits",
"_____no_output_____"
],
[
"- Real values (as opposed to boolean vals) flow along edges\n- AND, OR, NOT replaced by binary gates (*, +, max) or unary gates (exp)",
"_____no_output_____"
]
],
[
[
"# Base case circuit\n# inputs: x, y\n# outputs: x * y\ndef forwardMultiplyGate(x, y):\n return x * y\nforwardMultiplyGate(-2, 3)",
"_____no_output_____"
]
],
[
[
"The core question then becomes: How should one tweak the input slightly to increase the output?",
"_____no_output_____"
],
[
"### Random Local Search",
"_____no_output_____"
],
[
"General idea: randomly select x, y values and then compare with previous values\nProblem: this doesn't \"tweak\" x, y; all it does is randomly get a good value\n\nRefined general idea: start at some values for x, y. Then based on some tweaking factor, push x, y up/down based on the random scalar times tweaking factor",
"_____no_output_____"
]
],
[
[
"import random\n\nx, y = -2, 3\n\nbest_x = x\nbest_y = y\nbest_val = float('-inf')\ntweak = 0.01\n\nfor i in range(1000):\n x_prime = x + tweak * (random.random() * 2 - 1) # to put tweaking scalar in range [-1, 1)\n y_prime = y + tweak * (random.random() * 2 - 1)\n val_prime = forwardMultiplyGate(x_prime, y_prime)\n if (val_prime > best_val):\n best_x = x_prime\n best_y = y_prime\n best_val = val_prime\n # not setting x and y since we don't want some sort of numerical gradient yet, just completely random\nprint(\"best x: %s, best y: %s, best out: %s\" % (best_x, best_y, best_val))",
"best x: -1.9904144141862778, best y: 2.990801697770975, best out: -5.95293480921614\n"
]
],
[
[
"### Numerical Gradient",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e720f4d54e432cbd03aeac1f7ff668fbbc2c11c0 | 69,162 | ipynb | Jupyter Notebook | module3-ridge-regression/LS_DS_213_assignment.ipynb | DevvinK/DS-Unit-2-Linear-Models | 319711aafc00f4f0797603dfcfce464ce04513a7 | [
"MIT"
] | null | null | null | module3-ridge-regression/LS_DS_213_assignment.ipynb | DevvinK/DS-Unit-2-Linear-Models | 319711aafc00f4f0797603dfcfce464ce04513a7 | [
"MIT"
] | null | null | null | module3-ridge-regression/LS_DS_213_assignment.ipynb | DevvinK/DS-Unit-2-Linear-Models | 319711aafc00f4f0797603dfcfce464ce04513a7 | [
"MIT"
] | null | null | null | 41.488902 | 1,582 | 0.361875 | [
[
[
"Lambda School Data Science\n\n*Unit 2, Sprint 1, Module 3*\n\n---",
"_____no_output_____"
],
[
"# Ridge Regression\n\n## Assignment\n\nWe're going back to our other **New York City** real estate dataset. Instead of predicting apartment rents, you'll predict property sales prices.\n\nBut not just for condos in Tribeca...\n\n- [ ] Use a subset of the data where `BUILDING_CLASS_CATEGORY` == `'01 ONE FAMILY DWELLINGS'` and the sale price was more than 100 thousand and less than 2 million.\n- [ ] Do train/test split. Use data from January — March 2019 to train. Use data from April 2019 to test.\n- [ ] Do one-hot encoding of categorical features.\n- [ ] Do feature selection with `SelectKBest`.\n- [ ] Fit a ridge regression model with multiple features. Use the `normalize=True` parameter (or do [feature scaling](https://scikit-learn.org/stable/modules/preprocessing.html) beforehand — use the scaler's `fit_transform` method with the train set, and the scaler's `transform` method with the test set)\n- [ ] Get mean absolute error for the test set.\n- [ ] As always, commit your notebook to your fork of the GitHub repo.\n\nThe [NYC Department of Finance](https://www1.nyc.gov/site/finance/taxes/property-rolling-sales-data.page) has a glossary of property sales terms and NYC Building Class Code Descriptions. The data comes from the [NYC OpenData](https://data.cityofnewyork.us/browse?q=NYC%20calendar%20sales) portal.\n\n\n## Stretch Goals\n\nDon't worry, you aren't expected to do all these stretch goals! These are just ideas to consider and choose from.\n\n- [ ] Add your own stretch goal(s) !\n- [ ] Instead of `Ridge`, try `LinearRegression`. Depending on how many features you select, your errors will probably blow up! 💥\n- [ ] Instead of `Ridge`, try [`RidgeCV`](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RidgeCV.html).\n- [ ] Learn more about feature selection:\n - [\"Permutation importance\"](https://www.kaggle.com/dansbecker/permutation-importance)\n - [scikit-learn's User Guide for Feature Selection](https://scikit-learn.org/stable/modules/feature_selection.html)\n - [mlxtend](http://rasbt.github.io/mlxtend/) library\n - scikit-learn-contrib libraries: [boruta_py](https://github.com/scikit-learn-contrib/boruta_py) & [stability-selection](https://github.com/scikit-learn-contrib/stability-selection)\n - [_Feature Engineering and Selection_](http://www.feat.engineering/) by Kuhn & Johnson.\n- [ ] Try [statsmodels](https://www.statsmodels.org/stable/index.html) if you’re interested in more inferential statistical approach to linear regression and feature selection, looking at p values and 95% confidence intervals for the coefficients.\n- [ ] Read [_An Introduction to Statistical Learning_](http://faculty.marshall.usc.edu/gareth-james/ISL/ISLR%20Seventh%20Printing.pdf), Chapters 1-3, for more math & theory, but in an accessible, readable way.\n- [ ] Try [scikit-learn pipelines](https://scikit-learn.org/stable/modules/compose.html).",
"_____no_output_____"
]
],
[
[
"%%capture\nimport sys\n\n# If you're on Colab:\nif 'google.colab' in sys.modules:\n DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/'\n !pip install category_encoders==2.*\n\n# If you're working locally:\nelse:\n DATA_PATH = '../data/'\n \n# Ignore this Numpy warning when using Plotly Express:\n# FutureWarning: Method .ptp is deprecated and will be removed in a future version. Use numpy.ptp instead.\nimport warnings\nwarnings.filterwarnings(action='ignore', category=FutureWarning, module='numpy')",
"_____no_output_____"
],
[
"import pandas as pd\nimport pandas_profiling\n\n# Read New York City property sales data\ndf = pd.read_csv(DATA_PATH+'condos/NYC_Citywide_Rolling_Calendar_Sales.csv')\n\n# Change column names: replace spaces with underscores\ndf.columns = [col.replace(' ', '_') for col in df]\n\n# SALE_PRICE was read as strings.\n# Remove symbols, convert to integer\ndf['SALE_PRICE'] = (\n df['SALE_PRICE']\n .str.replace('$','')\n .str.replace('-','')\n .str.replace(',','')\n .astype(int)\n)",
"_____no_output_____"
],
[
"# BOROUGH is a numeric column, but arguably should be a categorical feature,\n# so convert it from a number to a string\ndf['BOROUGH'] = df['BOROUGH'].astype(str)",
"_____no_output_____"
],
[
"# Reduce cardinality for NEIGHBORHOOD feature\n\n# Get a list of the top 10 neighborhoods\ntop10 = df['NEIGHBORHOOD'].value_counts()[:10].index\n\n# At locations where the neighborhood is NOT in the top 10, \n# replace the neighborhood with 'OTHER'\ndf.loc[~df['NEIGHBORHOOD'].isin(top10), 'NEIGHBORHOOD'] = 'OTHER'",
"_____no_output_____"
],
[
"print(df.shape)\ndf.head()",
"(23040, 21)\n"
],
[
"df['BUILDING_CLASS_CATEGORY'].value_counts()",
"_____no_output_____"
],
[
"df['SALE_PRICE'].value_counts()",
"_____no_output_____"
],
[
"df['SALE_PRICE'].isna().sum()",
"_____no_output_____"
],
[
"df_subset['SALE_PRICE'].between(10000,2000000)",
"_____no_output_____"
],
[
"df_subset = df.copy()\ndf_subset = df_subset[df_subset['SALE_PRICE'].between(10000,2000000)]\ndf_subset = df_subset[df_subset['BUILDING_CLASS_CATEGORY'] == '01 ONE FAMILY DWELLINGS']\ndf_subset",
"_____no_output_____"
],
[
"df_subset.columns",
"_____no_output_____"
],
[
"import datetime\n\ndf_subset['SALE_DATE'] = pd.to_datetime(df_subset['SALE_DATE'], infer_datetime_format=True)\ndf_subset['SALE_DATE'].dtype",
"_____no_output_____"
],
[
"train = df_subset[df_subset['SALE_DATE'].dt.month < 4]\nprint(train['SALE_DATE'].dt.month.value_counts())\n\ntest = df_subset[df_subset['SALE_DATE'].dt.month == 4]\nprint(test['SALE_DATE'].dt.month.value_counts())",
"1 966\n3 810\n2 772\nName: SALE_DATE, dtype: int64\n4 651\nName: SALE_DATE, dtype: int64\n"
],
[
"train.select_dtypes(exclude='number').describe().T",
"_____no_output_____"
],
[
"target = 'SALE_PRICE'\nhigh_cardinality = ['ADDRESS','LAND_SQUARE_FEET','SALE_DATE']\nfeatures = train.columns.drop([target] + high_cardinality)\n\nX_train = train[features]\ny_train = train[features]\n\nX_test = train[features]\ny_train = train[features]",
"_____no_output_____"
],
[
"import category_encoders as ce\nencoder = ce.OneHotEncoder(use_cat_names=True)\n\nX_train = encoder.fit_transform(X_train)\nX_test = encoder.transform(X_test)",
"_____no_output_____"
],
[
"print(X_train.shape)\nX_train.head()",
"(2548, 50)\n"
],
[
"from sklearn.feature_selection import f_regression, SelectKBest\nselector = SelectKBest(score_func = f_regression, k=15)\nX_train_selected = selector.fit_transform(X_train, y_train)\nX_test_selected = selector.transform(X_test)\nX_train_selected.shape",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7210174fbdf72fb12212c21d2cb3a321c513997 | 266,515 | ipynb | Jupyter Notebook | sample_comp/01_compare_outputs.ipynb | hectorcanovas/data_mining_Gaia_DR2 | c43503891a15881f57fee082ca3c3242b4b105c3 | [
"MIT"
] | 1 | 2019-10-07T12:57:43.000Z | 2019-10-07T12:57:43.000Z | sample_comp/01_compare_outputs.ipynb | hectorcanovas/data_mining_Gaia_DR2 | c43503891a15881f57fee082ca3c3242b4b105c3 | [
"MIT"
] | null | null | null | sample_comp/01_compare_outputs.ipynb | hectorcanovas/data_mining_Gaia_DR2 | c43503891a15881f57fee082ca3c3242b4b105c3 | [
"MIT"
] | null | null | null | 1,730.616883 | 261,568 | 0.960449 | [
[
[
"## Compare the DBSCAN, OPTICS, HDBSCAN outputs\n### Output: Fig. 6 in Canovas+2019",
"_____no_output_____"
]
],
[
[
"import os, glob, getpass, sys\nimport warnings\n\nimport numpy as np\nimport itertools\nimport matplotlib.pyplot as plt\nfrom astropy.table import Table, join, vstack, hstack, Column, MaskedColumn, unique\nfrom astropy.utils.exceptions import AstropyWarning\n\nuser = getpass.getuser()\nsys.path.append('/Users/' + user + '/Dropbox/my_python_packages')\npath = '../'\nsys.path.append(path)\nfrom gaia.cluster_comparison_n import Comparison_n as Comparison\nfrom extra_codes import sample_comp as samp_comp",
"_____no_output_____"
],
[
"# Path to data ================================\nwarnings.simplefilter('ignore', AstropyWarning)\npath_0 = path + 'sample_control/'\npath_1 = path + 'sample_clusters/cl_'\ncols = ['ra', 'dec', 'parallax', 'pmra', 'pmdec', 'source_id']\n\n# Control Data ================================\npath_control = path_0 + 'OPH___control_sample.vot'\n\n# Cluster Data ================================\ntabs_dbscan = glob.glob(path_1 + 'dbscan/cl_dbscan*vot') ; tabs_dbscan.sort()\ntabs_hdbscan = glob.glob(path_1 + 'hdbscan/cl_hdbscan*vot') ; tabs_hdbscan.sort()\ntabs_optics = glob.glob(path_1 + 'optics/cl_optics*vot') ; tabs_optics.sort()",
"_____no_output_____"
],
[
"# Read Data ===================================\nlabel_db = ['mPts = ' + inp[inp.find('mpts')+5:inp.find('.vot')] for inp in tabs_dbscan]\nlabel_op = ['mPts = ' + inp[inp.find('mpts')+5:inp.find('.vot')] for inp in tabs_optics]\nlabel_hd = ['mCls = ' + inp[inp.find('mcls')+5:inp.find('.vot')] for inp in tabs_hdbscan]\n\n\n# Cosmetics for DBscan label:\nfor i in range(2):\n label_db[i] = label_db[i].replace('= 0', '= ')\n \n \ncl_dbscan_l, cl_optics_l, cl_hdbscan_l = [],[],[]\nfor i in range(len(tabs_dbscan)):\n cl_dbscan_l.append (samp_comp.read_cluster(inp_path = tabs_dbscan[i], label = label_db[i], cols=cols))\n cl_optics_l.append (samp_comp.read_cluster(inp_path = tabs_optics[i], label = label_op[i], cols=cols))\n cl_hdbscan_l.append(samp_comp.read_cluster(inp_path = tabs_hdbscan[i], label = label_hd[i], cols=cols))\n\ncontrol = samp_comp.read_cluster(inp_path = path_control, label = '', cols=cols)\ncl_list = [cl_dbscan_l, cl_optics_l, cl_hdbscan_l] ",
"_____no_output_____"
],
[
"# Make Plot ===================================\nfig = plt.figure(figsize=[30,35])\nplt.subplots_adjust(hspace = 0.25)\n\ncolors = itertools.cycle([\"blue\", \"limegreen\", \"red\"])\npl_idx = itertools.cycle([[331,332,333], [334,335,336], [337,338,339]])\nylabels = itertools.cycle(['DBSCAN #Objects', 'OPTICS #Objects', 'HDBSCAN #Objects'])\nftsize = 38\nx1lim = None\nx2lim = [-20,0]\nx3lim = [-32.5,-17.5]\n\nfor clusters in cl_list:\n inp_list = Comparison()\n inp_list.load_clusters(control=control, cluster_list=clusters)\n hists = inp_list.plot_3_hist(colors=colors, linewidth=5, fig=False, pl_indexes = next(pl_idx), x1lim=x1lim, x2lim=x2lim, x3lim=x3lim, x1_bins=5, x2_bins=5, x3_bins=5, ftsize=ftsize, ylabel_1=next(ylabels))\n \nplt.show()\nfig.savefig('01_compare_outputs.pdf', bbox_inches = 'tight', overwrite = True)",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e72104a9742a0f719dfbea2f38a0fac23d904ff0 | 144,596 | ipynb | Jupyter Notebook | index.ipynb | fomightez/length_binder | 9f72660adbacf47b6b6545c2cc8e566c530dbc40 | [
"MIT"
] | 2 | 2018-06-27T02:45:01.000Z | 2018-06-27T02:45:03.000Z | index.ipynb | fomightez/length_binder | 9f72660adbacf47b6b6545c2cc8e566c530dbc40 | [
"MIT"
] | null | null | null | index.ipynb | fomightez/length_binder | 9f72660adbacf47b6b6545c2cc8e566c530dbc40 | [
"MIT"
] | null | null | null | 77.949326 | 34,671 | 0.702136 | [
[
[
"# Protein length in several organisms\n\nThis notebook collects and plots protein length for several organisms.\n\nData sources are specified [here](https://github.com/fomightez/length_binder#data-sources).",
"_____no_output_____"
]
],
[
[
"from intermine.webservice import Service\nservice = Service(\"https://yeastmine.yeastgenome.org:443/yeastmine/service\")\nquery = service.new_query(\"Protein\")\nquery.add_view(\n \"genes.primaryIdentifier\", \"genes.secondaryIdentifier\", \"symbol\", \"length\",\n \"molecularWeight\", \"pI\", \"genes.featureType\", \"genes.sgdAlias\",\n \"genes.description\"\n)\nquery.add_sort_order(\"Protein.symbol\", \"ASC\")\nquery.add_constraint(\"genes.featureType\", \"=\", \"intein_encoding_region\", code = \"H\")\nquery.add_constraint(\"genes.featureType\", \"=\", \"blocked_reading_frame\", code = \"E\")\nquery.add_constraint(\"genes.qualifier\", \"!=\", \"Dubious\", code = \"B\")\nquery.add_constraint(\"genes.qualifier\", \"IS NULL\", code = \"C\")\nquery.add_constraint(\"genes.status\", \"=\", \"Active\", code = \"D\")\nquery.add_constraint(\"genes.featureType\", \"=\", \"ORF\", code = \"F\")\nquery.add_constraint(\"genes.featureType\", \"=\", \"transposable_element_gene\", code = \"G\")\nquery.add_constraint(\"organism.name\", \"=\", \"Saccharomyces cerevisiae\", code = \"A\")\nquery.set_logic(\"A and (B or C) and D and (F or G or E or H)\")\n\n#for row in query.rows():\n# if row[\"length\"] > 1500:\n# print (row[\"genes.primaryIdentifier\"], row[\"genes.secondaryIdentifier\"], row[\"symbol\"], row[\"length\"])\n\nsc_prot_length = []\nfor row in query.rows():\n #print (row[\"length\"])\n sc_prot_length.append(row[\"length\"])\n\n#max(sc_prot_length)\nprint(\"The number of S. cerevisiae (yeast) proteins retrived is {}.\".format(len(sc_prot_length)))",
"The number of S. cerevisiae (yeast) proteins retrived is 6012.\n"
],
[
"from Bio import SeqIO\n\n# Fly\nrecords = []\nfor record in SeqIO.parse(\"uniprot-proteomeUP000000803.fasta\", \"fasta\"):\n records.append(record)\n\nfly_prot_length = []\nfor record in records:\n #print (len(record.seq))\n fly_prot_length.append(len(record.seq))\n \n#print(len(fly_prot_length))\nprint(\"The number of Drosophila melanogaster (fly) proteins available \"\n \"is {}.\".format(len(fly_prot_length)))\n\n# Arabidopsis\nrecords = []\nfor record in SeqIO.parse(\"TAIR9_pep_20090619.fa\", \"fasta\"):\n records.append(record)\n\nthale_cress_prot_length = []\nfor record in records:\n #print (len(record.seq))\n thale_cress_prot_length.append(len(record.seq))\n \n#print(len(thale_cress_prot_length))\nprint(\"The number of Arabidopsis thaliana (thale cress) proteins available \"\n \"is {}.\".format(len(thale_cress_prot_length)))\n",
"The number of Drosophila melanogaster (fly) proteins available is 21938.\nThe number of Arabidopsis thaliana (thale cress) proteins available is 33410.\n"
],
[
"import pandas as pd\n'''\ndf = pd.DataFrame([thale_cress_prot_length, fly_prot_length, sc_prot_length], ['thale_cress', 'fly', 'yeast']).T # based on\n# https://stackoverflow.com/a/46431740/8508004\n'''\nprot_length = thale_cress_prot_length + fly_prot_length + sc_prot_length\norganism = ([\"thale_cress\"] * len(thale_cress_prot_length) + \n [\"fly\"] * len(fly_prot_length) + \n [\"yeast\"] * len(sc_prot_length))\ndf = pd.DataFrame(list(zip(prot_length, organism)), columns=['length', 'organism'])\ndf.head()",
"_____no_output_____"
],
[
"df.max(0).length",
"_____no_output_____"
],
[
"%matplotlib notebook\nimport seaborn as sns\nax = sns.boxplot(x=\"organism\", y=\"length\", data=df, palette=\"Set2\")\n#ax = sns.swarmplot(x=\"organism\", y=\"length\", data=df, color=\".25\")",
"_____no_output_____"
],
[
"%matplotlib notebook\nax2 = sns.boxplot(x=\"organism\", y=\"length\", data=df, palette=\"Set2\")\nax2.set(ylim=(0,1500));",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7210bd1996ea562c57ba299602e7609e6a78989 | 9,617 | ipynb | Jupyter Notebook | notebooks/plot-car-park-occupancy-6-weeks.ipynb | urbanobservatory/movement-dashboard | 1f77e988acb9cd3b884ba641a841434ebc078181 | [
"MIT"
] | null | null | null | notebooks/plot-car-park-occupancy-6-weeks.ipynb | urbanobservatory/movement-dashboard | 1f77e988acb9cd3b884ba641a841434ebc078181 | [
"MIT"
] | 3 | 2020-03-20T09:25:42.000Z | 2020-06-02T12:25:50.000Z | notebooks/plot-car-park-occupancy-6-weeks.ipynb | urbanobservatory/movement-dashboard | 1f77e988acb9cd3b884ba641a841434ebc078181 | [
"MIT"
] | 1 | 2020-03-19T16:37:58.000Z | 2020-03-19T16:37:58.000Z | 34.469534 | 393 | 0.51149 | [
[
[
"import matplotlib\nimport pandas as pd\nimport numpy as np\nimport json\nimport math\nimport urllib.request\nimport dateutil.parser\nimport dateutil.rrule\nimport dateutil.tz\nimport datetime\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom textwrap import wrap\n\nmatplotlib.rcParams.update({\n 'font.size': 13,\n 'timezone': 'Europe/London'\n})",
"_____no_output_____"
],
[
"# Used across all of the plots\ntzLocal = dateutil.tz.gettz('Europe/London')\ndateToday = datetime.datetime.combine(datetime.date.today(), datetime.datetime.min.time()).replace(tzinfo=tzLocal)\n\ncolourUp = '#f64a8a'\ncolourDown = '#233067'\n\nresampleFrequency = 900",
"_____no_output_____"
]
],
[
[
"# Car park occupancy across Tyne and Wear\n\nThe data represents the car parks with ANPR at the entry and exit, with data collected through Tyne and Wear UTMC. This is not all car parks.\n\nYou can [download the underlying counts as a CSV file](https://covid.view.urbanobservatory.ac.uk/output/recent-car-park-occupancy-pd.csv) and [accompanying metadata](https://covid.view.urbanobservatory.ac.uk/output/recent-car-park-metadata-pd.csv), or access it through [an API](https://api.newcastle.urbanobservatory.ac.uk/api/v2/sensors/entity?metric=%22Occupied%20spaces%22&page=1).\n",
"_____no_output_____"
]
],
[
[
"dfCarParks = pd.read_pickle('../cache/recent-car-park-occupancy-pd.pkl')\ncarParkMetadata = pd.read_pickle('../cache/recent-car-park-metadata-pd.pkl')\nprint('Last data obtained %s' \n % (np.max(dfCarParks.index).strftime('%d %B %Y %H:%M')))",
"_____no_output_____"
],
[
"def plotCarParkTimeseries(type='continuous', historicCutOffDays=28):\n dfCarParksRecent = dfCarParks[dfCarParks.index >= dateToday - pd.Timedelta(days=historicCutOffDays)]\n dfCarParkMissingFreq = dfCarParksRecent \\\n .isna() \\\n .sum(axis=0) \\\n .apply(lambda c: c / len(dfCarParksRecent.index))\n dfCarParkPlotList = sorted(\n dfCarParkMissingFreq[dfCarParkMissingFreq < 0.5].index,\n key=lambda carPark: carParkMetadata[carParkMetadata.index == carPark]['capacity'].values[0],\n reverse=True\n )\n\n if type == 'daily':\n dfCarParksRecent = dfCarParksRecent.resample('24H').sum() / (3600 / resampleFrequency)\n\n fig, axs = plt.subplots(\n len(dfCarParkPlotList), 1,\n figsize = (18, 1.5 * len(dfCarParkPlotList))\n )\n\n plotIndex = 0\n\n for carPark in dfCarParkPlotList:\n carParkMeta = carParkMetadata[carParkMetadata.index == carPark]\n ax = axs[plotIndex]\n ax.set_title(\n '%s (%s with %u spaces)' % (\n carPark,\n carParkMeta['district'].values[0],\n carParkMeta['capacity'].values[0]\n ),\n loc='left',\n fontdict={ 'horizontalalignment': 'left', 'fontsize': 12 }\n )\n ax.margins(x=0, y=0)\n if type == 'daily':\n dfWeekdays = dfCarParksRecent[dfCarParksRecent.index.to_series().apply(\n lambda t: t.strftime('%A') not in ['Saturday', 'Sunday']\n )][carPark]\n dfWeekends = dfCarParksRecent[dfCarParksRecent.index.to_series().apply(\n lambda t: t.strftime('%A') in ['Saturday', 'Sunday']\n )][carPark]\n\n ax.bar(\n dfWeekdays.index,\n dfWeekdays,\n color=colourDown,\n label='Vehicle-hours on weekdays'\n )\n ax.bar(\n dfWeekends.index,\n dfWeekends,\n color=colourUp,\n label='Vehicle-hours on weekends'\n )\n elif type == 'continuous':\n ax.fill_between(\n dfCarParksRecent[carPark].index,\n dfCarParksRecent[carPark],\n color=colourDown,\n where=dfCarParksRecent.index.to_series().apply(\n lambda t: t.strftime('%A') not in ['Saturday', 'Sunday']\n ),\n label='Occupied spaces on weekdays'\n )\n ax.fill_between(\n dfCarParksRecent[carPark].index,\n dfCarParksRecent[carPark],\n color=colourUp,\n where=dfCarParksRecent.index.to_series().apply(\n lambda t: t.strftime('%A') in ['Saturday', 'Sunday']\n ),\n label='Occupied spaces on weekend'\n )\n\n ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1, byweekday=mdates.MO))\n ax.xaxis.set_tick_params(which='major', pad=15)\n ax.xaxis.set_minor_locator(mdates.DayLocator(interval=1))\n\n if ax == axs[-1]:\n ax.set_xlabel('Date')\n\n if historicCutOffDays > 75:\n timeLocatorMajor = mdates.AutoDateLocator(minticks=10, maxticks=30)\n conciseZeroFormats = ['', '%Y', '%b', '%d-%b', '%H:%M', '%H:%M']\n conciseOffsetFormats = ['', '%Y', '%b-%Y', '%d-%b-%Y-%b', '%d-%b-%Y', '%d-%b-%Y %H:%M']\n ax.xaxis.set_tick_params(which='major', pad=0)\n ax.xaxis.set_major_locator(timeLocatorMajor)\n ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator=timeLocatorMajor, zero_formats=conciseZeroFormats, offset_formats=conciseOffsetFormats))\n else:\n dataFormatMajor = mdates.DateFormatter('%a %d %b')\n ax.xaxis.set_major_formatter(dataFormatMajor)\n ax.xaxis.set_minor_formatter(mdates.DateFormatter('%d'))\n else:\n ax.xaxis.set_ticklabels([]);\n\n if ax == axs[0]:\n ax.legend(\n loc='upper right',\n ncol=2,\n fontsize=11,\n frameon=False,\n bbox_to_anchor=(1.0, 1.35)\n )\n\n plotIndex = plotIndex + 1\n\n plt.tight_layout()\n fig.subplots_adjust(hspace=0.4)\n plt.show()",
"_____no_output_____"
]
],
[
[
"## Daily occupancy of car parks during last 6 weeks\n\nThe below plot shows the profile of the car park occupancy within the last month or so, rather than being aggregated to a daily level.",
"_____no_output_____"
]
],
[
[
"# Continuous plot of areas for the last N days\nplotCarParkTimeseries('continuous', 42)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7211f6e94f61e420f9d492079ecda712208d6b4 | 2,713 | ipynb | Jupyter Notebook | examples/3_Functions.ipynb | GATWE/ipyaladin | fd20e4d2171edb37c0c6d4dd739693b7e2bebd78 | [
"BSD-3-Clause"
] | 75 | 2017-06-29T09:29:53.000Z | 2022-03-18T16:11:11.000Z | examples/3_Functions.ipynb | GATWE/ipyaladin | fd20e4d2171edb37c0c6d4dd739693b7e2bebd78 | [
"BSD-3-Clause"
] | 26 | 2017-07-13T17:23:40.000Z | 2022-03-09T19:08:55.000Z | examples/3_Functions.ipynb | GATWE/ipyaladin | fd20e4d2171edb37c0c6d4dd739693b7e2bebd78 | [
"BSD-3-Clause"
] | 15 | 2017-07-13T20:55:59.000Z | 2022-02-07T12:38:44.000Z | 22.608333 | 148 | 0.540361 | [
[
[
"import ipyaladin as ipyal",
"_____no_output_____"
],
[
"aladin= ipyal.Aladin(survey= 'P/DSS2/red',\n fov= 10,\n target= 'LMC',\n reticle_color= '#ff89ff')\naladin",
"_____no_output_____"
],
[
"url= 'http://vizier.u-strasbg.fr/viz-bin/votable?-source=HIP2&-c=LMC&-out.add=_RAJ,_DEJ&-oc.form=dm&-out.meta=DhuL&-out.max=9999&-c.rm=180'\noptions= {'sourceSize':12, 'color': '#f08080'}\naladin.add_catalog_from_URL(url, options)",
"_____no_output_____"
],
[
"def getObjectData(data):\n return data\n\ndef getObjectRaDecProduct(data):\n return data['ra']*data['dec']\n\n# when trigerred, the listeners on the js side of the application will send a json object whose parameter data\n# will be used by the python functions\n# (data is a litteral object on the js side, it will be converted as a dictionary object on the python side)\naladin.add_listener('objectHovered', getObjectRaDecProduct)\naladin.add_listener('objectClicked', getObjectData)",
"_____no_output_____"
],
[
"aladin_bis= ipyal.Aladin(target='269.956288 -23.823863', fov=1)\naladin_bis",
"_____no_output_____"
],
[
"aladin_bis.set_color_map('rainbow')",
"_____no_output_____"
],
[
"aladin_bis.get_JPEG_thumbnail()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e72124f195373fcacb730271067c45985e3a57d1 | 5,023 | ipynb | Jupyter Notebook | .ipynb_checkpoints/ReadMe-checkpoint.ipynb | gy18gs/TheBlackDeath | 3bad9b6c138af1a111d5d0b02facd8937075dc6a | [
"BSD-2-Clause"
] | null | null | null | .ipynb_checkpoints/ReadMe-checkpoint.ipynb | gy18gs/TheBlackDeath | 3bad9b6c138af1a111d5d0b02facd8937075dc6a | [
"BSD-2-Clause"
] | null | null | null | .ipynb_checkpoints/ReadMe-checkpoint.ipynb | gy18gs/TheBlackDeath | 3bad9b6c138af1a111d5d0b02facd8937075dc6a | [
"BSD-2-Clause"
] | null | null | null | 55.197802 | 586 | 0.678081 | [
[
[
"# The Black Death Project: ReadMe",
"_____no_output_____"
],
[
"#### This project focuses on the Black Death, a plague that swept through London in 1665. The data simulates the weekly death rate for the parishes in London, based on the parish population and average rats caught per week.\n# •\n#### The submission for this project includes:\n#### • This ReadMe - *introduction to the project and the software intention*\n#### • TheBlackDeath.ipynb - *the project itself*\n#### • deathmap.txt - *the textfile in which the death map data is stored*\n#### • death_parishes.txt - *the parish death rate file*\n#### • death_rats.txt - *the rat-catch file*\n#### • BlackDeathUML.jpeg - *the UML diagram of the program*\n#### • license.txt - *the license for the code used in the project*\n# •",
"_____no_output_____"
],
[
"## *SOFTWARE INTENTION*\n#### This Jupyter notebook is designed to simulate the average weekly deaths from the Black Plague in 16 London parishes, as calculated by a given equation:\n### d = (0.8 x r) x (1.3 x p)\n#### - This initial equation is what is used to combine the rats and parishes CSV files, in order to produce a raster grid to demonstrate the weekly deaths. The produced 'deathmap.txt' (as found on the notebook homepage) is the result of combining the two grids in the equation.\n#### - The interactive part of the notebook found from Step 5 onwards, enables the user to change the values for the r (rats) and p (parishes) part of the average weekly deaths equation, in order to create a new outcome of weekly deaths.\n#### - This interactive feature allows the user to mimic different scenarios of the Black Plague: *users can greatly increase the amount of rats caught, to favour the population, or greatly increase the population density to give a better chance of survival!*\n# •\n## Is this a perfect model? No...\n## *SOFTWARE DEVELOPMENT GOING FORWARD*\n#### Although the equation can simulate the average weekly deaths in the parishes, it is not a realistic model of population change... *to have a realistic model of population change, a separate model would be needed which allows the user to vary the average rat catch ONLY, and have a set population amount...*... this would look something like: deaths = (rats caught that week) x (previous week's population). *This would take into account the deaths of the previous week, and use that figure to calculate the average weekly death rate as the population decreases over time.*\n# •\n\n## *OTHER COMMENTS TO NOTE*\n#### As well as displaying the weekly death rate from the given equation, I wanted this program to be interactive, so that the user could influence the average death rate outcome by altering the parameters. Sliding scale bars seemed the most appropriate way to fulfil this, as they allow the user to physically alter the death rate on a scale and compare the outcome of their choices. This is reflected in the calculated Average Weekly Death Rate, as printed above the new Death Rate map, in Part 6.\n#### This notebook is tested throughout, with print statements to display old and altered death rate calculations, and values from the CSV file.\n#### The UML diagram, *BlackDeathUML.jpeg* provides brief detail on the structure of the Black Death project.",
"_____no_output_____"
],
[
"## ____\n### Bibliography and sources\n\n##### Matplotlib code: https://www.geog.leeds.ac.uk/courses/computing/practicals/python/agent-framework/part2/4.html \n##### Raster maps of parish deaths and average rat catch: https://www.geog.leeds.ac.uk/courses/computing/study/core-python/assessment2/death.html \n##### Slider widget code and import information: - https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20List.html - https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Basics.html - https://towardsdatascience.com/a-very-simple-demo-of-interactive-controls-on-jupyter-notebook-4429cf46aabd - https://ipython-books.github.io/33-mastering-widgets-in-the-jupyter-notebook/",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7212512b8d0f61482b52e9eadf0dc3cd9257323 | 7,535 | ipynb | Jupyter Notebook | examples/Robertson_kinetics.ipynb | jeremyagray/chempy | 2afe591859150425964a8cb3bc749cb601ad3087 | [
"BSD-2-Clause"
] | 340 | 2015-10-30T03:41:05.000Z | 2022-03-31T05:01:17.000Z | examples/Robertson_kinetics.ipynb | jeremyagray/chempy | 2afe591859150425964a8cb3bc749cb601ad3087 | [
"BSD-2-Clause"
] | 80 | 2015-11-03T13:31:23.000Z | 2022-03-31T16:46:19.000Z | examples/Robertson_kinetics.ipynb | jeremyagray/chempy | 2afe591859150425964a8cb3bc749cb601ad3087 | [
"BSD-2-Clause"
] | 75 | 2016-06-06T19:55:48.000Z | 2022-03-19T23:39:13.000Z | 24.704918 | 164 | 0.540146 | [
[
[
"from collections import defaultdict\nfrom ipywidgets import interact\nimport matplotlib.pyplot as plt\nfrom chempy import Reaction, Substance, ReactionSystem\nfrom chempy.kinetics.ode import get_odesys\nfrom chempy.kinetics.analysis import plot_reaction_contributions\nfrom chempy.printing.tables import UnimolecularTable, BimolecularTable\nfrom chempy.util.graph import rsys2graph\nimport sympy\nsympy.init_printing()\n%matplotlib inline",
"_____no_output_____"
],
[
"A, B, C, D = map(Substance, 'ABCD')\nOne = sympy.S.One\nreactions = r0, r1, r2 = [\n Reaction({'A'}, {'B'}, 4*One/100, name='R1: A cons.'),\n Reaction({'B', 'C'}, {'A', 'C'}, 10**(4*One), name='R2: A reform.'),\n Reaction({'B': 2}, {'B', 'C'}, 3*10**(7*One), name='R3: C form.')\n]\nrsys = ReactionSystem(reactions, (A, B, C))\nrsys",
"_____no_output_____"
],
[
"uni, not_uni = UnimolecularTable.from_ReactionSystem(rsys)\nbi, not_bi = BimolecularTable.from_ReactionSystem(rsys)\nassert not (not_uni & not_bi), \"There are only uni- & bi-molecular reactions in this set\"",
"_____no_output_____"
],
[
"uni",
"_____no_output_____"
],
[
"bi",
"_____no_output_____"
],
[
"rsys2graph(rsys, 'robertson.png', save='.')\nfrom IPython.display import Image; Image('robertson.png')",
"_____no_output_____"
],
[
"odesys, extra = get_odesys(rsys, include_params=True)\nodesys.exprs",
"_____no_output_____"
],
[
"odesys.get_jac()",
"_____no_output_____"
],
[
"c0 = defaultdict(float, {'A': 1})\nresult = odesys.integrate(1e10, c0, integrator='cvode', nsteps=2000)\n{k: v for k, v in result.info.items() if not k.startswith('internal')}",
"_____no_output_____"
],
[
"extra['rate_exprs_cb'](result.xout, result.yout)",
"_____no_output_____"
],
[
"result.plot(xscale='log', yscale='log')",
"_____no_output_____"
],
[
"fig, axes = plt.subplots(2, 2, figsize=(14, 6))\nplot_reaction_contributions(result, rsys, extra['rate_exprs_cb'], 'AB', axes=axes[0, :])\nplot_reaction_contributions(result, rsys, extra['rate_exprs_cb'], 'AB', axes=axes[1, :],\n relative=True, yscale='linear')\nplt.tight_layout()",
"_____no_output_____"
]
],
[
[
"We could also have parsed the reactions from a string:",
"_____no_output_____"
]
],
[
[
"str_massaction = \"\"\"\nA -> B; 'k1'\nB + C -> A + C; 'k2'\n2 B -> B + C; 'k3'\n\"\"\"",
"_____no_output_____"
],
[
"rsys3 = ReactionSystem.from_string(str_massaction, substance_factory=lambda formula: Substance(formula))",
"_____no_output_____"
],
[
"rsys3.substance_names()",
"_____no_output_____"
],
[
"odesys3, extra3 = get_odesys(rsys3, include_params=False, lower_bounds=[0, 0, 0])\nextra3['param_keys'], extra3['unique']",
"_____no_output_____"
],
[
"odesys3.exprs, odesys3.params, odesys3.names, odesys3.param_names",
"_____no_output_____"
],
[
"def integrate_and_plot(A0=1.0, B0=0.0, C0=0.0, lg_k1=-2, lg_k2=4, lg_k3=7, lg_tend=9):\n plt.figure(figsize=(14, 4))\n tout, yout, info = odesys3.integrate(\n 10**lg_tend, {'A': A0, 'B': B0, 'C': C0},\n {'k1': 10**lg_k1, 'k2': 10**lg_k2, 'k3': 10**lg_k3},\n integrator='cvode', nsteps=3000)\n plt.subplot(1, 2, 1)\n odesys3.plot_result(xscale='log', yscale='log')\n plt.legend(loc='best')\n plt.subplot(1, 2, 2)\n plt.plot(tout[tout<.05], yout[tout<.05, odesys3.names.index('B')])\n _ = plt.legend('best')\ninteract(integrate_and_plot) #, **kw)",
"_____no_output_____"
],
[
"# We could also have used SymPy to construct symbolic rates:\nimport sympy\nrsys_sym = ReactionSystem.from_string(\"\"\"\nA -> B; sp.Symbol('k1')\nB + C -> A + C; sp.Symbol('k2')\n2 B -> B + C; sp.Symbol('k3')\n\"\"\", rxn_parse_kwargs=dict(globals_={'sp': sympy}), substance_factory=lambda formula: Substance(formula))\nodesys_sym, _ = get_odesys(rsys_sym, params=True)\nfor attr in 'exprs params names param_names'.split():\n print(getattr(odesys_sym, attr))",
"_____no_output_____"
]
],
[
[
"For larger systems it is easy to loose track of what substances are actually playing a part, here the html tables can help (note the yellow background color):",
"_____no_output_____"
]
],
[
[
"rsys.substances['D'] = D\nuni, not_uni = UnimolecularTable.from_ReactionSystem(rsys)\nuni",
"_____no_output_____"
],
[
"bi, not_bi = BimolecularTable.from_ReactionSystem(rsys)\nbi",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7212cdb06bb3264e23c3b6b63843282dc060b79 | 13,799 | ipynb | Jupyter Notebook | [Self Help] Python/Notes - Learning Resources/Python Statements/[Notes] Useful Operators.ipynb | amuganda/MacOS_Repository_Restructured | e66c880aa5780ae839ca6a428c6d786761901338 | [
"MIT"
] | null | null | null | [Self Help] Python/Notes - Learning Resources/Python Statements/[Notes] Useful Operators.ipynb | amuganda/MacOS_Repository_Restructured | e66c880aa5780ae839ca6a428c6d786761901338 | [
"MIT"
] | 1 | 2022-02-28T03:05:30.000Z | 2022-02-28T03:05:30.000Z | [Self Help] Python/Notes - Learning Resources/Python Statements/[Notes] Useful Operators.ipynb | amuganda/MacOS_Repository_Restructured | e66c880aa5780ae839ca6a428c6d786761901338 | [
"MIT"
] | null | null | null | 16.446961 | 77 | 0.419885 | [
[
[
"Range",
"_____no_output_____"
]
],
[
[
"myList = [1,2,3]",
"_____no_output_____"
],
[
"for num in range(10):\n print(num)",
"0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n"
],
[
"for num in range(3,10):\n print(num)",
"3\n4\n5\n6\n7\n8\n9\n"
],
[
"for num in range(3,15,3):\n print(num)",
"3\n6\n9\n12\n"
],
[
"list(range(0,22,3))",
"_____no_output_____"
]
],
[
[
"Enumerate",
"_____no_output_____"
]
],
[
[
"indexCount = 0\n\nfor letter in 'abcdef':\n print ('At index {} the letter is {}'.format(indexCount,letter))\n indexCount += 1",
"At index 0 the letter is a\nAt index 1 the letter is b\nAt index 2 the letter is c\nAt index 3 the letter is d\nAt index 4 the letter is e\nAt index 5 the letter is f\n"
],
[
"indexCount = 0\nword = 'abcde'\nfor letter in word:\n print (word[indexCount])\n indexCount += 1",
"a\nb\nc\nd\ne\n"
],
[
"word = 'abcde'\n\nfor item in enumerate(word):\n print(item)",
"(0, 'a')\n(1, 'b')\n(2, 'c')\n(3, 'd')\n(4, 'e')\n"
],
[
"word = 'abcde'\n\nfor index,letter in enumerate(word):\n print(index)\n print(letter)",
"0\na\n1\nb\n2\nc\n3\nd\n4\ne\n"
]
],
[
[
"Pairing/Packing items ",
"_____no_output_____"
]
],
[
[
"myList1 = [1,2,3,4,5,6]\nmyList2 = ['a','b','c','d','e','f']",
"_____no_output_____"
],
[
"for item in zip (myList1,myList2):\n print(item)",
"(1, 'a')\n(2, 'b')\n(3, 'c')\n(4, 'd')\n(5, 'e')\n(6, 'f')\n"
],
[
"myList1 = [1,2,3,4,5,6]\nmyList2 = ['a','b','c','d','e','f']\nmyList4 = [100,200,300,400,500,1600]",
"_____no_output_____"
],
[
"for item in zip (myList1,myList2,myList4):\n print(item)",
"(1, 'a', 100)\n(2, 'b', 200)\n(3, 'c', 300)\n(4, 'd', 400)\n(5, 'e', 500)\n(6, 'f', 1600)\n"
]
],
[
[
"An example of 'casting'",
"_____no_output_____"
]
],
[
[
"list(zip(myList1,myList2,myList4))",
"_____no_output_____"
],
[
"'x' in [1,2,3]",
"_____no_output_____"
],
[
"'x' in ['x','y','z']",
"_____no_output_____"
],
[
"'myKey' in {'myKey':345}",
"_____no_output_____"
],
[
"d = {'myKey':345}\n\n345 in d.keys()",
"_____no_output_____"
],
[
"myList = [10,20,30,40,50,60,80,100]",
"_____no_output_____"
],
[
"max(myList)",
"_____no_output_____"
],
[
"min(myList)",
"_____no_output_____"
]
],
[
[
"Importing a library",
"_____no_output_____"
]
],
[
[
"from random import shuffle\nmyList = [1,2,3,4,5,6,7,8,9,100,101,3284]",
"_____no_output_____"
]
],
[
[
"NB. The below is called an in place function",
"_____no_output_____"
]
],
[
[
"shuffle(myList)",
"_____no_output_____"
],
[
"myList",
"_____no_output_____"
],
[
"from random import randint\nrandint(0,100)",
"_____no_output_____"
],
[
"myNum = randint(0,10)\nmyNum\n",
"_____no_output_____"
]
],
[
[
"Input\n\nWhen using 'Input' whatever is entered is always saved as a 'String'",
"_____no_output_____"
]
],
[
[
"result = input ('What Is Your Favourite Colour:' )",
"What Is Your Favourite Colour:Yellow\n"
],
[
"result",
"_____no_output_____"
],
[
"result = input ('What Is Your Favourite Number:' )",
"What Is Your Favourite Number:28\n"
],
[
"result",
"_____no_output_____"
]
],
[
[
"Possible means to convert a 'Str' to an 'Int'",
"_____no_output_____"
]
],
[
[
"type(result)",
"_____no_output_____"
],
[
"int(result)",
"_____no_output_____"
],
[
"x = int(result)",
"_____no_output_____"
],
[
"x",
"_____no_output_____"
],
[
"result = input ('What Is Your Favourite Number:' )\nx = int(result)\n\nx",
"What Is Your Favourite Number:44\n"
],
[
"type(result)",
"_____no_output_____"
],
[
"print(type(x))",
"<class 'int'>\n"
]
],
[
[
"Refactored ",
"_____no_output_____"
]
],
[
[
"result = int(input ('What Is Your Favourite Number:' ))\ntype(result)",
"What Is Your Favourite Number:44\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e72132841475568f00fa9c0907fb6056badc3b37 | 29,165 | ipynb | Jupyter Notebook | Notebooks/RNN_practicals_X.ipynb | lasofivec/dataflowr | 68697f57968c4b8bc2669375f257a55057125f96 | [
"Apache-2.0"
] | null | null | null | Notebooks/RNN_practicals_X.ipynb | lasofivec/dataflowr | 68697f57968c4b8bc2669375f257a55057125f96 | [
"Apache-2.0"
] | null | null | null | Notebooks/RNN_practicals_X.ipynb | lasofivec/dataflowr | 68697f57968c4b8bc2669375f257a55057125f96 | [
"Apache-2.0"
] | null | null | null | 27.618371 | 171 | 0.506703 | [
[
[
"# RNN practicals\n\nThis jupyter notebook allows you to reproduce and explore the results presented in the [lecture on RNN](https://mlelarge.github.io/dataflowr-slides/X/lesson5.html#1)",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom collections import OrderedDict\nimport scipy.special\nfrom scipy.special import binom\nimport matplotlib.pyplot as plt\nimport time",
"_____no_output_____"
],
[
"def running_mean(x, N):\n cumsum = np.cumsum(np.insert(x, 0, 0)) \n return (cumsum[N:] - cumsum[:-N]) / float(N)\n\ndef Catalan(k):\n return binom(2*k,k)/(k+1)",
"_____no_output_____"
],
[
"import torch\nuse_gpu = torch.cuda.is_available()\ndef gpu(tensor, gpu=use_gpu):\n if gpu:\n return tensor.cuda()\n else:\n return tensor",
"_____no_output_____"
]
],
[
[
"# Generation datasets",
"_____no_output_____"
]
],
[
[
"seq_max_len = 20\nseq_min_len = 4",
"_____no_output_____"
]
],
[
[
"## generating positive examples",
"_____no_output_____"
]
],
[
[
"# convention: +1 opening parenthesis and -1 closing parenthesis\n\ndef all_parent(n, a, k=-1):\n global res\n if k==n-1 and sum(a) == 0:\n res.append(a.copy())\n elif k==n-1:\n pass\n else:\n k += 1\n if sum(a) > 0:\n a[k] = 1\n all_parent(n,a,k)\n \n a[k] = -1\n all_parent(n,a,k)\n a[k] = 0\n else:\n a[k] = 1\n all_parent(n,a,k)\n a[k] = 0",
"_____no_output_____"
]
],
[
[
"## generating negative examples",
"_____no_output_____"
]
],
[
[
"def all_parent_mistake(n, a, k=-1):\n global res\n if k==n-1 and sum(a) >= -1 and sum(a) <= 1 and min(np.cumsum(a))<0:\n res.append(a.copy())\n elif sum(a) > n-k:\n pass\n elif k==n-1:\n pass\n else:\n k += 1\n if sum(a) >= -1 and k != 0:\n a[k] = 1\n all_parent_mistake(n,a,k)\n \n a[k] = -1\n all_parent_mistake(n,a,k)\n a[k] = 0\n else:\n a[k] = 1\n all_parent_mistake(n,a,k)\n a[k] = 0",
"_____no_output_____"
],
[
"# numbering the parentheses\n# example: seq of len 6\n# ( ( ( ) ) ) \n# 0 1 2 6 5 4\n# we always have ( + ) = seq_len\n# 'wrong' parentheses are always closing and numbered as:\n# ) )\n# 7 8\n\ndef reading_par(l, n):\n res = [0]*len(l)\n s = []\n n_plus = -1\n n_moins = n+1\n c = 0\n for i in l:\n if i == 1:\n n_plus += 1\n s.append(n_plus)\n res[c] = n_plus\n c += 1\n else:\n try:\n res[c] = n-s.pop()\n except:\n res[c] = n_moins\n n_moins += 1\n c += 1\n return res",
"_____no_output_____"
],
[
"all_par = OrderedDict()\nfor n in range(seq_min_len,seq_max_len+1,2):\n a = [0]*n\n res = []\n all_parent(n=n,a=a,k=-1)\n all_par[n] = [reading_par(k,n) for k in res]",
"_____no_output_____"
],
[
"all_par_mist = OrderedDict()\nfor n in range(seq_min_len,seq_max_len+1,2):\n a = [0]*n\n res = []\n all_parent_mistake(n=n,a=a,k=-1)\n all_par_mist[n] = [reading_par(k,n) for k in res]",
"_____no_output_____"
],
[
"all_par[6]",
"_____no_output_____"
],
[
"all_par_mist[6]",
"_____no_output_____"
]
],
[
[
"## number of negative examples by length",
"_____no_output_____"
]
],
[
[
"long_mist = {i:len(l) for (i,l) in zip(all_par_mist.keys(),all_par_mist.values())}",
"_____no_output_____"
],
[
"long_mist",
"_____no_output_____"
]
],
[
[
"## number of positive examples by length",
"_____no_output_____"
]
],
[
[
"Catalan_num = {i:len(l) for (i,l) in zip(all_par.keys(),all_par.values())}",
"_____no_output_____"
],
[
"Catalan_num",
"_____no_output_____"
]
],
[
[
"Sanity check, see [Catalan numbers](https://en.wikipedia.org/wiki/Catalan_number)",
"_____no_output_____"
]
],
[
[
"[(2*i,Catalan(i)) for i in range(2,int(seq_max_len/2)+1)]",
"_____no_output_____"
],
[
"# nombre de suites correctes de longueur entre 4 et 10, alphabet de taille nb_symbol.\nnb_symbol = 10\nnp.sum([Catalan(i)*int(nb_symbol/2)**i for i in range(2,int(seq_max_len/2)+1)])",
"_____no_output_____"
],
[
"import random\nimport torch\n\nclass SequenceGenerator():\n def __init__(self, nb_symbol = 10, seq_min_len = 4, seq_max_len = 10):\n self.nb_symbol = nb_symbol\n self.seq_min_len = seq_min_len\n self.seq_max_len = seq_max_len\n self.population = [i for i in range(int(nb_symbol/2))]\n \n def generate_pattern(self):\n len_r = random.randint(self.seq_min_len/2,self.seq_max_len/2)\n pattern = random.choices(self.population,k=len_r)\n return pattern + pattern[::-1]\n \n def generate_pattern_parenthesis(self, len_r = None):\n if len_r == None:\n len_r = int(2*random.randint(self.seq_min_len/2,self.seq_max_len/2))\n pattern = np.random.choice(self.population,size=int(len_r/2),replace=True)\n ind_r = random.randint(0,Catalan_num[len_r]-1)\n res = [pattern[i] if i <= len_r/2 else self.nb_symbol-1-pattern[len_r-i] for i in all_par[len_r][ind_r]]\n return res\n \n def generate_parenthesis_false(self):\n len_r = int(2*random.randint(self.seq_min_len/2,self.seq_max_len/2))\n pattern = np.random.choice(self.population,size=int(len_r/2),replace=True)\n ind_r = random.randint(0,long_mist[len_r]-1)\n res = [pattern[i] if i <= len_r/2 \n else self.nb_symbol-1-pattern[len_r-i] if i<= len_r \n else self.nb_symbol-1-pattern[i-len_r] for i in all_par_mist[len_r][ind_r]]\n return res\n \n def generate_hard_parenthesis(self, len_r = None):\n if len_r == None:\n len_r = int(2*random.randint(self.seq_min_len/2,self.seq_max_len/2))\n pattern = np.random.choice(self.population,size=int(len_r/2),replace=True)\n ind_r = random.randint(0,Catalan_num[len_r]-1)\n res = [pattern[i] if i <= len_r/2 else self.nb_symbol-1-pattern[len_r-i] for i in all_par[len_r][ind_r]]\n \n if len_r == None:\n len_r = int(2*random.randint(self.seq_min_len/2,self.seq_max_len/2))\n pattern = np.random.choice(self.population,size=int(len_r/2),replace=True)\n ind_r = random.randint(0,Catalan_num[len_r]-1)\n res2 = [pattern[i] if i <= len_r/2 else self.nb_symbol-1-pattern[len_r-i] for i in all_par[len_r][ind_r]]\n return res + res2\n \n def generate_hard_nonparenthesis(self, len_r = None):\n if len_r == None:\n len_r = int(2*random.randint(self.seq_min_len/2,self.seq_max_len/2))\n pattern = np.random.choice(self.population,size=int(len_r/2),replace=True)\n ind_r = random.randint(0,long_mist[len_r]-1)\n res = [pattern[i] if i <= len_r/2 \n else self.nb_symbol-1-pattern[len_r-i] if i<= len_r \n else self.nb_symbol-1-pattern[i-len_r] for i in all_par_mist[len_r][ind_r]]\n \n if len_r == None:\n len_r = int(2*random.randint(self.seq_min_len/2,self.seq_max_len/2))\n pattern = np.random.choice(self.population,size=int(len_r/2),replace=True)\n ind_r = random.randint(0,Catalan_num[len_r]-1)\n res2 = [pattern[i] if i <= len_r/2 else self.nb_symbol-1-pattern[len_r-i] for i in all_par[len_r][ind_r]]\n return res +[self.nb_symbol-1-pattern[0]]+ res2\n \n def generate_false(self):\n popu = [i for i in range(nb_symbol)]\n len = random.randint(self.seq_min_len/2,self.seq_max_len/2)\n return random.choices(popu,k=len) + random.choices(popu,k=len)\n \n def generate_label(self, x):\n l = int(len(x)/2)\n return 1 if x[:l] == x[:l-1:-1] else 0\n \n def generate_label_parenthesis(self, x):\n s = []\n label = 1\n lenx = len(x)\n for i in x:\n if s == [] and i < self.nb_symbol/2:\n s.append(i)\n elif s == [] and i >= self.nb_symbol/2:\n label = 0\n break\n elif i == self.nb_symbol-1-s[-1]:\n s.pop()\n else:\n s.append(i)\n if s != []:\n label = 0\n return label\n \n def one_hot(self,seq):\n one_hot_seq = []\n for s in seq:\n one_hot = [0 for _ in range(self.nb_symbol)]\n one_hot[s] = 1\n one_hot_seq.append(one_hot)\n return one_hot_seq\n \n def generate_input(self, len_r = None, true_parent = False, hard_false = True):\n if true_parent:\n seq = self.generate_pattern_parenthesis(len_r)\n elif bool(random.getrandbits(1)):\n seq = self.generate_pattern_parenthesis(len_r)\n else:\n if hard_false:\n seq = self.generate_parenthesis_false()\n else:\n seq = self.generate_false()\n return gpu(torch.from_numpy(np.array(self.one_hot(seq))).type(torch.FloatTensor)), gpu(torch.from_numpy(np.array([self.generate_label_parenthesis(seq)])))\n\n def generate_input_hard(self,true_parent = False):\n if true_parent:\n seq = self.generate_hard_parenthesis(self.seq_max_len)\n elif bool(random.getrandbits(1)):\n seq = self.generate_hard_parenthesis(self.seq_max_len)\n else:\n seq = self.generate_hard_nonparenthesis(self.seq_max_len)\n \n return gpu(torch.from_numpy(np.array(self.one_hot(seq))).type(torch.FloatTensor)), gpu(torch.from_numpy(np.array([self.generate_label_parenthesis(seq)])))",
"_____no_output_____"
],
[
"nb_symbol = 10\ngenerator = SequenceGenerator(nb_symbol = nb_symbol, seq_min_len = seq_min_len, seq_max_len = seq_max_len)",
"_____no_output_____"
],
[
"generator.generate_pattern_parenthesis()",
"_____no_output_____"
],
[
"x = generator.generate_parenthesis_false()",
"_____no_output_____"
],
[
"generator.generate_label_parenthesis(x)",
"_____no_output_____"
],
[
"generator.generate_input()",
"_____no_output_____"
]
],
[
[
"# First RNN",
"_____no_output_____"
]
],
[
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass RecNet(nn.Module):\n def __init__(self, dim_input=10, dim_recurrent=50, dim_output=2):\n super(RecNet, self).__init__()\n self.fc_x2h = nn.Linear(dim_input, dim_recurrent)\n self.fc_h2h = nn.Linear(dim_recurrent, dim_recurrent, bias = False)\n self.fc_h2y = nn.Linear(dim_recurrent, dim_output)\n \n def forward(self, x):\n h = x.new_zeros(1, self.fc_h2y.weight.size(1))\n for t in range(x.size(0)):\n h = torch.relu(self.fc_x2h(x[t,:]) + self.fc_h2h(h)) \n return self.fc_h2y(h)\n \nRNN = gpu(RecNet(dim_input = nb_symbol))",
"_____no_output_____"
],
[
"cross_entropy = nn.CrossEntropyLoss()\nlearning_rate = 1e-3\noptimizer = torch.optim.Adam(RNN.parameters(),lr=learning_rate)\nnb_train = 40000\nloss_t = []\ncorrects =[]\nlabels = []\nstart = time.time()\nfor k in range(nb_train):\n x,l = generator.generate_input(hard_false = False)\n y = RNN(x)\n loss = cross_entropy(y,l)\n _,preds = torch.max(y.data,1)\n corrects.append(preds.item() == l.data.item())\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n loss_t.append(loss)\n labels.append(l.data)\nprint(time.time() - start) # Time in minutes",
"_____no_output_____"
],
[
"plt.plot(running_mean(loss_t,int(nb_train/100)))",
"_____no_output_____"
],
[
"plt.plot(running_mean(corrects,int(nb_train/100)))",
"_____no_output_____"
],
[
"plt.plot(np.cumsum(labels))",
"_____no_output_____"
],
[
"nb_test = 1000\ncorrects_test =[]\nlabels_test = []\nfor k in range(nb_test):\n x,l = generator.generate_input(len_r=seq_max_len,true_parent=True)\n y = RNN(x)\n _,preds = torch.max(y.data,1)\n corrects_test.append(preds.item() == l.data.item())\n labels_test.append(l.data)",
"_____no_output_____"
],
[
"np.sum(corrects_test)/nb_test",
"_____no_output_____"
],
[
"nb_test = 1000\ncorrects_test =[]\nlabels_test = []\nfor k in range(nb_test):\n x,l = generator.generate_input(len_r=seq_max_len, hard_false = True)\n y = RNN(x)\n _,preds = torch.max(y.data,1)\n corrects_test.append(preds.item() == l.data.item())\n labels_test.append(l.data)",
"_____no_output_____"
],
[
"np.sum(corrects_test)/nb_test",
"_____no_output_____"
],
[
"nb_test = 1000\ncorrectsh_test =[]\nlabelsh_test = []\nfor k in range(nb_test):\n x,l = generator.generate_input_hard()\n y = RNN(x)\n _,preds = torch.max(y.data,1)\n correctsh_test.append(preds.item() == l.data.item())\n labelsh_test.append(l.data)",
"_____no_output_____"
],
[
"np.sum(correctsh_test)/nb_test",
"_____no_output_____"
],
[
"nb_test = 1000\ncorrectsh_test =[]\nlabelsh_test = []\nfor k in range(nb_test):\n x,l = generator.generate_input_hard(true_parent=True)\n y = RNN(x)\n _,preds = torch.max(y.data,1)\n correctsh_test.append(preds.item() == l.data.item())\n labelsh_test.append(l.data)",
"_____no_output_____"
],
[
"np.sum(correctsh_test)/nb_test",
"_____no_output_____"
]
],
[
[
"# RNN with Gating ",
"_____no_output_____"
]
],
[
[
"class RecNetGating(nn.Module):\n def __init__(self, dim_input=10, dim_recurrent=50, dim_output=2):\n super(RecNetGating, self).__init__()\n self.fc_x2h = nn.Linear(dim_input, dim_recurrent)\n self.fc_h2h = nn.Linear(dim_recurrent, dim_recurrent, bias = False)\n self.fc_x2z = nn.Linear(dim_input, dim_recurrent)\n self.fc_h2z = nn.Linear(dim_recurrent,dim_recurrent, bias = False)\n self.fc_h2y = nn.Linear(dim_recurrent, dim_output)\n \n def forward(self, x):\n h = x.new_zeros(1, self.fc_h2y.weight.size(1))\n for t in range(x.size(0)):\n z = torch.sigmoid(self.fc_x2z(x[t,:])+self.fc_h2z(h))\n hb = torch.relu(self.fc_x2h(x[t,:]) + self.fc_h2h(h))\n h = z * h + (1-z) * hb \n return self.fc_h2y(h) \n \nRNNG = gpu(RecNetGating(dim_input = nb_symbol))",
"_____no_output_____"
],
[
"optimizerG = torch.optim.Adam(RNNG.parameters(),lr=1e-3)\nloss_tG = []\ncorrectsG =[]\nlabelsG = []\nstart = time.time()\nfor k in range(nb_train):\n x,l = generator.generate_input(hard_false = False)\n y = RNNG(x)\n loss = cross_entropy(y,l)\n _,preds = torch.max(y.data,1)\n correctsG.append(preds.item() == l.data.item())\n optimizerG.zero_grad()\n loss.backward()\n optimizerG.step()\n loss_tG.append(loss)\n labelsG.append(l.item())\nprint(time.time() - start)",
"_____no_output_____"
],
[
"plt.plot(running_mean(loss_tG,int(nb_train/50)))\nplt.plot(running_mean(loss_t,int(nb_train/50)))",
"_____no_output_____"
],
[
"plt.plot(running_mean(correctsG,int(nb_train/50)))\nplt.plot(running_mean(corrects,int(nb_train/50)))",
"_____no_output_____"
],
[
"nb_test = 1000\ncorrectsG_test =[]\nlabelsG_test = []\nfor k in range(nb_test):\n x,l = generator.generate_input(len_r=seq_max_len,true_parent=True)\n y = RNNG(x)\n _,preds = torch.max(y.data,1)\n correctsG_test.append(preds.item() == l.data.item())\n labelsG_test.append(l.data)",
"_____no_output_____"
],
[
"np.sum(correctsG_test)/nb_test",
"_____no_output_____"
],
[
"nb_test = 1000\ncorrectsG_test =[]\nlabelsG_test = []\nfor k in range(nb_test):\n x,l = generator.generate_input(len_r=seq_max_len, hard_false = True)\n y = RNNG(x)\n _,preds = torch.max(y.data,1)\n correctsG_test.append(preds.item() == l.data.item())\n labelsG_test.append(l.data)",
"_____no_output_____"
],
[
"np.sum(correctsG_test)/nb_test",
"_____no_output_____"
],
[
"nb_test = 1000\ncorrectshG_test =[]\nlabelshG_test = []\nfor k in range(nb_test):\n x,l = generator.generate_input_hard()\n y = RNNG(x)\n _,preds = torch.max(y.data,1)\n correctshG_test.append(preds.item() == l.data.item())\n labelshG_test.append(l.data)",
"_____no_output_____"
],
[
"np.sum(correctshG_test)/nb_test",
"_____no_output_____"
]
],
[
[
"# LSTM",
"_____no_output_____"
]
],
[
[
"class LSTMNet(nn.Module):\n def __init__(self, dim_input=10, dim_recurrent=50, num_layers=4, dim_output=2):\n super(LSTMNet, self).__init__()\n self.lstm = nn.LSTM(input_size = dim_input, \n hidden_size = dim_recurrent,\n num_layers = num_layers)\n self.fc_o2y = nn.Linear(dim_recurrent,dim_output)\n \n def forward(self, x):\n x = x.unsqueeze(1)\n output, _ = self.lstm(x)\n output = output.squeeze(1)\n output = output.narrow(0, output.size(0)-1,1)\n return self.fc_o2y(F.relu(output))\n \nlstm = gpu(LSTMNet(dim_input = nb_symbol))",
"_____no_output_____"
],
[
"x, l = generator.generate_input()",
"_____no_output_____"
],
[
"lstm(x)",
"_____no_output_____"
],
[
"optimizerL = torch.optim.Adam(lstm.parameters(),lr=1e-3)\nloss_tL = []\ncorrectsL =[]\nlabelsL = []\nstart = time.time()\nfor k in range(nb_train):\n x,l = generator.generate_input(hard_false = False)\n y = lstm(x)\n loss = cross_entropy(y,l)\n _,preds = torch.max(y.data,1)\n correctsL.append(preds.item() == l.data.item())\n optimizerL.zero_grad()\n loss.backward()\n optimizerL.step()\n loss_tL.append(loss)\n labelsL.append(l.item())\nprint(time.time() - start)",
"_____no_output_____"
],
[
"plt.plot(running_mean(loss_tL,int(nb_train/50)))\nplt.plot(running_mean(loss_tG,int(nb_train/50)))\nplt.plot(running_mean(loss_t,int(nb_train/50)))",
"_____no_output_____"
],
[
"plt.plot(running_mean(correctsL,int(nb_train/50)))\nplt.plot(running_mean(correctsG,int(nb_train/50)))\nplt.plot(running_mean(corrects,int(nb_train/50)))",
"_____no_output_____"
],
[
"nb_test = 1000\ncorrectsL_test =[]\nlabelsL_test = []\nfor k in range(nb_test):\n x,l = generator.generate_input(len_r=seq_max_len,true_parent=True)\n y = lstm(x)\n _,preds = torch.max(y.data,1)\n correctsL_test.append(preds.item() == l.data.item())\n labelsL_test.append(l.data)",
"_____no_output_____"
],
[
"np.sum(correctsL_test)/nb_test",
"_____no_output_____"
],
[
"nb_test = 1000\ncorrectsL_test =[]\nlabelsL_test = []\nfor k in range(nb_test):\n x,l = generator.generate_input(len_r=seq_max_len,true_parent=False,hard_false = True)\n y = lstm(x)\n _,preds = torch.max(y.data,1)\n correctsL_test.append(preds.item() == l.data.item())\n labelsL_test.append(l.data)",
"_____no_output_____"
],
[
"np.sum(correctsL_test)/nb_test",
"_____no_output_____"
],
[
"nb_test = 1000\ncorrectshL_test =[]\nlabelshL_test = []\nfor k in range(nb_test):\n x,l = generator.generate_input_hard()\n y = lstm(x)\n _,preds = torch.max(y.data,1)\n correctshL_test.append(preds.item() == l.data.item())\n labelshL_test.append(l.data)",
"_____no_output_____"
],
[
"np.sum(correctshL_test)/nb_test",
"_____no_output_____"
]
],
[
[
"# GRU\n\nImplement your RNN with a [GRU](https://pytorch.org/docs/stable/nn.html#gru)",
"_____no_output_____"
],
[
"# Explore!\n\nWhat are good negative examples?\n\nHow to be sure that your network 'generalizes'?",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
e72147bf69c0dc32e5cd5b58bb4816229a07f85d | 19,883 | ipynb | Jupyter Notebook | ddsp/colab/demos/timbre_transfer.ipynb | andreykramer/ddsp | 519bdd8619f0bb77910fce9e9078646bc4655d16 | [
"Apache-2.0"
] | 1 | 2020-02-24T11:46:31.000Z | 2020-02-24T11:46:31.000Z | ddsp/colab/demos/timbre_transfer.ipynb | Neural-Finance/ddsp | d2421f724d115c5c265a3f9e362ae9ee5287339f | [
"Apache-2.0"
] | null | null | null | ddsp/colab/demos/timbre_transfer.ipynb | Neural-Finance/ddsp | d2421f724d115c5c265a3f9e362ae9ee5287339f | [
"Apache-2.0"
] | null | null | null | 41.165631 | 276 | 0.524368 | [
[
[
"<a href=\"https://colab.research.google.com/github/magenta/ddsp/blob/master/ddsp/colab/demos/timbre_transfer.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n\n##### Copyright 2020 Google LLC.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\n\n\n\n",
"_____no_output_____"
]
],
[
[
"# Copyright 2020 Google LLC. 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_____"
]
],
[
[
"# DDSP Timbre Transfer Demo\n\nThis notebook is a demo of timbre transfer using DDSP (Differentiable Digital Signal Processing). \nThe model here is trained to generate audio conditioned on a time series of fundamental frequency and loudness. \n\n* [DDSP ICLR paper](https://openreview.net/forum?id=B1x1ma4tDr)\n* [Audio Examples](http://goo.gl/magenta/ddsp-examples) \n\nBy default, the notebook will download pre-trained models for Violin and Flute. You can train a model on your own sounds by using the [Train Autoencoder Colab](https://github.com/magenta/ddsp/blob/master/ddsp/colab/demos/train_autoencoder.ipynb).\n\n<img src=\"https://storage.googleapis.com/ddsp/additive_diagram/ddsp_autoencoder.png\" alt=\"DDSP Autoencoder figure\" width=\"700\">\n\n\n# Environment Setup\n\n\nThis notebook extracts these features from input audio (either uploaded files, or recorded from the microphone) and resynthesizes with the model.\n\nHave fun! And please feel free to hack this notebook to make your own creative interactions.\n\n### Instructions for running:\n\n* Make sure to use a GPU runtime, click: __Runtime >> Change Runtime Type >> GPU__\n* Press the ▶️button on the left of each of the cells\n* View the code: Double-click any of the cells\n* Hide the code: Double click the right side of the cell\n",
"_____no_output_____"
]
],
[
[
"#@title #Install and Import\n\n#@markdown Install ddsp, define some helper functions, and download the model. This transfers a lot of data and _should take a minute or two_.\n%tensorflow_version 2.x\n\nprint('Installing from pip package...')\n!pip install -qU ddsp\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Ignore a bunch of deprecation warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport copy\nimport os\nimport time\n\nimport crepe\nimport ddsp\nimport ddsp.training\nfrom ddsp.colab.colab_utils import (download, play, record, specplot, upload,\n DEFAULT_SAMPLE_RATE)\nimport gin\nfrom google.colab import files\nimport librosa\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow.compat.v2 as tf\nimport tensorflow_datasets as tfds\n\n# Helper Functions\nsample_rate = DEFAULT_SAMPLE_RATE # 16000\n\n\nprint('Done!')",
"_____no_output_____"
],
[
"#@title Record or Upload Audio\n#@markdown * Either record audio from microphone or upload audio from file (.mp3 or .wav) \n#@markdown * Audio should be monophonic (single instrument / voice)\n#@markdown * Extracts fundmanetal frequency (f0) and loudness features. \n\nrecord_or_upload = \"Record\" #@param [\"Record\", \"Upload (.mp3 or .wav)\"]\n\nrecord_seconds = 5 #@param {type:\"number\", min:1, max:10, step:1}\n\nif record_or_upload == \"Record\":\n audio = record(seconds=record_seconds)\nelse:\n # Load audio sample here (.mp3 or .wav3 file)\n # Just use the first file.\n filenames, audios = upload()\n audio = audios[0]\naudio = audio[np.newaxis, :]\nprint('\\nExtracting audio features...')\n\n# Plot.\nspecplot(audio)\nplay(audio)\n\n# Setup the session.\nddsp.spectral_ops.reset_crepe()\n\n# Compute features.\nstart_time = time.time()\naudio_features = ddsp.training.eval_util.compute_audio_features(audio)\naudio_features['loudness_db'] = audio_features['loudness_db'].astype(np.float32)\naudio_features_mod = None\nprint('Audio features took %.1f seconds' % (time.time() - start_time))\n\n\n# Plot Features.\nfig, ax = plt.subplots(nrows=3, \n ncols=1, \n sharex=True,\n figsize=(6, 8))\nax[0].plot(audio_features['loudness_db'])\nax[0].set_ylabel('loudness_db')\n\nax[1].plot(librosa.hz_to_midi(audio_features['f0_hz']))\nax[1].set_ylabel('f0 [midi]')\n\nax[2].plot(audio_features['f0_confidence'])\nax[2].set_ylabel('f0 confidence')\n_ = ax[2].set_xlabel('Time step [frame]')",
"_____no_output_____"
],
[
"#@title Choose a model\n\nmodel = 'Violin' #@param ['Violin', 'Flute', 'Flute2', 'Upload your own (checkpoint folder as .zip)']\nMODEL = model\n\nGCS_CKPT_DIR = 'gs://ddsp/models/tf2'\n\ndef find_model_dir(dir_name):\n # Iterate through directories until model directory is found\n for root, dirs, filenames in os.walk(dir_name):\n for filename in filenames:\n if filename.endswith(\".gin\") and not filename.startswith(\".\"):\n model_dir = root\n break\n return model_dir \n\n\nif model in ('Violin', 'Flute', 'Flute2'):\n # Pretrained models.\n PRETRAINED_DIR = '/content/pretrained'\n # Copy over from gs:// for faster loading.\n !rm -r $PRETRAINED_DIR &> /dev/null\n !mkdir $PRETRAINED_DIR &> /dev/null\n model_dir = os.path.join(GCS_CKPT_DIR, 'solo_%s_ckpt' % model.lower())\n !gsutil cp $model_dir/* $PRETRAINED_DIR &> /dev/null\n model_dir = PRETRAINED_DIR\n gin_file = os.path.join(model_dir, 'operative_config-0.gin')\n\nelse:\n # User models.\n UPLOAD_DIR = '/content/uploaded'\n !mkdir $UPLOAD_DIR\n uploaded_files = files.upload()\n\n for fnames in uploaded_files.keys():\n print(\"Unzipping... {}\".format(fnames))\n !unzip -o \"/content/$fnames\" -d $UPLOAD_DIR &> /dev/null\n model_dir = find_model_dir(UPLOAD_DIR)\n gin_file = os.path.join(model_dir, 'operative_config-0.gin')\n\n# Parse gin config,\nwith gin.unlock_config():\n gin.parse_config_file(gin_file, skip_unknown=True)\n\n# Assumes only one checkpoint in the folder, 'ckpt-[iter]`.\nckpt_files = [f for f in tf.io.gfile.listdir(model_dir) if 'ckpt' in f]\nckpt_name = ckpt_files[0].split('.')[0]\nckpt = os.path.join(model_dir, ckpt_name)\n\n# Ensure dimensions and sampling rates are equal\ntime_steps_train = gin.query_parameter('DefaultPreprocessor.time_steps')\nn_samples_train = gin.query_parameter('Additive.n_samples')\nhop_size = int(n_samples_train / time_steps_train)\n\ntime_steps = int(audio.shape[1] / hop_size)\nn_samples = time_steps * hop_size\n\n# print(\"===Trained model===\")\n# print(\"Time Steps\", time_steps_train)\n# print(\"Samples\", n_samples_train)\n# print(\"Hop Size\", hop_size)\n# print(\"\\n===Resynthesis===\")\n# print(\"Time Steps\", time_steps)\n# print(\"Samples\", n_samples)\n# print('')\n\ngin_params = [\n 'Additive.n_samples = {}'.format(n_samples),\n 'FilteredNoise.n_samples = {}'.format(n_samples),\n 'DefaultPreprocessor.time_steps = {}'.format(time_steps),\n]\n\nwith gin.unlock_config():\n gin.parse_config(gin_params)\n\n\n# Trim all input vectors to correct lengths \nfor key in ['f0_hz', 'f0_confidence', 'loudness_db']:\n audio_features[key] = audio_features[key][:time_steps]\naudio_features['audio'] = audio_features['audio'][:, :n_samples]\n\n\n# Set up the model just to predict audio given new conditioning\nmodel = ddsp.training.models.Autoencoder()\nmodel.restore(ckpt)\n\n# Build model by running a batch through it.\nstart_time = time.time()\n_ = model(audio_features, training=False)\nprint('Restoring model took %.1f seconds' % (time.time() - start_time))",
"_____no_output_____"
],
[
"#@title Modify conditioning\n\n#@markdown These models were not explicitly trained to perform timbre transfer, so they may sound unnatural if the incoming loudness and frequencies are very different then the training data (which will always be somewhat true). \n\n#@markdown This button will at least adjusts the average loudness and pitch to be similar to the training data (although not for user trained models).\n\nauto_adjust = True #@param{type:\"boolean\"}\n\n#@markdown You can also make additional manual adjustments:\n#@markdown * Shift the fundmental frequency to a more natural register.\n#@markdown * Silence audio below a threshold on f0_confidence.\n#@markdown * Adjsut the overall loudness level.\nf0_octave_shift = 0 #@param {type:\"slider\", min:-2, max:2, step:1}\nf0_confidence_threshold = 0 #@param {type:\"slider\", min:0.0, max:1.0, step:0.05}\nloudness_db_shift = 0 #@param {type:\"slider\", min:-20, max:20, step:1}\n\n#@markdown You might get more realistic sounds by shifting a few dB, or try going extreme and see what weird sounds you can make...\n\naudio_features_mod = {k: v.copy() for k, v in audio_features.items()}\n\n\n## Helper functions.\ndef shift_ld(audio_features, ld_shift=0.0):\n \"\"\"Shift loudness by a number of ocatves.\"\"\"\n audio_features['loudness_db'] += ld_shift\n return audio_features\n\n\ndef shift_f0(audio_features, f0_octave_shift=0.0):\n \"\"\"Shift f0 by a number of ocatves.\"\"\"\n audio_features['f0_hz'] *= 2.0 ** (f0_octave_shift)\n audio_features['f0_hz'] = np.clip(audio_features['f0_hz'], \n 0.0, \n librosa.midi_to_hz(110.0))\n return audio_features\n\n\ndef mask_by_confidence(audio_features, confidence_level=0.1):\n \"\"\"For the violin model, the masking causes fast dips in loudness. \n This quick transient is interpreted by the model as the \"plunk\" sound.\n \"\"\"\n mask_idx = audio_features['f0_confidence'] < confidence_level\n audio_features['f0_hz'][mask_idx] = 0.0\n # audio_features['loudness_db'][mask_idx] = -ddsp.spectral_ops.LD_RANGE\n return audio_features\n\n\ndef smooth_loudness(audio_features, filter_size=3):\n \"\"\"Smooth loudness with a box filter.\"\"\"\n smoothing_filter = np.ones([filter_size]) / float(filter_size)\n audio_features['loudness_db'] = np.convolve(audio_features['loudness_db'], \n smoothing_filter, \n mode='same')\n return audio_features\n\nif auto_adjust:\n if MODEL in ['Violin', 'Flute', 'Flute2']:\n # Adjust the peak loudness.\n l = audio_features['loudness_db']\n model_ld_avg_max = {\n 'Violin': -34.0,\n 'Flute': -45.0,\n 'Flute2': -44.0,\n }[MODEL]\n ld_max = np.max(audio_features['loudness_db'])\n ld_diff_max = model_ld_avg_max - ld_max\n audio_features_mod = shift_ld(audio_features_mod, ld_diff_max)\n\n # Further adjust the average loudness above a threshold.\n l = audio_features_mod['loudness_db']\n model_ld_mean = {\n 'Violin': -44.0,\n 'Flute': -51.0,\n 'Flute2': -53.0,\n }[MODEL]\n ld_thresh = -50.0\n ld_mean = np.mean(l[l > ld_thresh])\n ld_diff_mean = model_ld_mean - ld_mean\n audio_features_mod = shift_ld(audio_features_mod, ld_diff_mean)\n\n # Shift the pitch register.\n model_p_mean = {\n 'Violin': 73.0,\n 'Flute': 81.0,\n 'Flute2': 74.0,\n }[MODEL]\n p = librosa.hz_to_midi(audio_features['f0_hz'])\n p[p == -np.inf] = 0.0\n p_mean = p[l > ld_thresh].mean()\n p_diff = model_p_mean - p_mean\n p_diff_octave = p_diff / 12.0\n round_fn = np.floor if p_diff_octave > 1.5 else np.ceil\n p_diff_octave = round_fn(p_diff_octave)\n audio_features_mod = shift_f0(audio_features_mod, p_diff_octave)\n\n else:\n print('\\nUser uploaded model: disabling auto-adjust.')\n\n \naudio_features_mod = shift_ld(audio_features_mod, loudness_db_shift)\naudio_features_mod = shift_f0(audio_features_mod, f0_octave_shift)\naudio_features_mod = mask_by_confidence(audio_features_mod, f0_confidence_threshold)\n\n\n# Plot Features.\nfig, ax = plt.subplots(nrows=3, \n ncols=1, \n sharex=True,\n figsize=(6, 8))\nax[0].plot(audio_features['loudness_db'])\nax[0].plot(audio_features_mod['loudness_db'])\nax[0].set_ylabel('loudness_db')\n\nax[1].plot(librosa.hz_to_midi(audio_features['f0_hz']))\nax[1].plot(librosa.hz_to_midi(audio_features_mod['f0_hz']))\nax[1].set_ylabel('f0 [midi]')\n\nax[2].plot(audio_features_mod['f0_confidence'])\nax[2].plot(np.ones_like(audio_features_mod['f0_confidence']) * f0_confidence_threshold)\nax[2].set_ylabel('f0 confidence')\n_ = ax[2].set_xlabel('Time step [frame]')",
"_____no_output_____"
],
[
"#@title #Resynthesize Audio\n\naf = audio_features if audio_features_mod is None else audio_features_mod\n\n# Run a batch of predictions.\nstart_time = time.time()\naudio_gen = model(af, training=False)\nprint('Prediction took %.1f seconds' % (time.time() - start_time))\n\n# Plot\nprint('Original')\nplay(audio)\n\nprint('Resynthesis')\nplay(audio_gen)\n\nspecplot(audio)\nplt.title(\"Original\")\n\nspecplot(audio_gen)\n_ = plt.title(\"Resynthesis\")",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
e72147edfadf365a0d727863eb1ebef8851e168e | 763,817 | ipynb | Jupyter Notebook | conditional/main_conditional_disentangle_cifar_bs8K_sratio_0_5_drop_0_5_rl_stdlearnscale_30_annealing_run3.ipynb | minhtannguyen/ffjord | f3418249eaa4647f4339aea8d814cf2ce33be141 | [
"MIT"
] | null | null | null | conditional/main_conditional_disentangle_cifar_bs8K_sratio_0_5_drop_0_5_rl_stdlearnscale_30_annealing_run3.ipynb | minhtannguyen/ffjord | f3418249eaa4647f4339aea8d814cf2ce33be141 | [
"MIT"
] | null | null | null | conditional/main_conditional_disentangle_cifar_bs8K_sratio_0_5_drop_0_5_rl_stdlearnscale_30_annealing_run3.ipynb | minhtannguyen/ffjord | f3418249eaa4647f4339aea8d814cf2ce33be141 | [
"MIT"
] | null | null | null | 59.357864 | 1,175 | 0.587858 | [
[
[
"%run -p ../train_cnf_disentangle_rl.py --data cifar10 --dims 64,64,64 --strides 1,1,1,1 --num_blocks 2 --layer_type concat --multiscale True --rademacher True --batch_size 8000 --test_batch_size 5000 --save ../experiments_published/cnf_conditional_disentangle_cifar10_bs8K_sratio_0_5_drop_0_5_rl_stdlearnscale_30_annealing_run3 --seed 3 --conditional True --controlled_tol True --train_mode semisup --lr 0.001 --warmup_iters 1000 --atol 1e-4 --rtol 1e-4 --weight_y 0.5 --condition_ratio 0.5 --dropout_rate 0.5 --scale_fac 1.0 --gate cnn2 --scale_std 30.0 --max_grad_norm 20.0 --annealing_std True\n#",
"/tancode/repos/tan-ffjord/train_cnf_disentangle_rl.py\nimport argparse\nimport os\nimport time\nimport numpy as np\n\nimport torch\nimport torch.optim as optim\nimport torchvision.datasets as dset\nimport torchvision.transforms as tforms\nfrom torchvision.utils import save_image\n\nimport lib.layers as layers\nimport lib.utils as utils\nimport lib.multiscale_parallel as multiscale_parallel\nimport lib.modules as modules\nimport lib.thops as thops\n\nfrom train_misc import standard_normal_logprob\nfrom train_misc import set_cnf_options, count_nfe, count_parameters, count_total_time, count_nfe_gate\nfrom train_misc import add_spectral_norm, spectral_norm_power_iteration\nfrom train_misc import create_regularization_fns, get_regularization, append_regularization_to_log\n\nfrom tensorboardX import SummaryWriter\n\n# go fast boi!!\ntorch.backends.cudnn.benchmark = True\nSOLVERS = [\"dopri5\", \"bdf\", \"rk4\", \"midpoint\", 'adams', 'explicit_adams']\nGATES = [\"cnn1\", \"cnn2\", \"rnn\"]\n\nparser = argparse.ArgumentParser(\"Continuous Normalizing Flow\")\nparser.add_argument(\"--data\", choices=[\"mnist\", \"svhn\", \"cifar10\", 'lsun_church'], type=str, default=\"mnist\")\nparser.add_argument(\"--dims\", type=str, default=\"8,32,32,8\")\nparser.add_argument(\"--strides\", type=str, default=\"2,2,1,-2,-2\")\nparser.add_argument(\"--num_blocks\", type=int, default=1, help='Number of stacked CNFs.')\n\nparser.add_argument(\"--conv\", type=eval, default=True, choices=[True, False])\nparser.add_argument(\n \"--layer_type\", type=str, default=\"ignore\",\n choices=[\"ignore\", \"concat\", \"concat_v2\", \"squash\", \"concatsquash\", \"concatcoord\", \"hyper\", \"blend\"]\n)\nparser.add_argument(\"--divergence_fn\", type=str, default=\"approximate\", choices=[\"brute_force\", \"approximate\"])\nparser.add_argument(\n \"--nonlinearity\", type=str, default=\"softplus\", choices=[\"tanh\", \"relu\", \"softplus\", \"elu\", \"swish\"]\n)\n\nparser.add_argument(\"--seed\", type=int, default=0)\n\nparser.add_argument('--solver', type=str, default='dopri5', choices=SOLVERS)\nparser.add_argument('--atol', type=float, default=1e-5)\nparser.add_argument('--rtol', type=float, default=1e-5)\nparser.add_argument(\"--step_size\", type=float, default=None, help=\"Optional fixed step size.\")\n\nparser.add_argument('--gate', type=str, default='cnn1', choices=GATES)\nparser.add_argument('--scale', type=float, default=1.0)\nparser.add_argument('--scale_fac', type=float, default=1.0)\nparser.add_argument('--scale_std', type=float, default=1.0)\nparser.add_argument('--eta', default=0.1, type=float,\n help='tuning parameter that allows us to trade-off the competing goals of' \n 'minimizing the prediction loss and maximizing the gate rewards ')\nparser.add_argument('--rl-weight', default=0.01, type=float,\n help='rl weight')\n\nparser.add_argument('--gamma', default=0.99, type=float,\n help='discount factor, default: (0.99)')\n\nparser.add_argument('--test_solver', type=str, default=None, choices=SOLVERS + [None])\nparser.add_argument('--test_atol', type=float, default=None)\nparser.add_argument('--test_rtol', type=float, default=None)\n\nparser.add_argument(\"--imagesize\", type=int, default=None)\nparser.add_argument(\"--alpha\", type=float, default=1e-6)\nparser.add_argument('--time_length', type=float, default=1.0)\nparser.add_argument('--train_T', type=eval, default=True)\n\nparser.add_argument(\"--num_epochs\", type=int, default=500)\nparser.add_argument(\"--batch_size\", type=int, default=200)\nparser.add_argument(\n \"--batch_size_schedule\", type=str, default=\"\", help=\"Increases the batchsize at every given epoch, dash separated.\"\n)\nparser.add_argument(\"--test_batch_size\", type=int, default=200)\nparser.add_argument(\"--lr\", type=float, default=1e-3)\nparser.add_argument(\"--warmup_iters\", type=float, default=1000)\nparser.add_argument(\"--weight_decay\", type=float, default=0.0)\nparser.add_argument(\"--spectral_norm_niter\", type=int, default=10)\nparser.add_argument(\"--weight_y\", type=float, default=0.5)\nparser.add_argument(\"--annealing_std\", type=eval, default=False, choices=[True, False])\n\nparser.add_argument(\"--add_noise\", type=eval, default=True, choices=[True, False])\nparser.add_argument(\"--batch_norm\", type=eval, default=False, choices=[True, False])\nparser.add_argument('--residual', type=eval, default=False, choices=[True, False])\nparser.add_argument('--autoencode', type=eval, default=False, choices=[True, False])\nparser.add_argument('--rademacher', type=eval, default=True, choices=[True, False])\nparser.add_argument('--spectral_norm', type=eval, default=False, choices=[True, False])\nparser.add_argument('--multiscale', type=eval, default=False, choices=[True, False])\nparser.add_argument('--parallel', type=eval, default=False, choices=[True, False])\nparser.add_argument('--conditional', type=eval, default=False, choices=[True, False])\nparser.add_argument('--controlled_tol', type=eval, default=False, choices=[True, False])\nparser.add_argument(\"--train_mode\", choices=[\"semisup\", \"sup\", \"unsup\"], type=str, default=\"semisup\")\nparser.add_argument(\"--condition_ratio\", type=float, default=0.5)\nparser.add_argument(\"--dropout_rate\", type=float, default=0.0)\n\n\n# Regularizations\nparser.add_argument('--l1int', type=float, default=None, help=\"int_t ||f||_1\")\nparser.add_argument('--l2int', type=float, default=None, help=\"int_t ||f||_2\")\nparser.add_argument('--dl2int', type=float, default=None, help=\"int_t ||f^T df/dt||_2\")\nparser.add_argument('--JFrobint', type=float, default=None, help=\"int_t ||df/dx||_F\")\nparser.add_argument('--JdiagFrobint', type=float, default=None, help=\"int_t ||df_i/dx_i||_F\")\nparser.add_argument('--JoffdiagFrobint', type=float, default=None, help=\"int_t ||df/dx - df_i/dx_i||_F\")\n\nparser.add_argument(\"--time_penalty\", type=float, default=0, help=\"Regularization on the end_time.\")\nparser.add_argument(\n \"--max_grad_norm\", type=float, default=1e10,\n help=\"Max norm of graidents (default is just stupidly high to avoid any clipping)\"\n)\n\nparser.add_argument(\"--begin_epoch\", type=int, default=1)\nparser.add_argument(\"--resume\", type=str, default=None)\nparser.add_argument(\"--save\", type=str, default=\"experiments/cnf\")\nparser.add_argument(\"--val_freq\", type=int, default=1)\nparser.add_argument(\"--log_freq\", type=int, default=1)\n\nargs = parser.parse_args()\n\nimport lib.odenvp_conditional_rl as odenvp\n \n# set seed\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\n\n# logger\nutils.makedirs(args.save)\nlogger = utils.get_logger(logpath=os.path.join(args.save, 'logs'), filepath=os.path.abspath(__file__)) # write to log file\nwriter = SummaryWriter(os.path.join(args.save, 'tensorboard')) # write to tensorboard\n\nif args.layer_type == \"blend\":\n logger.info(\"!! Setting time_length from None to 1.0 due to use of Blend layers.\")\n args.time_length = 1.0\n\nlogger.info(args)\n\n\ndef add_noise(x):\n \"\"\"\n [0, 1] -> [0, 255] -> add noise -> [0, 1]\n \"\"\"\n if args.add_noise:\n noise = x.new().resize_as_(x).uniform_()\n x = x * 255 + noise\n x = x / 256\n return x\n\n\ndef update_lr(optimizer, itr):\n iter_frac = min(float(itr + 1) / max(args.warmup_iters, 1), 1.0)\n lr = args.lr * iter_frac\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = lr\n\n \ndef update_scale_std(model, epoch):\n epoch_frac = 1.0 - float(epoch - 1) / max(args.num_epochs + 1, 1)\n scale_std = args.scale_std * epoch_frac\n model.set_scale_std(scale_std)\n\n\ndef get_train_loader(train_set, epoch):\n if args.batch_size_schedule != \"\":\n epochs = [0] + list(map(int, args.batch_size_schedule.split(\"-\")))\n n_passed = sum(np.array(epochs) <= epoch)\n current_batch_size = int(args.batch_size * n_passed)\n else:\n current_batch_size = args.batch_size\n train_loader = torch.utils.data.DataLoader(\n dataset=train_set, batch_size=current_batch_size, shuffle=True, drop_last=True, pin_memory=True\n )\n logger.info(\"===> Using batch size {}. Total {} iterations/epoch.\".format(current_batch_size, len(train_loader)))\n return train_loader\n\n\ndef get_dataset(args):\n trans = lambda im_size: tforms.Compose([tforms.Resize(im_size), tforms.ToTensor(), add_noise])\n\n if args.data == \"mnist\":\n im_dim = 1\n im_size = 28 if args.imagesize is None else args.imagesize\n train_set = dset.MNIST(root=\"../data\", train=True, transform=trans(im_size), download=True)\n test_set = dset.MNIST(root=\"../data\", train=False, transform=trans(im_size), download=True)\n elif args.data == \"svhn\":\n im_dim = 3\n im_size = 32 if args.imagesize is None else args.imagesize\n train_set = dset.SVHN(root=\"../data\", split=\"train\", transform=trans(im_size), download=True)\n test_set = dset.SVHN(root=\"../data\", split=\"test\", transform=trans(im_size), download=True)\n elif args.data == \"cifar10\":\n im_dim = 3\n im_size = 32 if args.imagesize is None else args.imagesize\n train_set = dset.CIFAR10(\n root=\"../data\", train=True, transform=tforms.Compose([\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ]), download=True\n )\n test_set = dset.CIFAR10(root=\"../data\", train=False, transform=trans(im_size), download=True)\n elif args.data == 'celeba':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.CelebA(\n train=True, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.CelebA(\n train=False, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n elif args.data == 'lsun_church':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.LSUN(\n '../data', ['church_outdoor_train'], transform=tforms.Compose([\n tforms.Resize(96),\n tforms.RandomCrop(64),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.LSUN(\n '../data', ['church_outdoor_val'], transform=tforms.Compose([\n tforms.Resize(96),\n tforms.RandomCrop(64),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n ) \n elif args.data == 'imagenet_64':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.ImageFolder(\n train=True, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.ImageFolder(\n train=False, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n \n data_shape = (im_dim, im_size, im_size)\n if not args.conv:\n data_shape = (im_dim * im_size * im_size,)\n\n test_loader = torch.utils.data.DataLoader(\n dataset=test_set, batch_size=args.test_batch_size, shuffle=False, drop_last=True\n )\n return train_set, test_loader, data_shape\n\n\ndef compute_bits_per_dim(x, model):\n zero = torch.zeros(x.shape[0], 1).to(x)\n\n # Don't use data parallelize if batch size is small.\n # if x.shape[0] < 200:\n # model = model.module\n \n z, delta_logp, atol, rtol, logp_actions, nfe = model(x, zero) # run model forward\n\n logpz = standard_normal_logprob(z).view(z.shape[0], -1).sum(1, keepdim=True) # logp(z)\n logpx = logpz - delta_logp\n\n logpx_per_dim = torch.sum(logpx) / x.nelement() # averaged over batches\n bits_per_dim = -(logpx_per_dim - np.log(256)) / np.log(2)\n\n return bits_per_dim, atol, rtol, logp_actions, nfe\n\ndef compute_bits_per_dim_conditional(x, y, model):\n zero = torch.zeros(x.shape[0], 1).to(x)\n y_onehot = thops.onehot(y, num_classes=model.module.y_class).to(x)\n\n # Don't use data parallelize if batch size is small.\n # if x.shape[0] < 200:\n # model = model.module\n \n z, delta_logp, atol, rtol, logp_actions, nfe = model(x, zero) # run model forward\n \n dim_sup = int(args.condition_ratio * np.prod(z.size()[1:]))\n \n # prior\n mean, logs = model.module._prior(y_onehot)\n\n logpz_sup = modules.GaussianDiag.logp(mean, logs, z[:, 0:dim_sup]).view(-1,1) # logp(z)_sup\n logpz_unsup = standard_normal_logprob(z[:, dim_sup:]).view(z.shape[0], -1).sum(1, keepdim=True)\n logpz = logpz_sup + logpz_unsup\n logpx = logpz - delta_logp\n\n logpx_per_dim = torch.sum(logpx) / x.nelement() # averaged over batches\n bits_per_dim = -(logpx_per_dim - np.log(256)) / np.log(2)\n \n # dropout\n if args.dropout_rate > 0:\n zsup = model.module.dropout(z[:, 0:dim_sup])\n else:\n zsup = z[:, 0:dim_sup]\n \n # compute xentropy loss\n y_logits = model.module.project_class(zsup)\n loss_xent = model.module.loss_class(y_logits, y.to(x.get_device()))\n y_predicted = np.argmax(y_logits.cpu().detach().numpy(), axis=1)\n\n return bits_per_dim, loss_xent, y_predicted, atol, rtol, logp_actions, nfe\n\ndef create_model(args, data_shape, regularization_fns):\n hidden_dims = tuple(map(int, args.dims.split(\",\")))\n strides = tuple(map(int, args.strides.split(\",\")))\n\n if args.multiscale:\n model = odenvp.ODENVP(\n (args.batch_size, *data_shape),\n n_blocks=args.num_blocks,\n intermediate_dims=hidden_dims,\n nonlinearity=args.nonlinearity,\n alpha=args.alpha,\n cnf_kwargs={\"T\": args.time_length, \"train_T\": args.train_T, \"regularization_fns\": regularization_fns, \"solver\": args.solver, \"atol\": args.atol, \"rtol\": args.rtol, \"scale\": args.scale, \"scale_fac\": args.scale_fac, \"scale_std\": args.scale_std, \"gate\": args.gate},\n condition_ratio=args.condition_ratio,\n dropout_rate=args.dropout_rate,)\n elif args.parallel:\n model = multiscale_parallel.MultiscaleParallelCNF(\n (args.batch_size, *data_shape),\n n_blocks=args.num_blocks,\n intermediate_dims=hidden_dims,\n alpha=args.alpha,\n time_length=args.time_length,\n )\n else:\n if args.autoencode:\n\n def build_cnf():\n autoencoder_diffeq = layers.AutoencoderDiffEqNet(\n hidden_dims=hidden_dims,\n input_shape=data_shape,\n strides=strides,\n conv=args.conv,\n layer_type=args.layer_type,\n nonlinearity=args.nonlinearity,\n )\n odefunc = layers.AutoencoderODEfunc(\n autoencoder_diffeq=autoencoder_diffeq,\n divergence_fn=args.divergence_fn,\n residual=args.residual,\n rademacher=args.rademacher,\n )\n cnf = layers.CNF(\n odefunc=odefunc,\n T=args.time_length,\n regularization_fns=regularization_fns,\n solver=args.solver,\n )\n return cnf\n else:\n\n def build_cnf():\n diffeq = layers.ODEnet(\n hidden_dims=hidden_dims,\n input_shape=data_shape,\n strides=strides,\n conv=args.conv,\n layer_type=args.layer_type,\n nonlinearity=args.nonlinearity,\n )\n odefunc = layers.ODEfunc(\n diffeq=diffeq,\n divergence_fn=args.divergence_fn,\n residual=args.residual,\n rademacher=args.rademacher,\n )\n cnf = layers.CNF(\n odefunc=odefunc,\n T=args.time_length,\n train_T=args.train_T,\n regularization_fns=regularization_fns,\n solver=args.solver,\n )\n return cnf\n\n chain = [layers.LogitTransform(alpha=args.alpha)] if args.alpha > 0 else [layers.ZeroMeanTransform()]\n chain = chain + [build_cnf() for _ in range(args.num_blocks)]\n if args.batch_norm:\n chain.append(layers.MovingBatchNorm2d(data_shape[0]))\n model = layers.SequentialFlow(chain)\n return model\n\n\nif __name__ == \"__main__\":\n\n # get deivce\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n cvt = lambda x: x.type(torch.float32).to(device, non_blocking=True)\n\n # load dataset\n train_set, test_loader, data_shape = get_dataset(args)\n\n # build model\n regularization_fns, regularization_coeffs = create_regularization_fns(args)\n model = create_model(args, data_shape, regularization_fns)\n\n if args.spectral_norm: add_spectral_norm(model, logger)\n set_cnf_options(args, model)\n\n logger.info(model)\n logger.info(\"Number of trainable parameters: {}\".format(count_parameters(model)))\n \n writer.add_text('info', \"Number of trainable parameters: {}\".format(count_parameters(model)))\n\n # optimizer\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n \n # set initial iter\n itr = 1\n \n # set the meters\n time_epoch_meter = utils.RunningAverageMeter(0.97)\n time_meter = utils.RunningAverageMeter(0.97)\n loss_meter = utils.RunningAverageMeter(0.97) # track total loss\n nll_meter = utils.RunningAverageMeter(0.97) # track negative log-likelihood\n xent_meter = utils.RunningAverageMeter(0.97) # track xentropy score\n error_meter = utils.RunningAverageMeter(0.97) # track error score\n steps_meter = utils.RunningAverageMeter(0.97)\n grad_meter = utils.RunningAverageMeter(0.97)\n tt_meter = utils.RunningAverageMeter(0.97)\n\n # restore parameters\n if args.resume is not None:\n checkpt = torch.load(args.resume, map_location=lambda storage, loc: storage)\n model.load_state_dict(checkpt[\"state_dict\"])\n if \"optim_state_dict\" in checkpt.keys():\n optimizer.load_state_dict(checkpt[\"optim_state_dict\"])\n # Manually move optimizer state to device.\n for state in optimizer.state.values():\n for k, v in state.items():\n if torch.is_tensor(v):\n state[k] = cvt(v)\n args.begin_epoch = checkpt['epoch'] + 1\n itr = checkpt['iter'] + 1\n time_epoch_meter.set(checkpt['epoch_time_avg'])\n time_meter.set(checkpt['time_train'])\n loss_meter.set(checkpt['loss_train'])\n nll_meter.set(checkpt['bits_per_dim_train'])\n xent_meter.set(checkpt['xent_train'])\n error_meter.set(checkpt['error_train'])\n steps_meter.set(checkpt['nfe_train'])\n grad_meter.set(checkpt['grad_train'])\n tt_meter.set(checkpt['total_time_train'])\n\n if torch.cuda.is_available():\n model = torch.nn.DataParallel(model).cuda()\n\n # For visualization.\n if args.conditional:\n dim_unsup = int((1.0 - args.condition_ratio) * np.prod(data_shape))\n fixed_y = torch.from_numpy(np.arange(model.module.y_class)).repeat(model.module.y_class).type(torch.long).to(device, non_blocking=True)\n fixed_y_onehot = thops.onehot(fixed_y, num_classes=model.module.y_class)\n with torch.no_grad():\n mean, logs = model.module._prior(fixed_y_onehot)\n fixed_z_sup = modules.GaussianDiag.sample(mean, logs)\n fixed_z_unsup = cvt(torch.randn(model.module.y_class**2, dim_unsup))\n fixed_z = torch.cat((fixed_z_sup, fixed_z_unsup),1)\n else:\n fixed_z = cvt(torch.randn(100, *data_shape))\n \n\n if args.spectral_norm and not args.resume: spectral_norm_power_iteration(model, 500)\n\n best_loss_nll = float(\"inf\")\n best_error_score = float(\"inf\")\n \n for epoch in range(args.begin_epoch, args.num_epochs + 1):\n start_epoch = time.time()\n model.train()\n if args.annealing_std:\n update_scale_std(model.module, epoch)\n \n train_loader = get_train_loader(train_set, epoch)\n for _, (x, y) in enumerate(train_loader):\n start = time.time()\n update_lr(optimizer, itr)\n optimizer.zero_grad()\n\n if not args.conv:\n x = x.view(x.shape[0], -1)\n\n # cast data and move to device\n x = cvt(x)\n \n # compute loss\n if args.conditional:\n loss_nll, loss_xent, y_predicted, atol, rtol, logp_actions, nfe = compute_bits_per_dim_conditional(x, y, model)\n if args.train_mode == \"semisup\":\n loss = loss_nll + args.weight_y * loss_xent\n elif args.train_mode == \"sup\":\n loss = loss_xent\n elif args.train_mode == \"unsup\":\n loss = loss_nll\n else:\n raise ValueError('Choose supported train_mode: semisup, sup, unsup')\n error_score = 1. - np.mean(y_predicted.astype(int) == y.numpy()) \n \n else:\n loss, atol, rtol, logp_actions, nfe = compute_bits_per_dim(x, model)\n loss_nll, loss_xent, error_score = loss, 0., 0.\n \n if regularization_coeffs:\n reg_states = get_regularization(model, regularization_coeffs)\n reg_loss = sum(\n reg_state * coeff for reg_state, coeff in zip(reg_states, regularization_coeffs) if coeff != 0\n )\n loss = loss + reg_loss\n total_time = count_total_time(model)\n loss = loss + total_time * args.time_penalty\n\n # re-weight the gate rewards\n normalized_eta = args.eta / len(logp_actions)\n \n # collect cumulative future rewards\n R = - loss\n cum_rewards = []\n for r in nfe[::-1]:\n R = -normalized_eta * r.view(-1,1) + args.gamma * R\n cum_rewards.insert(0,R)\n \n # apply REINFORCE\n rl_loss = 0\n for lpa, r in zip(logp_actions, cum_rewards):\n rl_loss = rl_loss - lpa.view(-1,1) * args.rl_weight * r\n \n loss = loss + rl_loss.mean()\n \n loss.backward()\n \n grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)\n\n optimizer.step()\n\n if args.spectral_norm: spectral_norm_power_iteration(model, args.spectral_norm_niter)\n \n time_meter.update(time.time() - start)\n loss_meter.update(loss.item())\n nll_meter.update(loss_nll.item())\n if args.conditional:\n xent_meter.update(loss_xent.item())\n else:\n xent_meter.update(loss_xent)\n error_meter.update(error_score)\n steps_meter.update(count_nfe_gate(model))\n grad_meter.update(grad_norm)\n tt_meter.update(total_time)\n \n for idx in range(len(model.module.transforms)):\n for layer in model.module.transforms[idx].chain:\n if hasattr(layer, 'atol'):\n layer.odefunc.after_odeint()\n \n # write to tensorboard\n writer.add_scalars('time', {'train_iter': time_meter.val}, itr)\n writer.add_scalars('loss', {'train_iter': loss_meter.val}, itr)\n writer.add_scalars('bits_per_dim', {'train_iter': nll_meter.val}, itr)\n writer.add_scalars('xent', {'train_iter': xent_meter.val}, itr)\n writer.add_scalars('error', {'train_iter': error_meter.val}, itr)\n writer.add_scalars('nfe', {'train_iter': steps_meter.val}, itr)\n writer.add_scalars('grad', {'train_iter': grad_meter.val}, itr)\n writer.add_scalars('total_time', {'train_iter': tt_meter.val}, itr)\n\n if itr % args.log_freq == 0:\n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_%i'%tol_indx, {'train': atol[tol_indx].mean()}, itr)\n writer.add_scalars('rtol_%i'%tol_indx, {'train': rtol[tol_indx].mean()}, itr)\n \n log_message = (\n \"Iter {:04d} | Time {:.4f}({:.4f}) | Bit/dim {:.4f}({:.4f}) | Xent {:.4f}({:.4f}) | Loss {:.4f}({:.4f}) | Error {:.4f}({:.4f}) \"\n \"Steps {:.0f}({:.2f}) | Grad Norm {:.4f}({:.4f}) | Total Time {:.2f}({:.2f})\".format(\n itr, time_meter.val, time_meter.avg, nll_meter.val, nll_meter.avg, xent_meter.val, xent_meter.avg, loss_meter.val, loss_meter.avg, error_meter.val, error_meter.avg, steps_meter.val, steps_meter.avg, grad_meter.val, grad_meter.avg, tt_meter.val, tt_meter.avg\n )\n )\n if regularization_coeffs:\n log_message = append_regularization_to_log(log_message, regularization_fns, reg_states)\n logger.info(log_message)\n writer.add_text('info', log_message, itr)\n\n itr += 1\n \n # compute test loss\n model.eval()\n if epoch % args.val_freq == 0:\n with torch.no_grad():\n # write to tensorboard\n writer.add_scalars('time', {'train_epoch': time_meter.avg}, epoch)\n writer.add_scalars('loss', {'train_epoch': loss_meter.avg}, epoch)\n writer.add_scalars('bits_per_dim', {'train_epoch': nll_meter.avg}, epoch)\n writer.add_scalars('xent', {'train_epoch': xent_meter.avg}, epoch)\n writer.add_scalars('error', {'train_epoch': error_meter.avg}, epoch)\n writer.add_scalars('nfe', {'train_epoch': steps_meter.avg}, epoch)\n writer.add_scalars('grad', {'train_epoch': grad_meter.avg}, epoch)\n writer.add_scalars('total_time', {'train_epoch': tt_meter.avg}, epoch)\n \n start = time.time()\n logger.info(\"validating...\")\n writer.add_text('info', \"validating...\", epoch)\n losses_nll = []; losses_xent = []; losses = []\n total_correct = 0\n \n for (x, y) in test_loader:\n if not args.conv:\n x = x.view(x.shape[0], -1)\n x = cvt(x)\n if args.conditional:\n loss_nll, loss_xent, y_predicted, atol, rtol, logp_actions, nfe = compute_bits_per_dim_conditional(x, y, model)\n if args.train_mode == \"semisup\":\n loss = loss_nll + args.weight_y * loss_xent\n elif args.train_mode == \"sup\":\n loss = loss_xent\n elif args.train_mode == \"unsup\":\n loss = loss_nll\n else:\n raise ValueError('Choose supported train_mode: semisup, sup, unsup')\n total_correct += np.sum(y_predicted.astype(int) == y.numpy())\n else:\n loss, atol, rtol, logp_actions, nfe = compute_bits_per_dim(x, model)\n loss_nll, loss_xent = loss, 0.\n losses_nll.append(loss_nll.cpu().numpy()); losses.append(loss.cpu().numpy())\n if args.conditional: \n losses_xent.append(loss_xent.cpu().numpy())\n else:\n losses_xent.append(loss_xent)\n \n loss_nll = np.mean(losses_nll); loss_xent = np.mean(losses_xent); loss = np.mean(losses)\n error_score = 1. - total_correct / len(test_loader.dataset)\n time_epoch_meter.update(time.time() - start_epoch)\n \n # write to tensorboard\n test_time_spent = time.time() - start\n writer.add_scalars('time', {'validation': test_time_spent}, epoch)\n writer.add_scalars('epoch_time', {'validation': time_epoch_meter.val}, epoch)\n writer.add_scalars('bits_per_dim', {'validation': loss_nll}, epoch)\n writer.add_scalars('xent', {'validation': loss_xent}, epoch)\n writer.add_scalars('loss', {'validation': loss}, epoch)\n writer.add_scalars('error', {'validation': error_score}, epoch)\n \n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_%i'%tol_indx, {'validation': atol[tol_indx].mean()}, epoch)\n writer.add_scalars('rtol_%i'%tol_indx, {'validation': rtol[tol_indx].mean()}, epoch)\n \n log_message = \"Epoch {:04d} | Time {:.4f}, Epoch Time {:.4f}({:.4f}), Bit/dim {:.4f}(best: {:.4f}), Xent {:.4f}, Loss {:.4f}, Error {:.4f}(best: {:.4f})\".format(epoch, time.time() - start, time_epoch_meter.val, time_epoch_meter.avg, loss_nll, best_loss_nll, loss_xent, loss, error_score, best_error_score)\n logger.info(log_message)\n writer.add_text('info', log_message, epoch)\n \n for name, param in model.named_parameters():\n writer.add_histogram(name, param.clone().cpu().data.numpy(), epoch)\n \n \n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"epoch_%i_checkpt.pth\"%epoch))\n \n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"current_checkpt.pth\"))\n \n if loss_nll < best_loss_nll:\n best_loss_nll = loss_nll\n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"best_nll_checkpt.pth\"))\n \n if args.conditional:\n if error_score < best_error_score:\n best_error_score = error_score\n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"best_error_checkpt.pth\"))\n \n\n # visualize samples and density\n with torch.no_grad():\n fig_filename = os.path.join(args.save, \"figs\", \"{:04d}.jpg\".format(epoch))\n utils.makedirs(os.path.dirname(fig_filename))\n generated_samples, atol, rtol, logp_actions, nfe = model(fixed_z, reverse=True)\n generated_samples = generated_samples.view(-1, *data_shape)\n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_gen_%i'%tol_indx, {'validation': atol[tol_indx].mean()}, epoch)\n writer.add_scalars('rtol_gen_%i'%tol_indx, {'validation': rtol[tol_indx].mean()}, epoch)\n save_image(generated_samples, fig_filename, nrow=10)\n if args.data == \"mnist\":\n writer.add_images('generated_images', generated_samples.repeat(1,3,1,1), epoch)\n else:\n writer.add_images('generated_images', generated_samples.repeat(1,1,1,1), epoch)\nNamespace(JFrobint=None, JdiagFrobint=None, JoffdiagFrobint=None, add_noise=True, alpha=1e-06, annealing_std=True, atol=0.0001, autoencode=False, batch_norm=False, batch_size=8000, batch_size_schedule='', begin_epoch=1, condition_ratio=0.5, conditional=True, controlled_tol=True, conv=True, data='cifar10', dims='64,64,64', divergence_fn='approximate', dl2int=None, dropout_rate=0.5, eta=0.1, gamma=0.99, gate='cnn2', imagesize=None, l1int=None, l2int=None, layer_type='concat', log_freq=1, lr=0.001, max_grad_norm=20.0, multiscale=True, nonlinearity='softplus', num_blocks=2, num_epochs=500, parallel=False, rademacher=True, residual=False, resume=None, rl_weight=0.01, rtol=0.0001, save='../experiments_published/cnf_conditional_disentangle_cifar10_bs8K_sratio_0_5_drop_0_5_rl_stdlearnscale_30_annealing_run3', scale=1.0, scale_fac=1.0, scale_std=30.0, seed=3, solver='dopri5', spectral_norm=False, spectral_norm_niter=10, step_size=None, strides='1,1,1,1', test_atol=None, test_batch_size=5000, test_rtol=None, test_solver=None, time_length=1.0, time_penalty=0, train_T=True, train_mode='semisup', val_freq=1, warmup_iters=1000.0, weight_decay=0.0, weight_y=0.5)\n"
]
]
] | [
"code"
] | [
[
"code"
]
] |
e72156e87ff0a025531293b073315b076cad60a0 | 273,799 | ipynb | Jupyter Notebook | docs/source/_docs/introduction.ipynb | jasonrwang/pyNetLogo | 01117c9d9c7d4d5681fe1e08f8862d6b64c9a4b7 | [
"BSD-3-Clause"
] | null | null | null | docs/source/_docs/introduction.ipynb | jasonrwang/pyNetLogo | 01117c9d9c7d4d5681fe1e08f8862d6b64c9a4b7 | [
"BSD-3-Clause"
] | null | null | null | docs/source/_docs/introduction.ipynb | jasonrwang/pyNetLogo | 01117c9d9c7d4d5681fe1e08f8862d6b64c9a4b7 | [
"BSD-3-Clause"
] | null | null | null | 257.571966 | 89,888 | 0.900358 | [
[
[
"## Example 1: NetLogo interaction through the pyNetLogo connector\n\nThis notebook provides a simple example of interaction between a NetLogo model and the Python environment, using the Wolf Sheep Predation model included in the NetLogo example library (Wilensky, 1999). This model is slightly modified to add additional agent properties and illustrate the exchange of different data types. All files used in the example are available from the pyNetLogo repository at https://github.com/quaquel/pyNetLogo.\n\nWe start by instantiating a link to NetLogo, loading the model, and executing the `setup` command in NetLogo.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('white')\nsns.set_context('talk')\n\nimport pyNetLogo\n\nnetlogo = pyNetLogo.NetLogoLink(gui=True)\n\nnetlogo.load_model('./models/Wolf Sheep Predation_v6.nlogo')\nnetlogo.command('setup')",
"_____no_output_____"
]
],
[
[
"We can use the `write_NetLogo_attriblist` method to pass properties to agents from a Pandas dataframe -- for instance, initial values for given attributes. This improves performance by simultaneously setting multiple properties for multiple agents in a single function call.\n\nAs an example, we first load data from an Excel file into a dataframe. Each row corresponds to an agent, with columns for each attribute (including the `who` NetLogo identifier, which is required). In this case, we set coordinates for the agents using the `xcor` and `ycor` attributes.",
"_____no_output_____"
]
],
[
[
"agent_xy = pd.read_excel('./data/xy_DataFrame.xlsx')\nagent_xy[['who','xcor','ycor']].head(5)",
"_____no_output_____"
]
],
[
[
"We can then pass the dataframe to NetLogo, specifying which attributes and which agent type we want to update:",
"_____no_output_____"
]
],
[
[
"netlogo.write_NetLogo_attriblist(agent_xy[['who','xcor','ycor']], 'a-sheep')",
"_____no_output_____"
]
],
[
[
"We can check the data exchange by returning data from NetLogo to the Python workspace, using the report method. In the example below, this returns arrays for the `xcor` and `ycor` coordinates of the `sheep` agents, sorted by their `who` number. These are then plotted on a conventional scatter plot.\n\nThe `report` method directly passes a string to the NetLogo instance, so that the command syntax may need to be adjusted depending on the NetLogo version. The `netlogo_version` property of the link object can be used to check the current version. By default, the link object will use the most recent NetLogo version which was found.",
"_____no_output_____"
]
],
[
[
"if netlogo.netlogo_version == '6':\n x = netlogo.report('map [s -> [xcor] of s] sort sheep')\n y = netlogo.report('map [s -> [ycor] of s] sort sheep')\nelif netlogo.netlogo_version == '5':\n x = netlogo.report('map [[xcor] of ?1] sort sheep')\n y = netlogo.report('map [[ycor] of ?1] sort sheep')",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(1)\n\nax.scatter(x, y, s=4)\nax.set_xlabel('xcor')\nax.set_ylabel('ycor')\nax.set_aspect('equal')\nfig.set_size_inches(5,5)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"We can then run the model for 100 ticks and update the Python coordinate arrays for the sheep agents, and return an additional array for each agent's energy value. The latter is plotted on a histogram for each agent type.",
"_____no_output_____"
]
],
[
[
"#We can use either of the following commands to run for 100 ticks:\n\nnetlogo.command('repeat 100 [go]')\n#netlogo.repeat_command('go', 100)\n\nif netlogo.netlogo_version == '6':\n #Return sorted arrays so that the x, y and energy properties of each agent are in the same order\n x = netlogo.report('map [s -> [xcor] of s] sort sheep')\n y = netlogo.report('map [s -> [ycor] of s] sort sheep')\n energy_sheep = netlogo.report('map [s -> [energy] of s] sort sheep')\nelif netlogo.netlogo_version == '5':\n x = netlogo.report('map [[xcor] of ?1] sort sheep')\n y = netlogo.report('map [[ycor] of ?1] sort sheep')\n energy_sheep = netlogo.report('map [[energy] of ?1] sort sheep')\n \nenergy_wolves = netlogo.report('[energy] of wolves') #NetLogo returns these in random order",
"_____no_output_____"
],
[
"from mpl_toolkits.axes_grid1 import make_axes_locatable\n\nfig, ax = plt.subplots(1, 2)\n\nsc = ax[0].scatter(x, y, s=50, c=energy_sheep,\n cmap=plt.cm.coolwarm)\nax[0].set_xlabel('xcor')\nax[0].set_ylabel('ycor')\nax[0].set_aspect('equal')\ndivider = make_axes_locatable(ax[0])\ncax = divider.append_axes('right', size='5%', pad=0.1)\ncbar = plt.colorbar(sc, cax=cax, orientation='vertical')\ncbar.set_label('Energy of sheep')\n\nsns.distplot(energy_sheep, kde=False, bins=10,\n ax=ax[1], label='Sheep')\nsns.distplot(energy_wolves, kde=False, bins=10,\n ax=ax[1], label='Wolves')\nax[1].set_xlabel('Energy')\nax[1].set_ylabel('Counts')\nax[1].legend()\nfig.set_size_inches(14,5)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"The `repeat_report` method returns a Pandas dataframe containing reported values over a given number of ticks, for one or multiple reporters. By default, this assumes the model is run with the \"go\" NetLogo command; this can be set by passing an optional `go` argument. \n\nThe dataframe is indexed by ticks, with labeled columns for each reporter. In this case, we track the number of wolf and sheep agents over 200 ticks; the outcomes are first plotted as a function of time. The number of wolf agents is then plotted as a function of the number of sheep agents, to approximate a phase-space plot. ",
"_____no_output_____"
]
],
[
[
"counts = netlogo.repeat_report(['count wolves','count sheep'], 200, go='go')",
"_____no_output_____"
],
[
"counts",
"_____no_output_____"
],
[
"fig, (ax1, ax2) = plt.subplots(1, 2)\n\ncounts.plot(ax=ax1, use_index=True, legend=True)\nax1.set_xlabel('Ticks')\nax1.set_ylabel('Counts')\n\nax2.plot(counts['count wolves'], counts['count sheep'])\nax2.set_xlabel('Wolves')\nax2.set_ylabel('Sheep')\nfig.set_size_inches(12,5)\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"The `repeat_report` method can also be used with reporters that return a NetLogo list. In this case, the list is converted to a numpy array. As an example, we track the energy of the wolf and sheep agents over 5 ticks, and plot the distribution of the wolves' energy at the final tick recorded in the dataframe.\n\nTo illustrate different data types, we also track the `[sheep_str] of sheep` reporter (which returns a string property across the sheep agents, converted to a numpy object array), `count sheep` (returning a single numerical variable), and `glob_str` (returning a single string variable).",
"_____no_output_____"
]
],
[
[
"energy_df = netlogo.repeat_report(['[energy] of wolves',\n '[energy] of sheep',\n '[sheep_str] of sheep',\n 'count sheep',\n 'glob_str'], 5)\n\nfig, ax = plt.subplots(1)\n\nsns.distplot(energy_df['[energy] of wolves'].iloc[-1], kde=False, bins=20, ax=ax)\nax.set_xlabel('Energy')\nax.set_ylabel('Counts')\nfig.set_size_inches(4,4)\n\nplt.show()",
"_____no_output_____"
],
[
"energy_df.head()",
"_____no_output_____"
]
],
[
[
" ",
"_____no_output_____"
],
[
"The `patch_report` method can be used to return a dataframe which (for this example) contains the `countdown` attribute of each NetLogo patch. This dataframe essentially replicates the NetLogo environment, with column labels corresponding to the xcor patch coordinates, and indices following the pycor coordinates.",
"_____no_output_____"
]
],
[
[
"countdown_df = netlogo.patch_report('countdown')\n\nfig, ax = plt.subplots(1)\n\npatches = sns.heatmap(countdown_df, xticklabels=5, yticklabels=5,\n cbar_kws={'label':'countdown'}, ax=ax)\nax.set_xlabel('pxcor')\nax.set_ylabel('pycor')\nax.set_aspect('equal')\nfig.set_size_inches(8,4)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"The dataframes can be manipulated with any of the existing Pandas functions, for instance by exporting to an Excel file. The `patch_set` method provides the inverse functionality to `patch_report`, and updates the NetLogo environment from a dataframe.",
"_____no_output_____"
]
],
[
[
"countdown_df.to_excel('countdown.xlsx')\nnetlogo.patch_set('countdown', countdown_df.max()-countdown_df)",
"_____no_output_____"
],
[
"countdown_update_df = netlogo.patch_report('countdown')\n\nfig, ax = plt.subplots(1)\n\npatches = sns.heatmap(countdown_update_df, xticklabels=5, yticklabels=5, cbar_kws={'label':'countdown'}, ax=ax)\nax.set_xlabel('pxcor')\nax.set_ylabel('pycor')\nax.set_aspect('equal')\nfig.set_size_inches(8,4)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"Finally, the `kill_workspace()` method shuts down the NetLogo instance.",
"_____no_output_____"
]
],
[
[
"netlogo.kill_workspace()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7215cb4405c3804d3e774709cd5ab45f2135be1 | 12,075 | ipynb | Jupyter Notebook | Python/2. Python Basics (cont.)/3. Pandas/Notebooks/Start Learning Here/Part-1b_1-(D-Tale)/D-Tale_introduction.ipynb | okara83/Becoming-a-Data-Scientist | f09a15f7f239b96b77a2f080c403b2f3e95c9650 | [
"MIT"
] | null | null | null | Python/2. Python Basics (cont.)/3. Pandas/Notebooks/Start Learning Here/Part-1b_1-(D-Tale)/D-Tale_introduction.ipynb | okara83/Becoming-a-Data-Scientist | f09a15f7f239b96b77a2f080c403b2f3e95c9650 | [
"MIT"
] | null | null | null | Python/2. Python Basics (cont.)/3. Pandas/Notebooks/Start Learning Here/Part-1b_1-(D-Tale)/D-Tale_introduction.ipynb | okara83/Becoming-a-Data-Scientist | f09a15f7f239b96b77a2f080c403b2f3e95c9650 | [
"MIT"
] | 2 | 2022-02-09T15:41:33.000Z | 2022-02-11T07:47:40.000Z | 38.701923 | 406 | 0.636439 | [
[
[
"import dtale\nimport pandas as pd",
"_____no_output_____"
],
[
"df = pd.read_csv('national-history.csv')",
"_____no_output_____"
],
[
"dtale.show(df)",
"_____no_output_____"
]
],
[
[
"Unlike Pandas, you can interact with the dataset and the library without typing code. \nAlso, D-Tale shows more information than Pandas right on the first screen.\n\nFirst, we can scroll down to the right to see more data. In Pandas, this is not as easy and intuitive as D-Tale. Then, in the left-hand corner, you can see the number of columns and rows in the left-hand corner without typing any code. Rovering at the top, you will see the navigation menu.",
"_____no_output_____"
],
[
"## Opening D-Tale In a separate tab for demonstration purposes",
"_____no_output_____"
],
[
"Another thing about D-Tale is that <b>we don’t need to use it on Jupyter Notebook</b>!!!! So, let’s use D-Tale in a different tab for demonstration purposes. It’s up to you how you want to use it, though. Use the code below.\n",
"_____no_output_____"
]
],
[
[
"dtale.show(df).open_browser()",
"_____no_output_____"
]
],
[
[
"# Data Preparation\n## Change datatype with one click\nChanging datatype is not difficult on Pandas, even for beginners, and you shouldn’t have problems changing them for one or two features. However, what if you need to change the datatype of 300+ features? This is not uncommon a professional environment, and typing hundreds of code lines is not the best use of our time for tasks like this. With D-Tale, we can change datatypes within a few clicks.\n\n<br>For example, in this dataset, I noticed that the date column is a string. We don’t want that. Let’s change it to DateTime. Just click on the column name, and right below the column name, click on Type Conversion, and select if you want to change inplace or create a new column. Select the datatype, change the date format, and click Apply. That’s it!",
"_____no_output_____"
],
[
"Also, There is a bonus. Before applying the change, you can see the code that will be used. If you are learning Python, that’s a fantastic add-on. There is more. Once the datatype is a DateTime, we can see additional information when clicking on the column name, such as skewness. ",
"_____no_output_____"
],
[
"## Create a new column with a different format\nWe can also create a new column with a different format. For demonstration purposes, let’s convert the date column into a string. Just click on the column name you want to convert, then click on Type Conversion, click on New Column, choose the new column name, and select the datatype. Done!\n\n",
"_____no_output_____"
],
[
"## Dropping columns\nDropping columns couldn’t be easier. Select the column you want to delete, click on Delete, click on Yes in the pop-up window, and the column is gone. And yeah, typing the code to drop columns is just as easy, but not this easy.\n",
"_____no_output_____"
],
[
"## Change the column’s name\nRenaming columns process: click, rename, save. This easy! Just click on the column’s name, click on Rename, choose the name, and save it. It’s done. This is particularly handy if you need to change the name of dozens of columns.\n\n\n",
"_____no_output_____"
],
[
"## Data Transformation\n### Filtering data\nFiltering data is extremely easy. Click on the column you want to filter. At the bottom, you will see the filtering options. You can filter any datatype. D-Tale has filtering options such as equals, greater/smaller than, different than, etc. ",
"_____no_output_____"
],
[
"# Merging data\nTo merge two dataframes, click on the ▶ icon at the top left, and a new tab will open. You can upload datasets straight from the UI. Choose the datasets, how you want to join them, and that’s pretty much it. You can also see the code at the bottom if you’re going to use it in another project.",
"_____no_output_____"
],
[
"### Grouping By\nTo group by, click on Summarize Data, select the columns you want to group by, the function (sum, count, mean, median, etc), and it’s done. You can open it in the same tab or a different tab.\n",
"_____no_output_____"
],
[
"\n## Describe data\nNeed a quick summary of a feature? Not a problem. With D-Tale, you can see information such as value counts, missing values, frequency, statistics summarization such as mean, median, percentiles, standard deviation, skewness, word counts, and much more. Depending on the data type, it also shows a plot of the data, such as histogram, time series, bar plot, and so on.\nTo do so, just click on the column’s name, then click on Describe (column analysis), and you will see a lot of cool information\n\nIf you want to quickly navigate through all the columns, you can click on the ▶ sign at the top right, click on the summary option, and you will be able to check all the features individually with a click.\n",
"_____no_output_____"
],
[
"## Data Visualization\nData visualization is one of the most time-consuming tasks during data analyses. It can be a nightmare for beginners to make them look good, but fortunately, D-Tale can also help with that. You can create visualizations with a few clicks, and the best part: you can get the code and learn what is going on.",
"_____no_output_____"
],
[
"### Bar plot\nLet’s start creating a bar plot. To create a bar plot, click on the top right, go to charts, and a GUI will open. There, you can select one type of plot between thirteen options! From there, select the X and Y variables, the type of aggregation, if any, and voilá, you just got a nice looking graph.\nIn the example below, I’m putting continent in the x-axis and number of total COVID cases by continent in the y-axis.\n\nIf you want to group the data, write the variable you want to group and do. In this example, I’m grouping the countries into continent groups.\n\n",
"_____no_output_____"
],
[
"### Plot code\nNow you can easily get the code to check how the plot was created. It’s a good way of learning or even delivering final products, since the charts are good looking and could be use as the final version.",
"_____no_output_____"
],
[
"### Scatter Plot\nCreating a scatter plot is just as easy as a bar plot. Choose the x- and y-axis, group, if you want to, and boom. You got a scatter plot. Below, I’m checking the relationship between the number of new cases and the number of vaccinated people against COVID-19.\n",
"_____no_output_____"
],
[
"# Time Series\nD-Tale takes time series to another level. With one click, you can easily create a time series plot with them and go over different time series types, such as Hodrick-Prescott and Bacter-King filters.\n",
"_____no_output_____"
],
[
"## Describe Dataset\nWe already talked about this topic, but I want to mention some exciting visualizations that you can create with the summarization feature, such as histograms, exploring categories, and creating a QQ plot.\nHowever, the coolest part is that you can interact the chosen columns with other columns and create instantaneous graphs. This is the best way to understand your dataset without spending hours typing code to get results that you could get with one click.",
"_____no_output_____"
],
[
"## More D-Tale Feature\nOn top of the data analysis options, D-Tale also offers some additional settings, such as choosing language and dark mode.\n",
"_____no_output_____"
],
[
"### Change language and dark mode\nD-Tale has some more complex tasks that can be confusing for non-English speakers, and if you are native language is Chinese or Portuguese, I got good news: D-Tale supports these two languages in addition to English to translate their UI.\nIt also supports dark mode for those who like it. I’m not the biggest fan of dark mode because I find it harder to read, but you should like this additional feature if you don’t have this problem.",
"_____no_output_____"
],
[
"### Highlight columns\nD-Tale allows us to highlight data depending on a few options. For example, you can highlight the data depending on the data type. We can also highlight NaN values and outliers to avoid missing them. You can also highlight data based on arguments, such as greater or smaller than a specific number.\n\nD-Tale could make your life much easier, even for those seasoned professionals, by turning tedious tasks into intuitive ones. There are so many cool and more complex features that were left out of this blog, so I recommend you to try it out, explore it, and find more features that will be useful for yo",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown"
] | [
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e72160c5b79048d148221f1d1e93353715f19ba7 | 1,541 | ipynb | Jupyter Notebook | Index.ipynb | jairideout/scikit-bio-cookbook | 4b3d323c46f7afb5cf6f5bc1fa0a173d3f616a71 | [
"BSD-3-Clause"
] | null | null | null | Index.ipynb | jairideout/scikit-bio-cookbook | 4b3d323c46f7afb5cf6f5bc1fa0a173d3f616a71 | [
"BSD-3-Clause"
] | null | null | null | Index.ipynb | jairideout/scikit-bio-cookbook | 4b3d323c46f7afb5cf6f5bc1fa0a173d3f616a71 | [
"BSD-3-Clause"
] | null | null | null | 32.104167 | 427 | 0.621674 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e7216fa3bb6666e8965a2459ee9d10f1c0ef3c30 | 5,164 | ipynb | Jupyter Notebook | notebooks/archive/07-student-hierarchical-finches.ipynb | francescolosterzo/bayesian-stats-modelling-tutorial | c3e96f411269b7dc53a390a84c6dba48df77d83c | [
"MIT"
] | 602 | 2018-02-01T19:06:18.000Z | 2022-03-09T16:07:46.000Z | notebooks/archive/07-student-hierarchical-finches.ipynb | anmin/bayesian-stats-modelling-tutorial | afc521d9f6acf83b993f36c858340c8c72589cb3 | [
"MIT"
] | 61 | 2018-06-26T04:39:50.000Z | 2021-08-02T18:09:16.000Z | notebooks/archive/07-student-hierarchical-finches.ipynb | anmin/bayesian-stats-modelling-tutorial | afc521d9f6acf83b993f36c858340c8c72589cb3 | [
"MIT"
] | 261 | 2018-07-08T02:44:22.000Z | 2022-03-07T18:15:20.000Z | 22.068376 | 161 | 0.544733 | [
[
[
"# Introduction\n\nThis notebook is designed to be the \"exercise\" notebook for you to practice defining hierarchical models. We will do this with the finches dataset again.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport pymc3 as pm\nfrom data import load_finches_2012\nimport arviz as az\n\n%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'",
"_____no_output_____"
],
[
"df = load_finches_2012()\ndf.groupby('species').size()",
"_____no_output_____"
],
[
"df.sample(5)",
"_____no_output_____"
],
[
"df.groupby('species')['beak_depth'].describe()",
"_____no_output_____"
],
[
"fortis_filter = df['species'] == 'fortis'\nscandens_filter = df['species'] == 'scandens'\nunknown_filter = df['species'] == 'unknown'",
"_____no_output_____"
]
],
[
[
"**Exercise:** Define a hierarchical model for the finches beak depths. For bonus points, use NumPy-like fancy indexing!\n\nIf you'd like a hint, one possible model you can implement is shown below.\n\n",
"_____no_output_____"
]
],
[
[
"with pm.Model() as beak_depth_model:\n # SD can only be positive, therefore it is reasonable to constrain to >0\n # Likewise for betas.\n sd_hyper = pm._________('sd_hyper', _________)\n beta_hyper = pm._________('beta_hyper', _________)\n \n # Beaks cannot be of \"negative\" mean, therefore, HalfNormal is \n # a reasonable, constrained prior.\n mean = pm._________('mean', _________, shape=_________)\n sd = pm._________('sd', _________, shape=_________)\n nu = pm._________('nu', _________) + 1\n \n # Define the likelihood distribution for the data.\n ",
"_____no_output_____"
]
],
[
[
"Sample from the posterior distribution!",
"_____no_output_____"
]
],
[
[
"# Your code below.\n",
"_____no_output_____"
]
],
[
[
"Visualize the traceplots to check for convergence.",
"_____no_output_____"
]
],
[
[
"# Your code below\n",
"_____no_output_____"
]
],
[
[
"Visualize the posterior distributions using the `plot_posterior` or `forestplot` functions.",
"_____no_output_____"
]
],
[
[
"ax1, ax2, ax3 = pm.plot_posterior(trace, varnames=['mean'])\nax1.set_title('fortis')\nax2.set_title('scandens')\nax3.set_title('unknown')",
"_____no_output_____"
]
],
[
[
"Now, repeat the model specification for beak length.",
"_____no_output_____"
]
],
[
[
"# Model definition",
"_____no_output_____"
],
[
"# Sample from posterior",
"_____no_output_____"
],
[
"# Check for convergence",
"_____no_output_____"
],
[
"# Plot posterior distribution",
"_____no_output_____"
]
],
[
[
"**Discuss:** \n\n- Are the estimates for the unknown species' beak depth and beak length more reasonable? How so?",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e721791e190ae25f0c85ab7390d5494784a045ca | 17,096 | ipynb | Jupyter Notebook | 11 - Tune Hyperparameters.ipynb | pmathur20/mslearn-dp100 | 9fc7301dcd24b8886c03a1c0f85ceedc6e6e1298 | [
"MIT"
] | 1 | 2021-08-08T11:20:27.000Z | 2021-08-08T11:20:27.000Z | 11 - Tune Hyperparameters.ipynb | pmathur20/mslearn-dp100 | 9fc7301dcd24b8886c03a1c0f85ceedc6e6e1298 | [
"MIT"
] | null | null | null | 11 - Tune Hyperparameters.ipynb | pmathur20/mslearn-dp100 | 9fc7301dcd24b8886c03a1c0f85ceedc6e6e1298 | [
"MIT"
] | null | null | null | 42.316832 | 746 | 0.623947 | [
[
[
"# Tune Hyperparameters\n\nThere are many machine learning algorithms that require *hyperparameters* (parameter values that influence training, but can't be determined from the training data itself). For example, when training a logistic regression model, you can use a *regularization rate* hyperparameter to counteract bias in the model; or when training a convolutional neural network, you can use hyperparameters like *learning rate* and *batch size* to control how weights are adjusted and how many data items are processed in a mini-batch respectively. The choice of hyperparameter values can significantly affect the performance of a trained model, or the time taken to train it; and often you need to try multiple combinations to find the optimal solution.\n\nIn this case, you'll train a classification model with two hyperparameters, but the principles apply to any kind of model you can train with Azure Machine Learning.",
"_____no_output_____"
],
[
"## Connect to your workspace\n\nTo get started, connect to your workspace.\n\n> **Note**: If you haven't already established an authenticated session with your Azure subscription, you'll be prompted to authenticate by clicking a link, entering an authentication code, and signing into Azure.",
"_____no_output_____"
]
],
[
[
"import azureml.core\nfrom azureml.core import Workspace\n\n# Load the workspace from the saved config file\nws = Workspace.from_config()\nprint('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))",
"_____no_output_____"
]
],
[
[
"## Prepare data\n\nIn this lab, you'll use a dataset containing details of diabetes patients. Run the cell below to create this dataset (if it already exists, the existing version will be used)",
"_____no_output_____"
]
],
[
[
"from azureml.core import Dataset\n\ndefault_ds = ws.get_default_datastore()\n\nif 'diabetes dataset' not in ws.datasets:\n default_ds.upload_files(files=['./data/diabetes.csv', './data/diabetes2.csv'], # Upload the diabetes csv files in /data\n target_path='diabetes-data/', # Put it in a folder path in the datastore\n overwrite=True, # Replace existing files of the same name\n show_progress=True)\n\n #Create a tabular dataset from the path on the datastore (this may take a short while)\n tab_data_set = Dataset.Tabular.from_delimited_files(path=(default_ds, 'diabetes-data/*.csv'))\n\n # Register the tabular dataset\n try:\n tab_data_set = tab_data_set.register(workspace=ws, \n name='diabetes dataset',\n description='diabetes data',\n tags = {'format':'CSV'},\n create_new_version=True)\n print('Dataset registered.')\n except Exception as ex:\n print(ex)\nelse:\n print('Dataset already registered.')",
"_____no_output_____"
]
],
[
[
"## Prepare a training script\n\nNow let's create a folder for the training script you'll use to train the model.",
"_____no_output_____"
]
],
[
[
"import os\n\nexperiment_folder = 'diabetes_training-hyperdrive'\nos.makedirs(experiment_folder, exist_ok=True)\n\nprint('Folder ready.')",
"_____no_output_____"
]
],
[
[
"Now create the Python script to train the model. In this example, you'll use a *Gradient Boosting* algorithm to train a classification model. The script must include:\n\n- An argument for each hyperparameter you want to optimize (in this case, the learning rate and number of estimators for the Gradient Boosting algorithm)\n- Code to log the performance metric you want to optimize for (in this case, you'll log both AUC and accuracy, so you can choose to optimize the model for either of these)",
"_____no_output_____"
]
],
[
[
"%%writefile $experiment_folder/diabetes_training.py\n# Import libraries\nimport argparse, joblib, os\nfrom azureml.core import Run\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.metrics import roc_auc_score, roc_curve\n\n# Get the experiment run context\nrun = Run.get_context()\n\n# Get script arguments\nparser = argparse.ArgumentParser()\n\n# Input dataset\nparser.add_argument(\"--input-data\", type=str, dest='input_data', help='training dataset')\n\n# Hyperparameters\nparser.add_argument('--learning_rate', type=float, dest='learning_rate', default=0.1, help='learning rate')\nparser.add_argument('--n_estimators', type=int, dest='n_estimators', default=100, help='number of estimators')\n\n# Add arguments to args collection\nargs = parser.parse_args()\n\n# Log Hyperparameter values\nrun.log('learning_rate', np.float(args.learning_rate))\nrun.log('n_estimators', np.int(args.n_estimators))\n\n# load the diabetes dataset\nprint(\"Loading Data...\")\ndiabetes = run.input_datasets['training_data'].to_pandas_dataframe() # Get the training data from the estimator input\n\n# Separate features and labels\nX, y = diabetes[['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']].values, diabetes['Diabetic'].values\n\n# Split data into training set and test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)\n\n# Train a Gradient Boosting classification model with the specified hyperparameters\nprint('Training a classification model')\nmodel = GradientBoostingClassifier(learning_rate=args.learning_rate,\n n_estimators=args.n_estimators).fit(X_train, y_train)\n\n# calculate accuracy\ny_hat = model.predict(X_test)\nacc = np.average(y_hat == y_test)\nprint('Accuracy:', acc)\nrun.log('Accuracy', np.float(acc))\n\n# calculate AUC\ny_scores = model.predict_proba(X_test)\nauc = roc_auc_score(y_test,y_scores[:,1])\nprint('AUC: ' + str(auc))\nrun.log('AUC', np.float(auc))\n\n# Save the model in the run outputs\nos.makedirs('outputs', exist_ok=True)\njoblib.dump(value=model, filename='outputs/diabetes_model.pkl')\n\nrun.complete()",
"_____no_output_____"
]
],
[
[
"## Create compute\n\nHyperparameter tuning involves running multiple training iterations with different hyperparameter values and comparing the performance metrics of the resulting models. To do this efficiently, we'll take advantage of on-demand cloud compute and create a cluster - this will allow multiple training iterations to be run concurrently.\n\nUse the following code to specify an Azure Machine Learning compute cluster (it will be created if it doesn't already exist).\n\n> **Important**: Change *your-compute-cluster* to the name of your compute cluster in the code below before running it! Cluster names must be globally unique names between 2 to 16 characters in length. Valid characters are letters, digits, and the - character.",
"_____no_output_____"
]
],
[
[
"from azureml.core.compute import ComputeTarget, AmlCompute\nfrom azureml.core.compute_target import ComputeTargetException\n\ncluster_name = \"your-compute-cluster\"\n\ntry:\n # Check for existing compute target\n training_cluster = ComputeTarget(workspace=ws, name=cluster_name)\n print('Found existing cluster, use it.')\nexcept ComputeTargetException:\n # If it doesn't already exist, create it\n try:\n compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS11_V2', max_nodes=2)\n training_cluster = ComputeTarget.create(ws, cluster_name, compute_config)\n training_cluster.wait_for_completion(show_output=True)\n except Exception as ex:\n print(ex)\n ",
"_____no_output_____"
]
],
[
[
"> **Note**: Compute instances and clusters are based on standard Azure virtual machine images. For this exercise, the *Standard_DS11_v2* image is recommended to achieve the optimal balance of cost and performance. If your subscription has a quota that does not include this image, choose an alternative image; but bear in mind that a larger image may incur higher cost and a smaller image may not be sufficient to complete the tasks. Alternatively, ask your Azure administrator to extend your quota.\n\nYou'll need a Python environment to be hosted on the compute, so let's define that as Conda configuration file.",
"_____no_output_____"
]
],
[
[
"%%writefile $experiment_folder/hyperdrive_env.yml\nname: batch_environment\ndependencies:\n- python=3.6.2\n- scikit-learn\n- pip\n- pip:\n - azureml-defaults\n",
"_____no_output_____"
]
],
[
[
"## Run a hyperparameter tuning experiment\n\nAzure Machine Learning includes a hyperparameter tuning capability through *hyperdrive* experiments. These experiments launch multiple child runs, each with a different hyperparameter combination. The run producing the best model (as determined by the logged target performance metric for which you want to optimize) can be identified, and its trained model selected for registration and deployment.\n\n> **Note**: In this example, we aren't specifying an early stopping policy. Such a policy is only relevant if the training script performs multiple training iterations, logging the primary metric for each iteration. This approach is typically employed when training deep neural network models over multiple *epochs*.",
"_____no_output_____"
]
],
[
[
"from azureml.core import Experiment, ScriptRunConfig, Environment\nfrom azureml.train.hyperdrive import GridParameterSampling, HyperDriveConfig, PrimaryMetricGoal, choice\nfrom azureml.widgets import RunDetails\n\n# Create a Python environment for the experiment\nhyper_env = Environment.from_conda_specification(\"experiment_env\", experiment_folder + \"/hyperdrive_env.yml\")\n\n# Get the training dataset\ndiabetes_ds = ws.datasets.get(\"diabetes dataset\")\n\n# Create a script config\nscript_config = ScriptRunConfig(source_directory=experiment_folder,\n script='diabetes_training.py',\n # Add non-hyperparameter arguments -in this case, the training dataset\n arguments = ['--input-data', diabetes_ds.as_named_input('training_data')],\n environment=hyper_env,\n compute_target = training_cluster)\n\n# Sample a range of parameter values\nparams = GridParameterSampling(\n {\n # Hyperdrive will try 6 combinations, adding these as script arguments\n '--learning_rate': choice(0.01, 0.1, 1.0),\n '--n_estimators' : choice(10, 100)\n }\n)\n\n# Configure hyperdrive settings\nhyperdrive = HyperDriveConfig(run_config=script_config, \n hyperparameter_sampling=params, \n policy=None, # No early stopping policy\n primary_metric_name='AUC', # Find the highest AUC metric\n primary_metric_goal=PrimaryMetricGoal.MAXIMIZE, \n max_total_runs=6, # Restict the experiment to 6 iterations\n max_concurrent_runs=2) # Run up to 2 iterations in parallel\n\n# Run the experiment\nexperiment = Experiment(workspace=ws, name='mslearn-diabetes-hyperdrive')\nrun = experiment.submit(config=hyperdrive)\n\n# Show the status in the notebook as the experiment runs\nRunDetails(run).show()\nrun.wait_for_completion()",
"_____no_output_____"
]
],
[
[
"You can view the experiment run status in the widget above. You can also view the main Hyperdrive experiment run and its child runs in [Azure Machine Learning studio](https://ml.azure.com).\n\n> **Note**: If a message indicating that a non-numeric can't be visualized is displayed, you can ignore it.\n\n## Determine the best performing run\n\nWhen all of the runs have finished, you can find the best one based on the performance metric you specified (in this case, the one with the best AUC).",
"_____no_output_____"
]
],
[
[
"# Print all child runs, sorted by the primary metric\nfor child_run in run.get_children_sorted_by_primary_metric():\n print(child_run)\n\n# Get the best run, and its metrics and arguments\nbest_run = run.get_best_run_by_primary_metric()\nbest_run_metrics = best_run.get_metrics()\nscript_arguments = best_run.get_details() ['runDefinition']['arguments']\nprint('Best Run Id: ', best_run.id)\nprint(' -AUC:', best_run_metrics['AUC'])\nprint(' -Accuracy:', best_run_metrics['Accuracy'])\nprint(' -Arguments:',script_arguments)",
"_____no_output_____"
]
],
[
[
"Now that you've found the best run, you can register the model it trained.",
"_____no_output_____"
]
],
[
[
"from azureml.core import Model\n\n# Register model\nbest_run.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model',\n tags={'Training context':'Hyperdrive'},\n properties={'AUC': best_run_metrics['AUC'], 'Accuracy': best_run_metrics['Accuracy']})\n\n# List registered models\nfor model in Model.list(ws):\n print(model.name, 'version:', model.version)\n for tag_name in model.tags:\n tag = model.tags[tag_name]\n print ('\\t',tag_name, ':', tag)\n for prop_name in model.properties:\n prop = model.properties[prop_name]\n print ('\\t',prop_name, ':', prop)\n print('\\n')",
"_____no_output_____"
]
],
[
[
"> **More Information**: For more information about Hyperdrive, see the [Azure ML documentation](https://docs.microsoft.com/azure/machine-learning/how-to-tune-hyperparameters).",
"_____no_output_____"
]
]
] | [
"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"
]
] |
e7217d8ab73872e1c32c641b0aeac9ba9495d039 | 221,723 | ipynb | Jupyter Notebook | I_ForcingFiles/OBC/SSH_Tofino.ipynb | remanevy/Package | b8c394c5b886b2a85063f8da3957ea3ca4bbec3f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | I_ForcingFiles/OBC/SSH_Tofino.ipynb | remanevy/Package | b8c394c5b886b2a85063f8da3957ea3ca4bbec3f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | I_ForcingFiles/OBC/SSH_Tofino.ipynb | remanevy/Package | b8c394c5b886b2a85063f8da3957ea3ca4bbec3f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 231.685475 | 107,125 | 0.887364 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e72186c2aa615a8e65add2ffbfaead1bbe46f181 | 94,164 | ipynb | Jupyter Notebook | Chapter09/chapter_9.ipynb | mocalab/Hands-on-Machine-Learning-for-Cyber-Security | 3580150901bf0d5accbb31c7e9006b39a2a806a0 | [
"MIT"
] | 112 | 2019-03-04T02:27:44.000Z | 2022-03-22T20:54:16.000Z | Chapter09/chapter_9.ipynb | nicolas-gagnon/Hands-on-Machine-Learning-for-Cyber-Security | 8b0a0cf2a73cda71172e7b5104522a7ecd3a6a90 | [
"MIT"
] | 2 | 2019-07-26T17:23:52.000Z | 2022-02-22T14:19:44.000Z | Chapter09/chapter_9.ipynb | nicolas-gagnon/Hands-on-Machine-Learning-for-Cyber-Security | 8b0a0cf2a73cda71172e7b5104522a7ecd3a6a90 | [
"MIT"
] | 84 | 2019-01-16T13:01:12.000Z | 2022-03-27T20:44:20.000Z | 33.774749 | 294 | 0.439595 | [
[
[
"# see http://icsdweb.aegean.gr/awid for more info",
"_____no_output_____"
],
[
"import pandas as pd",
"_____no_output_____"
],
[
"# http://icsdweb.aegean.gr/awid/features.html\n\n# get the names of the features\n \nfeatures = ['frame.interface_id',\n 'frame.dlt',\n 'frame.offset_shift',\n 'frame.time_epoch',\n 'frame.time_delta',\n 'frame.time_delta_displayed',\n 'frame.time_relative',\n 'frame.len',\n 'frame.cap_len',\n 'frame.marked',\n 'frame.ignored',\n 'radiotap.version',\n 'radiotap.pad',\n 'radiotap.length',\n 'radiotap.present.tsft',\n 'radiotap.present.flags',\n 'radiotap.present.rate',\n 'radiotap.present.channel',\n 'radiotap.present.fhss',\n 'radiotap.present.dbm_antsignal',\n 'radiotap.present.dbm_antnoise',\n 'radiotap.present.lock_quality',\n 'radiotap.present.tx_attenuation',\n 'radiotap.present.db_tx_attenuation',\n 'radiotap.present.dbm_tx_power',\n 'radiotap.present.antenna',\n 'radiotap.present.db_antsignal',\n 'radiotap.present.db_antnoise',\n 'radiotap.present.rxflags',\n 'radiotap.present.xchannel',\n 'radiotap.present.mcs',\n 'radiotap.present.ampdu',\n 'radiotap.present.vht',\n 'radiotap.present.reserved',\n 'radiotap.present.rtap_ns',\n 'radiotap.present.vendor_ns',\n 'radiotap.present.ext',\n 'radiotap.mactime',\n 'radiotap.flags.cfp',\n 'radiotap.flags.preamble',\n 'radiotap.flags.wep',\n 'radiotap.flags.frag',\n 'radiotap.flags.fcs',\n 'radiotap.flags.datapad',\n 'radiotap.flags.badfcs',\n 'radiotap.flags.shortgi',\n 'radiotap.datarate',\n 'radiotap.channel.freq',\n 'radiotap.channel.type.turbo',\n 'radiotap.channel.type.cck',\n 'radiotap.channel.type.ofdm',\n 'radiotap.channel.type.2ghz',\n 'radiotap.channel.type.5ghz',\n 'radiotap.channel.type.passive',\n 'radiotap.channel.type.dynamic',\n 'radiotap.channel.type.gfsk',\n 'radiotap.channel.type.gsm',\n 'radiotap.channel.type.sturbo',\n 'radiotap.channel.type.half',\n 'radiotap.channel.type.quarter',\n 'radiotap.dbm_antsignal',\n 'radiotap.antenna',\n 'radiotap.rxflags.badplcp',\n 'wlan.fc.type_subtype',\n 'wlan.fc.version',\n 'wlan.fc.type',\n 'wlan.fc.subtype',\n 'wlan.fc.ds',\n 'wlan.fc.frag',\n 'wlan.fc.retry',\n 'wlan.fc.pwrmgt',\n 'wlan.fc.moredata',\n 'wlan.fc.protected',\n 'wlan.fc.order',\n 'wlan.duration',\n 'wlan.ra',\n 'wlan.da',\n 'wlan.ta',\n 'wlan.sa',\n 'wlan.bssid',\n 'wlan.frag',\n 'wlan.seq',\n 'wlan.bar.type',\n 'wlan.ba.control.ackpolicy',\n 'wlan.ba.control.multitid',\n 'wlan.ba.control.cbitmap',\n 'wlan.bar.compressed.tidinfo',\n 'wlan.ba.bm',\n 'wlan.fcs_good',\n 'wlan_mgt.fixed.capabilities.ess',\n 'wlan_mgt.fixed.capabilities.ibss',\n 'wlan_mgt.fixed.capabilities.cfpoll.ap',\n 'wlan_mgt.fixed.capabilities.privacy',\n 'wlan_mgt.fixed.capabilities.preamble',\n 'wlan_mgt.fixed.capabilities.pbcc',\n 'wlan_mgt.fixed.capabilities.agility',\n 'wlan_mgt.fixed.capabilities.spec_man',\n 'wlan_mgt.fixed.capabilities.short_slot_time',\n 'wlan_mgt.fixed.capabilities.apsd',\n 'wlan_mgt.fixed.capabilities.radio_measurement',\n 'wlan_mgt.fixed.capabilities.dsss_ofdm',\n 'wlan_mgt.fixed.capabilities.del_blk_ack',\n 'wlan_mgt.fixed.capabilities.imm_blk_ack',\n 'wlan_mgt.fixed.listen_ival',\n 'wlan_mgt.fixed.current_ap',\n 'wlan_mgt.fixed.status_code',\n 'wlan_mgt.fixed.timestamp',\n 'wlan_mgt.fixed.beacon',\n 'wlan_mgt.fixed.aid',\n 'wlan_mgt.fixed.reason_code',\n 'wlan_mgt.fixed.auth.alg',\n 'wlan_mgt.fixed.auth_seq',\n 'wlan_mgt.fixed.category_code',\n 'wlan_mgt.fixed.htact',\n 'wlan_mgt.fixed.chanwidth',\n 'wlan_mgt.fixed.fragment',\n 'wlan_mgt.fixed.sequence',\n 'wlan_mgt.tagged.all',\n 'wlan_mgt.ssid',\n 'wlan_mgt.ds.current_channel',\n 'wlan_mgt.tim.dtim_count',\n 'wlan_mgt.tim.dtim_period',\n 'wlan_mgt.tim.bmapctl.multicast',\n 'wlan_mgt.tim.bmapctl.offset',\n 'wlan_mgt.country_info.environment',\n 'wlan_mgt.rsn.version',\n 'wlan_mgt.rsn.gcs.type',\n 'wlan_mgt.rsn.pcs.count',\n 'wlan_mgt.rsn.akms.count',\n 'wlan_mgt.rsn.akms.type',\n 'wlan_mgt.rsn.capabilities.preauth',\n 'wlan_mgt.rsn.capabilities.no_pairwise',\n 'wlan_mgt.rsn.capabilities.ptksa_replay_counter',\n 'wlan_mgt.rsn.capabilities.gtksa_replay_counter',\n 'wlan_mgt.rsn.capabilities.mfpr',\n 'wlan_mgt.rsn.capabilities.mfpc',\n 'wlan_mgt.rsn.capabilities.peerkey',\n 'wlan_mgt.tcprep.trsmt_pow',\n 'wlan_mgt.tcprep.link_mrg',\n 'wlan.wep.iv',\n 'wlan.wep.key',\n 'wlan.wep.icv',\n 'wlan.tkip.extiv',\n 'wlan.ccmp.extiv',\n 'wlan.qos.tid',\n 'wlan.qos.priority',\n 'wlan.qos.eosp',\n 'wlan.qos.ack',\n 'wlan.qos.amsdupresent',\n 'wlan.qos.buf_state_indicated',\n 'wlan.qos.bit4',\n 'wlan.qos.txop_dur_req',\n 'wlan.qos.buf_state_indicated',\n 'data.len',\n 'class']",
"_____no_output_____"
],
[
"# import a training set\nawid = pd.read_csv(\"../data/AWID-CLS-R-Trn.csv\", header=None, names=features)\n\n# see the number of rows/columns\nawid.shape",
"/Users/sinanozdemir/Desktop/cyber/env/lib/python2.7/site-packages/IPython/core/interactiveshell.py:2714: DtypeWarning: Columns (37,38,39,40,41,42,43,44,45,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,74,88) have mixed types. Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n"
],
[
"# they use ? as a null attribute. We will eventually have to replace them with None values\nawid.head()",
"_____no_output_____"
],
[
"# see the distribution of response vars\nawid['class'].value_counts(normalize=True)",
"_____no_output_____"
],
[
"# claims there are no null values because of the ?'s'\nawid.isna().sum()",
"_____no_output_____"
],
[
"# replace the ? marks with None\nawid.replace({\"?\": None}, inplace=True)",
"_____no_output_____"
],
[
"# Many missing pieces of data!\nawid.isna().sum()",
"_____no_output_____"
],
[
"# goal is to remove columns that have over 50% of missing data\ncolumns_with_mostly_null_data = awid.columns[awid.isnull().mean() >= 0.5]\n\n# 72 columns are going to be affected!\ncolumns_with_mostly_null_data.shape",
"_____no_output_____"
],
[
"# drop the columns with over half missing data\nawid.drop(columns_with_mostly_null_data, axis=1, inplace=True)",
"_____no_output_____"
],
[
"awid.shape",
"_____no_output_____"
],
[
"# now drop the rows that have missing values\nawid.dropna(inplace=True) # drop rows with null data",
"_____no_output_____"
],
[
"# lost 456,169 rows\nawid.shape",
"_____no_output_____"
],
[
"# doesn't affect our distribution too much\n\n# 0.878763 is our null accuracy. Our model must be better than this number to be a contender\nawid['class'].value_counts(normalize=True)",
"_____no_output_____"
],
[
"# only select numerical columns for our ML algorithms, there should be more..\nawid.select_dtypes(['number']).shape",
"_____no_output_____"
],
[
"# transform all columns into numerical dtypes\nfor col in awid.columns:\n awid[col] = pd.to_numeric(awid[col], errors='ignore')",
"_____no_output_____"
],
[
"# that makes more sense\nawid.select_dtypes(['number']).shape",
"_____no_output_____"
],
[
"# basic descroptive statistics\nawid.describe()",
"_____no_output_____"
],
[
"X, y = awid.select_dtypes(['number']), awid['class']",
"_____no_output_____"
],
[
"# do a basic naive bayes fitting\nfrom sklearn.naive_bayes import GaussianNB\n\nnb = GaussianNB()\n\n# fit our model to the data\nnb.fit(X, y)",
"_____no_output_____"
],
[
"# read in the test data and do the same transformations to it to match the training data\nawid_test = pd.read_csv(\"../data/AWID-CLS-R-Tst.csv\", header=None, names=features)\n# drop the problematic columns\nawid_test.drop(columns_with_mostly_null_data, axis=1, inplace=True)\n# replace ? with None\nawid_test.replace({\"?\": None}, inplace=True)\n# drop the rows with null data\nawid_test.dropna(inplace=True) # drop rows with null data\n# convert columns to numerical values\nfor col in awid_test.columns:\n awid_test[col] = pd.to_numeric(awid_test[col], errors='ignore')\nawid_test.shape",
"_____no_output_____"
],
[
"# basic metric, accuracy\nfrom sklearn.metrics import accuracy_score",
"_____no_output_____"
],
[
"X_test = awid_test.select_dtypes(['number'])\ny_test = awid_test['class']\n\n# simple function to test the accuracy of a model fitted on training data on our testing data\ndef get_test_accuracy_of(model):\n y_preds = model.predict(X_test)\n return accuracy_score(y_preds, y_test)\n \n# naive abyes does very poorly on its own!\nget_test_accuracy_of(nb)",
"_____no_output_____"
],
[
"from sklearn.linear_model import LogisticRegression\n\nlr = LogisticRegression()\n\nlr.fit(X, y)\n\n# Logistic Regressions does even worse\nget_test_accuracy_of(lr)",
"/Users/sinanozdemir/Desktop/cyber/env/lib/python2.7/site-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n FutureWarning)\n/Users/sinanozdemir/Desktop/cyber/env/lib/python2.7/site-packages/sklearn/linear_model/logistic.py:459: FutureWarning: Default multi_class will be changed to 'auto' in 0.22. Specify the multi_class option to silence this warning.\n \"this warning.\", FutureWarning)\n"
],
[
"from sklearn.tree import DecisionTreeClassifier\n\ntree = DecisionTreeClassifier()\n\ntree.fit(X, y)\n\n# Tree does very well!\nget_test_accuracy_of(tree)",
"_____no_output_____"
],
[
"# see gini scores of decision tree features\npd.DataFrame({'feature':awid.select_dtypes(['number']).columns, \n 'importance':tree.feature_importances_}).sort_values('importance', ascending=False).head(10)",
"_____no_output_____"
],
[
"from sklearn.ensemble import RandomForestClassifier\n\nforest = RandomForestClassifier()\n\nforest.fit(X, y)\n\n# Random Forest does slightly worse\nget_test_accuracy_of(forest)",
"/Users/sinanozdemir/Desktop/cyber/env/lib/python2.7/site-packages/sklearn/ensemble/forest.py:248: FutureWarning: The default value of n_estimators will change from 10 in version 0.20 to 100 in 0.22.\n \"10 in version 0.20 to 100 in 0.22.\", FutureWarning)\n"
],
[
"# Create a pipeline that will scale the numerical data and then feed the resulting data into a decision tree\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import GridSearchCV\n\npreprocessing = Pipeline([\n (\"scale\", StandardScaler()),\n])\n\npipeline = Pipeline([\n (\"preprocessing\", preprocessing),\n (\"classifier\", DecisionTreeClassifier())\n])\n\n# try varying levels of depth\nparams = {\n \"classifier__max_depth\": [None, 3, 5, 10], \n }\n\n# instantiate a gridsearch module\ngrid = GridSearchCV(pipeline, params)\n# fit the module\ngrid.fit(X, y)\n\n# test the best model\nget_test_accuracy_of(grid.best_estimator_)",
"/Users/sinanozdemir/Desktop/cyber/env/lib/python2.7/site-packages/sklearn/model_selection/_split.py:1943: FutureWarning: You should specify a value for 'cv' instead of relying on the default value. The default value will change from 3 to 5 in version 0.22.\n warnings.warn(CV_WARNING, FutureWarning)\n/Users/sinanozdemir/Desktop/cyber/env/lib/python2.7/site-packages/sklearn/preprocessing/data.py:617: DataConversionWarning: Data with input dtype int64, float64 were all converted to float64 by StandardScaler.\n return self.partial_fit(X, y)\n/Users/sinanozdemir/Desktop/cyber/env/lib/python2.7/site-packages/sklearn/base.py:465: DataConversionWarning: Data with input dtype int64, float64 were all converted to float64 by StandardScaler.\n return self.fit(X, y, **fit_params).transform(X)\n/Users/sinanozdemir/Desktop/cyber/env/lib/python2.7/site-packages/sklearn/pipeline.py:451: DataConversionWarning: Data with input dtype int64, float64 were all converted to float64 by StandardScaler.\n Xt = transform.transform(Xt)\n"
],
[
"# try the same thing with a random forest\n\npreprocessing = Pipeline([\n (\"scale\", StandardScaler()),\n])\n\npipeline = Pipeline([\n (\"preprocessing\", preprocessing),\n (\"classifier\", RandomForestClassifier())\n])\n\n# try varying levels of depth\nparams = {\n \"classifier__max_depth\": [None, 3, 5, 10], \n }\n\ngrid = GridSearchCV(pipeline, params)\ngrid.fit(X, y)\n# best accuracy so far!\nget_test_accuracy_of(grid.best_estimator_)",
"_____no_output_____"
],
[
"from sklearn.preprocessing import LabelEncoder\nencoder = LabelEncoder()\nencoded_y = encoder.fit_transform(y)\nencoded_y.shape",
"_____no_output_____"
],
[
"encoded_y",
"_____no_output_____"
],
[
"from sklearn.preprocessing import LabelBinarizer\nbinarizer = LabelBinarizer()\nbinarized_y = binarizer.fit_transform(encoded_y)\nbinarized_y.shape",
"_____no_output_____"
],
[
"binarized_y[:5,]",
"_____no_output_____"
],
[
"y.head()",
"_____no_output_____"
],
[
"print encoder.classes_\nprint binarizer.classes_",
"['flooding' 'impersonation' 'injection' 'normal']\n[0 1 2 3]\n"
],
[
"from keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasClassifier",
"_____no_output_____"
],
[
"# Baseline model for the neural network. We choose a hidden layer of 10 neurons. The lesser number of neurons helps to eliminate the redundancies in the data and select the more important features.\ndef create_baseline_model(n, input_dim):\n # create model\n model = Sequential()\n model.add(Dense(n, input_dim=input_dim, kernel_initializer='normal', activation='relu'))\n model.add(Dense(4, kernel_initializer='normal', activation='sigmoid'))\n # Compile model. We use the the logarithmic loss function, and the Adam gradient optimizer.\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model",
"_____no_output_____"
],
[
"KerasClassifier(build_fn=create_baseline_model, epochs=100, batch_size=5, verbose=0, n=20)",
"_____no_output_____"
],
[
"# use the KerasClassifier\n\npreprocessing = Pipeline([\n (\"scale\", StandardScaler()),\n])\n\npipeline = Pipeline([\n (\"preprocessing\", preprocessing),\n (\"classifier\", KerasClassifier(build_fn=create_baseline_model, epochs=2, batch_size=128, \n verbose=1, n=10, input_dim=74))\n])",
"_____no_output_____"
],
[
"cross_val_score(pipeline, X, binarized_y)",
"Epoch 1/2\n892937/892937 [==============================] - 21s 24us/step - loss: 0.1027 - acc: 0.9683\nEpoch 2/2\n892937/892937 [==============================] - 18s 20us/step - loss: 0.0314 - acc: 0.9910\n446469/446469 [==============================] - 4s 10us/step\nEpoch 1/2\n892937/892937 [==============================] - 24s 27us/step - loss: 0.1089 - acc: 0.9682\nEpoch 2/2\n892937/892937 [==============================] - 19s 22us/step - loss: 0.0305 - acc: 0.9919 0s - loss: 0.0\n446469/446469 [==============================] - 4s 9us/step\nEpoch 1/2\n892938/892938 [==============================] - 18s 20us/step - loss: 0.0619 - acc: 0.9815\nEpoch 2/2\n892938/892938 [==============================] - 17s 20us/step - loss: 0.0153 - acc: 0.9916\n446468/446468 [==============================] - 4s 9us/step\n"
],
[
"# notice the LARGE variance in scores of a neural network. This is due to the high-variance nature of how networks fit\n# using stochastic gradient descent",
"_____no_output_____"
],
[
"pipeline.fit(X, binarized_y)",
"Epoch 1/2\n1339406/1339406 [==============================] - 29s 22us/step - loss: 0.0781 - acc: 0.9740\nEpoch 2/2\n1339406/1339406 [==============================] - 25s 19us/step - loss: 0.0298 - acc: 0.9856\n"
],
[
"# remake \nencoded_y_test = encoder.transform(y_test)\ndef get_network_test_accuracy_of(model):\n y_preds = model.predict(X_test)\n return accuracy_score(y_preds, encoded_y_test)",
"_____no_output_____"
],
[
"# not the best accuracy\nget_network_test_accuracy_of(pipeline)",
"389185/389185 [==============================] - 3s 7us/step\n"
],
[
"# by fitting again, we get a different test accuracy. This also highlights the variance on the network\npipeline.fit(X, binarized_y)\nget_network_test_accuracy_of(pipeline)",
"Epoch 1/2\n1339406/1339406 [==============================] - 29s 21us/step - loss: 0.0844 - acc: 0.9735 0s - loss: 0.085\nEpoch 2/2\n1339406/1339406 [==============================] - 32s 24us/step - loss: 0.0323 - acc: 0.9853 0s - loss: 0.0323 - acc: 0\n389185/389185 [==============================] - 4s 11us/step\n"
],
[
"# add some more epochs to learn more\npreprocessing = Pipeline([\n (\"scale\", StandardScaler()),\n])\n\npipeline = Pipeline([\n (\"preprocessing\", preprocessing),\n (\"classifier\", KerasClassifier(build_fn=create_baseline_model, epochs=10, batch_size=128, \n verbose=1, n=10, input_dim=74))\n])\n\ncross_val_score(pipeline, X, binarized_y)",
"Epoch 1/10\n892937/892937 [==============================] - 20s 22us/step - loss: 0.0945 - acc: 0.9744\nEpoch 2/10\n892937/892937 [==============================] - 17s 19us/step - loss: 0.0349 - acc: 0.9906\nEpoch 3/10\n892937/892937 [==============================] - 16s 18us/step - loss: 0.0293 - acc: 0.9920\nEpoch 4/10\n892937/892937 [==============================] - 17s 20us/step - loss: 0.0261 - acc: 0.9932\nEpoch 5/10\n892937/892937 [==============================] - 18s 20us/step - loss: 0.0231 - acc: 0.9938 0s - loss: 0.0232 - ac\nEpoch 6/10\n892937/892937 [==============================] - 15s 17us/step - loss: 0.0216 - acc: 0.9941\nEpoch 7/10\n892937/892937 [==============================] - 21s 23us/step - loss: 0.0206 - acc: 0.9944\nEpoch 8/10\n892937/892937 [==============================] - 17s 20us/step - loss: 0.0199 - acc: 0.9947 0s - loss: 0.0198 - a\nEpoch 9/10\n892937/892937 [==============================] - 17s 19us/step - loss: 0.0194 - acc: 0.9948\nEpoch 10/10\n892937/892937 [==============================] - 17s 19us/step - loss: 0.0189 - acc: 0.9950\n446469/446469 [==============================] - 4s 10us/step\nEpoch 1/10\n892937/892937 [==============================] - 19s 21us/step - loss: 0.1160 - acc: 0.9618\nEpoch 2/10\n892937/892937 [==============================] - 17s 19us/step - loss: 0.0427 - acc: 0.9843\nEpoch 3/10\n892937/892937 [==============================] - 18s 20us/step - loss: 0.0347 - acc: 0.9875\nEpoch 4/10\n892937/892937 [==============================] - 18s 20us/step - loss: 0.0318 - acc: 0.9895\nEpoch 5/10\n892937/892937 [==============================] - 17s 19us/step - loss: 0.0248 - acc: 0.9937\nEpoch 6/10\n892937/892937 [==============================] - 18s 20us/step - loss: 0.0225 - acc: 0.9942\nEpoch 7/10\n892937/892937 [==============================] - 18s 20us/step - loss: 0.0205 - acc: 0.9948\nEpoch 8/10\n892937/892937 [==============================] - 17s 20us/step - loss: 0.0193 - acc: 0.9951\nEpoch 9/10\n892937/892937 [==============================] - 17s 20us/step - loss: 0.0182 - acc: 0.9954\nEpoch 10/10\n892937/892937 [==============================] - 18s 20us/step - loss: 0.0173 - acc: 0.9956\n446469/446469 [==============================] - 4s 8us/step\nEpoch 1/10\n892938/892938 [==============================] - 26s 29us/step - loss: 0.0552 - acc: 0.9865\nEpoch 2/10\n892938/892938 [==============================] - 23s 25us/step - loss: 0.0068 - acc: 0.9959\nEpoch 3/10\n892938/892938 [==============================] - 19s 21us/step - loss: 0.0054 - acc: 0.9961\nEpoch 4/10\n892938/892938 [==============================] - 19s 21us/step - loss: 0.0048 - acc: 0.9962\nEpoch 5/10\n892938/892938 [==============================] - 18s 20us/step - loss: 0.0043 - acc: 0.9964\nEpoch 6/10\n892938/892938 [==============================] - 18s 20us/step - loss: 0.0040 - acc: 0.9965\nEpoch 7/10\n892938/892938 [==============================] - 18s 20us/step - loss: 0.0038 - acc: 0.9965\nEpoch 8/10\n892938/892938 [==============================] - 18s 20us/step - loss: 0.0037 - acc: 0.9965\nEpoch 9/10\n892938/892938 [==============================] - 17s 19us/step - loss: 0.0035 - acc: 0.9966\nEpoch 10/10\n892938/892938 [==============================] - 18s 20us/step - loss: 0.0035 - acc: 0.9966\n446468/446468 [==============================] - 4s 8us/step\n"
],
[
"# by fitting again, we get a different test accuracy. This also highlights the variance on the network\npipeline.fit(X, binarized_y)\nget_network_test_accuracy_of(pipeline)",
"Epoch 1/10\n1339406/1339406 [==============================] - 30s 22us/step - loss: 0.0812 - acc: 0.9754\nEpoch 2/10\n1339406/1339406 [==============================] - 27s 20us/step - loss: 0.0280 - acc: 0.9915\nEpoch 3/10\n1339406/1339406 [==============================] - 28s 21us/step - loss: 0.0226 - acc: 0.9921\nEpoch 4/10\n1339406/1339406 [==============================] - 27s 20us/step - loss: 0.0193 - acc: 0.9940\nEpoch 5/10\n1339406/1339406 [==============================] - 28s 21us/step - loss: 0.0169 - acc: 0.9951\nEpoch 6/10\n1339406/1339406 [==============================] - 34s 25us/step - loss: 0.0155 - acc: 0.9955\nEpoch 7/10\n1339406/1339406 [==============================] - 38s 28us/step - loss: 0.0148 - acc: 0.9957\nEpoch 8/10\n1339406/1339406 [==============================] - 34s 25us/step - loss: 0.0143 - acc: 0.9958 3s -\nEpoch 9/10\n1339406/1339406 [==============================] - 29s 21us/step - loss: 0.0139 - acc: 0.9960\nEpoch 10/10\n1339406/1339406 [==============================] - 28s 21us/step - loss: 0.0134 - acc: 0.9961\n389185/389185 [==============================] - 3s 8us/step\n"
],
[
"# Took much longer.... and still didn't increase accuracy",
"_____no_output_____"
],
[
"# change our function to have multiple hidden layers in our network\ndef network_builder(hidden_dimensions, input_dim):\n # create model\n model = Sequential()\n model.add(Dense(hidden_dimensions[0], input_dim=input_dim, kernel_initializer='normal', activation='relu'))\n # add multiple hidden layers\n for dimension in hidden_dimensions[1:]:\n model.add(Dense(dimension, kernel_initializer='normal', activation='relu'))\n model.add(Dense(4, kernel_initializer='normal', activation='sigmoid'))\n # Compile model. We use the the logarithmic loss function, and the Adam gradient optimizer.\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model",
"_____no_output_____"
],
[
"# add some more hidden layers to learn more\npreprocessing = Pipeline([\n (\"scale\", StandardScaler()),\n])\n\npipeline = Pipeline([\n (\"preprocessing\", preprocessing),\n (\"classifier\", KerasClassifier(build_fn=network_builder, epochs=10, batch_size=128, \n verbose=1, hidden_dimensions=(60,30,10), input_dim=74))\n])\n\ncross_val_score(pipeline, X, binarized_y)",
"Epoch 1/10\n892937/892937 [==============================] - 24s 26us/step - loss: 0.0457 - acc: 0.9860\nEpoch 2/10\n892937/892937 [==============================] - 21s 24us/step - loss: 0.0113 - acc: 0.9967\nEpoch 3/10\n892937/892937 [==============================] - 21s 23us/step - loss: 0.0079 - acc: 0.9977\nEpoch 4/10\n892937/892937 [==============================] - 26s 29us/step - loss: 0.0066 - acc: 0.9982\nEpoch 5/10\n892937/892937 [==============================] - 24s 27us/step - loss: 0.0061 - acc: 0.9983\nEpoch 6/10\n892937/892937 [==============================] - 25s 28us/step - loss: 0.0057 - acc: 0.9984 \nEpoch 7/10\n892937/892937 [==============================] - 24s 27us/step - loss: 0.0051 - acc: 0.9985\nEpoch 8/10\n892937/892937 [==============================] - 24s 27us/step - loss: 0.0050 - acc: 0.9986\nEpoch 9/10\n892937/892937 [==============================] - 25s 28us/step - loss: 0.0046 - acc: 0.9986\nEpoch 10/10\n892937/892937 [==============================] - 23s 26us/step - loss: 0.0044 - acc: 0.9987\n446469/446469 [==============================] - 6s 12us/step\nEpoch 1/10\n892937/892937 [==============================] - 27s 30us/step - loss: 0.0538 - acc: 0.9826\nEpoch 2/10\n892937/892937 [==============================] - 24s 27us/step - loss: 0.0113 - acc: 0.9967\nEpoch 3/10\n892937/892937 [==============================] - 21s 23us/step - loss: 0.0081 - acc: 0.9976\nEpoch 4/10\n892937/892937 [==============================] - 22s 25us/step - loss: 0.0066 - acc: 0.9981\nEpoch 5/10\n892937/892937 [==============================] - 22s 24us/step - loss: 0.0057 - acc: 0.9984\nEpoch 6/10\n892937/892937 [==============================] - 27s 30us/step - loss: 0.0052 - acc: 0.9985\nEpoch 7/10\n892937/892937 [==============================] - 23s 26us/step - loss: 0.0047 - acc: 0.9987\nEpoch 8/10\n892937/892937 [==============================] - 21s 24us/step - loss: 0.0045 - acc: 0.9987 - ETA: 1s\nEpoch 9/10\n892937/892937 [==============================] - 22s 25us/step - loss: 0.0043 - acc: 0.9987\nEpoch 10/10\n892937/892937 [==============================] - 22s 24us/step - loss: 0.0041 - acc: 0.9988\n446469/446469 [==============================] - 7s 15us/step\nEpoch 1/10\n892938/892938 [==============================] - 28s 31us/step - loss: 0.0416 - acc: 0.9909\nEpoch 2/10\n892938/892938 [==============================] - 24s 26us/step - loss: 0.0029 - acc: 0.9992\nEpoch 3/10\n892938/892938 [==============================] - 29s 32us/step - loss: 0.0024 - acc: 0.9993\nEpoch 4/10\n892938/892938 [==============================] - 22s 24us/step - loss: 0.0021 - acc: 0.9994\nEpoch 5/10\n892938/892938 [==============================] - 19s 22us/step - loss: 0.0018 - acc: 0.9995\nEpoch 6/10\n892938/892938 [==============================] - 19s 21us/step - loss: 0.0015 - acc: 0.9995\nEpoch 7/10\n892938/892938 [==============================] - 22s 24us/step - loss: 0.0016 - acc: 0.9995\nEpoch 8/10\n892938/892938 [==============================] - 20s 22us/step - loss: 0.0014 - acc: 0.9996\nEpoch 9/10\n892938/892938 [==============================] - 19s 22us/step - loss: 0.0013 - acc: 0.9996\nEpoch 10/10\n892938/892938 [==============================] - 19s 21us/step - loss: 0.0013 - acc: 0.9996\n446468/446468 [==============================] - 4s 10us/step\n"
],
[
"pipeline.fit(X, binarized_y)\nget_network_test_accuracy_of(pipeline)",
"Epoch 1/10\n1339406/1339406 [==============================] - 31s 23us/step - loss: 0.0422 - acc: 0.9865\nEpoch 2/10\n1339406/1339406 [==============================] - 28s 21us/step - loss: 0.0095 - acc: 0.9973\nEpoch 3/10\n1339406/1339406 [==============================] - 29s 22us/step - loss: 0.0068 - acc: 0.9981\nEpoch 4/10\n1339406/1339406 [==============================] - 28s 21us/step - loss: 0.0056 - acc: 0.9984\nEpoch 5/10\n1339406/1339406 [==============================] - 29s 21us/step - loss: 0.0051 - acc: 0.9986\nEpoch 6/10\n1339406/1339406 [==============================] - 28s 21us/step - loss: 0.0047 - acc: 0.9987\nEpoch 7/10\n1339406/1339406 [==============================] - 30s 22us/step - loss: 0.0041 - acc: 0.9988 0s - loss: 0.0041 - acc: 0.99 - ETA: 0s - loss: 0.0041 - acc: 0.998 - ETA: 0s - loss: 0.0041 - acc: 0\nEpoch 8/10\n1339406/1339406 [==============================] - 29s 22us/step - loss: 0.0039 - acc: 0.9989\nEpoch 9/10\n1339406/1339406 [==============================] - 29s 22us/step - loss: 0.0039 - acc: 0.9989\nEpoch 10/10\n1339406/1339406 [==============================] - 28s 21us/step - loss: 0.0036 - acc: 0.9990 0s - loss: 0.0036 - acc: \n389185/389185 [==============================] - 3s 9us/step\n"
],
[
"# we got small bump by increasing hidden layers",
"_____no_output_____"
],
[
"# add some more hidden layers to learn more\npreprocessing = Pipeline([\n (\"scale\", StandardScaler()),\n])\n\npipeline = Pipeline([\n (\"preprocessing\", preprocessing),\n (\"classifier\", KerasClassifier(build_fn=network_builder, epochs=10, batch_size=128, \n verbose=1, hidden_dimensions=(30,30,30,10), input_dim=74))\n])\n\ncross_val_score(pipeline, X, binarized_y)",
"Epoch 1/10\n892937/892937 [==============================] - 25s 28us/step - loss: 0.0671 - acc: 0.9709\nEpoch 2/10\n892937/892937 [==============================] - 21s 23us/step - loss: 0.0139 - acc: 0.9963\nEpoch 3/10\n892937/892937 [==============================] - 20s 22us/step - loss: 0.0100 - acc: 0.9973\nEpoch 4/10\n892937/892937 [==============================] - 25s 28us/step - loss: 0.0087 - acc: 0.9977\nEpoch 5/10\n892937/892937 [==============================] - 21s 24us/step - loss: 0.0078 - acc: 0.9979\nEpoch 6/10\n892937/892937 [==============================] - 21s 24us/step - loss: 0.0072 - acc: 0.9981\nEpoch 7/10\n892937/892937 [==============================] - 24s 27us/step - loss: 0.0069 - acc: 0.9982\nEpoch 8/10\n892937/892937 [==============================] - 24s 27us/step - loss: 0.0064 - acc: 0.9984\nEpoch 9/10\n892937/892937 [==============================] - 25s 28us/step - loss: 0.0060 - acc: 0.9984\nEpoch 10/10\n892937/892937 [==============================] - 22s 25us/step - loss: 0.0059 - acc: 0.9985\n446469/446469 [==============================] - 5s 11us/step\nEpoch 1/10\n892937/892937 [==============================] - 26s 29us/step - loss: 0.1102 - acc: 0.9298\nEpoch 2/10\n892937/892937 [==============================] - 24s 27us/step - loss: 0.0549 - acc: 0.9447\nEpoch 3/10\n892937/892937 [==============================] - 22s 24us/step - loss: 0.0456 - acc: 0.9494\nEpoch 4/10\n892937/892937 [==============================] - 22s 24us/step - loss: 0.0354 - acc: 0.9606\nEpoch 5/10\n892937/892937 [==============================] - 21s 23us/step - loss: 0.0342 - acc: 0.9609\nEpoch 6/10\n892937/892937 [==============================] - 20s 23us/step - loss: 0.0333 - acc: 0.9611\nEpoch 7/10\n892937/892937 [==============================] - 21s 23us/step - loss: 0.0329 - acc: 0.9613 1s\nEpoch 8/10\n892937/892937 [==============================] - 20s 23us/step - loss: 0.0256 - acc: 0.9720\nEpoch 9/10\n892937/892937 [==============================] - 20s 23us/step - loss: 0.0061 - acc: 0.9984 1s - loss: 0.0062 - acc: - ETA: 0s - loss: 0.006\nEpoch 10/10\n892937/892937 [==============================] - 21s 24us/step - loss: 0.0058 - acc: 0.9984 0s - loss: 0.0058 - acc: 0.998\n446469/446469 [==============================] - 5s 12us/step\nEpoch 1/10\n892938/892938 [==============================] - 26s 29us/step - loss: 0.0255 - acc: 0.9952\nEpoch 2/10\n892938/892938 [==============================] - 24s 27us/step - loss: 0.0031 - acc: 0.9992\nEpoch 3/10\n892938/892938 [==============================] - 20s 23us/step - loss: 0.0025 - acc: 0.9994\nEpoch 4/10\n892938/892938 [==============================] - 21s 23us/step - loss: 0.0022 - acc: 0.9995\nEpoch 5/10\n892938/892938 [==============================] - 21s 24us/step - loss: 0.0019 - acc: 0.9995 1s - loss:\nEpoch 6/10\n892938/892938 [==============================] - 21s 24us/step - loss: 0.0019 - acc: 0.9995 1s - loss\nEpoch 7/10\n892938/892938 [==============================] - 21s 24us/step - loss: 0.0017 - acc: 0.9995\nEpoch 8/10\n892938/892938 [==============================] - 21s 23us/step - loss: 0.0016 - acc: 0.9995\nEpoch 9/10\n892938/892938 [==============================] - 20s 23us/step - loss: 0.0014 - acc: 0.9996\nEpoch 10/10\n892938/892938 [==============================] - 21s 24us/step - loss: 0.0013 - acc: 0.9996\n446468/446468 [==============================] - 5s 12us/step\n"
],
[
"pipeline.fit(X, binarized_y)\nget_network_test_accuracy_of(pipeline)",
"Epoch 1/10\n1339406/1339406 [==============================] - 48s 36us/step - loss: 0.0666 - acc: 0.9548\nEpoch 2/10\n1339406/1339406 [==============================] - 108s 81us/step - loss: 0.0346 - acc: 0.9663\nEpoch 3/10\n1339406/1339406 [==============================] - 78s 59us/step - loss: 0.0261 - acc: 0.9732\nEpoch 4/10\n1339406/1339406 [==============================] - 102s 76us/step - loss: 0.0075 - acc: 0.9980\nEpoch 5/10\n1339406/1339406 [==============================] - 71s 53us/step - loss: 0.0066 - acc: 0.9983\nEpoch 6/10\n1339406/1339406 [==============================] - 111s 83us/step - loss: 0.0059 - acc: 0.9985\nEpoch 7/10\n1339406/1339406 [==============================] - 98s 73us/step - loss: 0.0055 - acc: 0.9986\nEpoch 8/10\n1339406/1339406 [==============================] - 93s 70us/step - loss: 0.0052 - acc: 0.9987\nEpoch 9/10\n1339406/1339406 [==============================] - 88s 66us/step - loss: 0.0051 - acc: 0.9988\nEpoch 10/10\n1339406/1339406 [==============================] - 87s 65us/step - loss: 0.0049 - acc: 0.9988\n389185/389185 [==============================] - 16s 41us/step\n"
],
[
"# best so far using deep learning",
"_____no_output_____"
],
[
"# deep learning isn't best for all data sets.",
"_____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",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7218b34da4c38a925cd74b0bbb5a36358843754 | 187,298 | ipynb | Jupyter Notebook | Regression/Support Vector Machine/NuSVR_StandardScaler.ipynb | shreepad-nade/ds-seed | 93ddd3b73541f436b6832b94ca09f50872dfaf10 | [
"Apache-2.0"
] | 53 | 2021-08-28T07:41:49.000Z | 2022-03-09T02:20:17.000Z | Regression/Support Vector Machine/NuSVR_StandardScaler.ipynb | shreepad-nade/ds-seed | 93ddd3b73541f436b6832b94ca09f50872dfaf10 | [
"Apache-2.0"
] | 142 | 2021-07-27T07:23:10.000Z | 2021-08-25T14:57:24.000Z | Regression/Support Vector Machine/NuSVR_StandardScaler.ipynb | shreepad-nade/ds-seed | 93ddd3b73541f436b6832b94ca09f50872dfaf10 | [
"Apache-2.0"
] | 38 | 2021-07-27T04:54:08.000Z | 2021-08-23T02:27:20.000Z | 319.62116 | 83,758 | 0.806287 | [
[
[
"# Nu-Support Vector Regression with StandardScaler",
"_____no_output_____"
],
[
"This Code template is for regression analysis using a Nu-Support Vector Regressor(NuSVR) based on the Support Vector Machine algorithm and feature rescaling technique StandardScaler in a pipeline. ",
"_____no_output_____"
],
[
"### Required Packages",
"_____no_output_____"
]
],
[
[
"import warnings \r\nimport numpy as np \r\nimport pandas as pd \r\nimport matplotlib.pyplot as plt\r\nimport seaborn as se \r\nfrom sklearn.pipeline import make_pipeline\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.model_selection import train_test_split \r\nfrom sklearn.svm import NuSVR \r\nfrom sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error\r\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
]
],
[
[
"### Initialization\n\nFilepath of CSV file",
"_____no_output_____"
]
],
[
[
"file_path= \"\"",
"_____no_output_____"
]
],
[
[
"List of features which are required for model training .",
"_____no_output_____"
]
],
[
[
"features =[]",
"_____no_output_____"
]
],
[
[
"Target feature for prediction.",
"_____no_output_____"
]
],
[
[
"target=''",
"_____no_output_____"
]
],
[
[
"### Data Fetching\nPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.\n\nWe will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry.",
"_____no_output_____"
]
],
[
[
"df=pd.read_csv(file_path)\ndf.head()",
"_____no_output_____"
]
],
[
[
"### Feature Selections\n\nIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.\n\nWe will assign all the required input features to X and target/outcome to Y.",
"_____no_output_____"
]
],
[
[
"X=df[features]\nY=df[target]",
"_____no_output_____"
]
],
[
[
"### Data Preprocessing\n\nSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes.\n",
"_____no_output_____"
]
],
[
[
"def NullClearner(df):\n if(isinstance(df, pd.Series) and (df.dtype in [\"float64\",\"int64\"])):\n df.fillna(df.mean(),inplace=True)\n return df\n elif(isinstance(df, pd.Series)):\n df.fillna(df.mode()[0],inplace=True)\n return df\n else:return df\ndef EncodeX(df):\n return pd.get_dummies(df)",
"_____no_output_____"
]
],
[
[
"Calling preprocessing functions on the feature and target set.\n",
"_____no_output_____"
]
],
[
[
"x=X.columns.to_list()\nfor i in x:\n X[i]=NullClearner(X[i])\nY=NullClearner(Y)\nX=EncodeX(X)\nX.head()",
"_____no_output_____"
]
],
[
[
"#### Correlation Map\n\nIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns.",
"_____no_output_____"
]
],
[
[
"f,ax = plt.subplots(figsize=(18, 18))\nmatrix = np.triu(X.corr())\nse.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Data Splitting\n\nThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of the model on new data.",
"_____no_output_____"
]
],
[
[
"X_train,X_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123)",
"_____no_output_____"
]
],
[
[
"### Model\nSupport vector machines (SVMs) are a set of supervised learning methods used for classification, regression and outliers detection.\n\nA Support Vector Machine is a discriminative classifier formally defined by a separating hyperplane. In other terms, for a given known/labelled data points, the SVM outputs an appropriate hyperplane that classifies the inputted new cases based on the hyperplane. In 2-Dimensional space, this hyperplane is a line separating a plane into two segments where each class or group occupied on either side.\n\nHere we will use NuSVR, the NuSVR implementation is based on libsvm. Similar to NuSVC, for regression, uses a parameter nu to control the number of support vectors. However, unlike NuSVC, where nu replaces C, here nu replaces the parameter epsilon of epsilon-SVR. \n#### Model Tuning Parameters\n\n 1. nu : float, default=0.5\n> An upper bound on the fraction of training errors and a lower bound of the fraction of support vectors. Should be in the interval (0, 1]. By default 0.5 will be taken.\n\n 2. C : float, default=1.0\n> Regularization parameter. The strength of the regularization is inversely proportional to C. Must be strictly positive. The penalty is a squared l2 penalty.\n\n 3. kernel : {‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’}, default=’rbf’\n> Specifies the kernel type to be used in the algorithm. It must be one of ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ or a callable. If none is given, ‘rbf’ will be used. If a callable is given it is used to pre-compute the kernel matrix from data matrices; that matrix should be an array of shape (n_samples, n_samples).\n\n 4. gamma : {‘scale’, ‘auto’} or float, default=’scale’\n> Gamma is a hyperparameter that we have to set before the training model. Gamma decides how much curvature we want in a decision boundary.\n\n 5. degree : int, default=3\n> Degree of the polynomial kernel function (‘poly’). Ignored by all other kernels.Using degree 1 is similar to using a linear kernel. Also, increasing degree parameter leads to higher training times.",
"_____no_output_____"
]
],
[
[
"model=make_pipeline(StandardScaler(),NuSVR())\nmodel.fit(X_train,y_train)",
"_____no_output_____"
]
],
[
[
"#### Model Accuracy\n\nWe will use the trained model to make a prediction on the test set.Then use the predicted value for measuring the accuracy of our model.\n\n> **score**: The **score** function returns the coefficient of determination <code>R<sup>2</sup></code> of the prediction.",
"_____no_output_____"
]
],
[
[
"print(\"Accuracy score {:.2f} %\\n\".format(model.score(X_test,y_test)*100))",
"Accuracy score 93.62 %\n\n"
]
],
[
[
"> **r2_score**: The **r2_score** function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions. \n\n> **mae**: The **mean abosolute error** function calculates the amount of total error(absolute average distance between the real data and the predicted data) by our model. \n\n> **mse**: The **mean squared error** function squares the error(penalizes the model for large errors) by our model. ",
"_____no_output_____"
]
],
[
[
"y_pred=model.predict(X_test)\nprint(\"R2 Score: {:.2f} %\".format(r2_score(y_test,y_pred)*100))\nprint(\"Mean Absolute Error {:.2f}\".format(mean_absolute_error(y_test,y_pred)))\nprint(\"Mean Squared Error {:.2f}\".format(mean_squared_error(y_test,y_pred)))",
"R2 Score: 93.62 %\nMean Absolute Error 3.29\nMean Squared Error 18.47\n"
]
],
[
[
"#### Prediction Plot\n\nFirst, we make use of a scatter plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis.\nFor the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(14,10))\nplt.plot(range(20),y_test[0:20], color = \"green\")\nplt.plot(range(20),model.predict(X_test[0:20]), color = \"red\")\nplt.legend([\"Actual\", \"prediction\"]) \nplt.title(\"Predicted vs True Value\")\nplt.xlabel(\"Record number\")\nplt.ylabel(target)\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### Creator: Thilakraj Devadiga , Github: [Profile](https://github.com/Thilakraj1998)\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"
] | [
[
"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"
]
] |
e72192a9f4c4402867f60515fd29bafebc88ef98 | 118,819 | ipynb | Jupyter Notebook | 4_POS_Tagging.ipynb | sushangautam/Natural-Language-Processing-Practice | 21eca69faa3c5145963daf07e518a9a99106d965 | [
"MIT"
] | null | null | null | 4_POS_Tagging.ipynb | sushangautam/Natural-Language-Processing-Practice | 21eca69faa3c5145963daf07e518a9a99106d965 | [
"MIT"
] | null | null | null | 4_POS_Tagging.ipynb | sushangautam/Natural-Language-Processing-Practice | 21eca69faa3c5145963daf07e518a9a99106d965 | [
"MIT"
] | null | null | null | 221.677239 | 894 | 0.35937 | [
[
[
"import nltk\nnltk.download('state_union')\nnltk.download('punkt')\nnltk.download('averaged_perceptron_tagger')\nfrom nltk.corpus import state_union\nfrom nltk.tokenize import PunktSentenceTokenizer",
"[nltk_data] Downloading package state_union to /root/nltk_data...\n[nltk_data] Package state_union is already up-to-date!\n[nltk_data] Downloading package punkt to /root/nltk_data...\n[nltk_data] Package punkt is already up-to-date!\n[nltk_data] Downloading package averaged_perceptron_tagger to\n[nltk_data] /root/nltk_data...\n[nltk_data] Unzipping taggers/averaged_perceptron_tagger.zip.\n"
],
[
"state_union.fileids()\n",
"_____no_output_____"
],
[
"train_text=state_union.raw(\"1993-Clinton.txt\")\nsample_text=state_union.raw(\"2006-GWBush.txt\")\ncustom_sent_tokenizer=PunktSentenceTokenizer(train_text)\ntokenized=custom_sent_tokenizer.tokenize(sample_text)\ndef process_content():\n try:\n for i in tokenized:\n words=nltk.word_tokenize(i)\n tagged=nltk.pos_tag(words)\n print(tagged)\n except Exception as e:\n print(str(e))\n \nprocess_content()",
"[('PRESIDENT', 'NNP'), ('GEORGE', 'NNP'), ('W.', 'NNP'), ('BUSH', 'NNP'), (\"'S\", 'POS'), ('ADDRESS', 'NNP'), ('BEFORE', 'IN'), ('A', 'NNP'), ('JOINT', 'NNP'), ('SESSION', 'NNP'), ('OF', 'IN'), ('THE', 'NNP'), ('CONGRESS', 'NNP'), ('ON', 'NNP'), ('THE', 'NNP'), ('STATE', 'NNP'), ('OF', 'IN'), ('THE', 'NNP'), ('UNION', 'NNP'), ('January', 'NNP'), ('31', 'CD'), (',', ','), ('2006', 'CD'), ('THE', 'NNP'), ('PRESIDENT', 'NNP'), (':', ':'), ('Thank', 'NNP'), ('you', 'PRP'), ('all', 'DT'), ('.', '.')]\n[('Mr.', 'NNP'), ('Speaker', 'NNP'), (',', ','), ('Vice', 'NNP'), ('President', 'NNP'), ('Cheney', 'NNP'), (',', ','), ('members', 'NNS'), ('of', 'IN'), ('Congress', 'NNP'), (',', ','), ('members', 'NNS'), ('of', 'IN'), ('the', 'DT'), ('Supreme', 'NNP'), ('Court', 'NNP'), ('and', 'CC'), ('diplomatic', 'JJ'), ('corps', 'NN'), (',', ','), ('distinguished', 'JJ'), ('guests', 'NNS'), (',', ','), ('and', 'CC'), ('fellow', 'JJ'), ('citizens', 'NNS'), (':', ':'), ('Today', 'VB'), ('our', 'PRP$'), ('nation', 'NN'), ('lost', 'VBD'), ('a', 'DT'), ('beloved', 'VBN'), (',', ','), ('graceful', 'JJ'), (',', ','), ('courageous', 'JJ'), ('woman', 'NN'), ('who', 'WP'), ('called', 'VBD'), ('America', 'NNP'), ('to', 'TO'), ('its', 'PRP$'), ('founding', 'NN'), ('ideals', 'NNS'), ('and', 'CC'), ('carried', 'VBD'), ('on', 'IN'), ('a', 'DT'), ('noble', 'JJ'), ('dream', 'NN'), ('.', '.')]\n[('Tonight', 'NN'), ('we', 'PRP'), ('are', 'VBP'), ('comforted', 'VBN'), ('by', 'IN'), ('the', 'DT'), ('hope', 'NN'), ('of', 'IN'), ('a', 'DT'), ('glad', 'JJ'), ('reunion', 'NN'), ('with', 'IN'), ('the', 'DT'), ('husband', 'NN'), ('who', 'WP'), ('was', 'VBD'), ('taken', 'VBN'), ('so', 'RB'), ('long', 'RB'), ('ago', 'RB'), (',', ','), ('and', 'CC'), ('we', 'PRP'), ('are', 'VBP'), ('grateful', 'JJ'), ('for', 'IN'), ('the', 'DT'), ('good', 'JJ'), ('life', 'NN'), ('of', 'IN'), ('Coretta', 'NNP'), ('Scott', 'NNP'), ('King', 'NNP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('President', 'NNP'), ('George', 'NNP'), ('W.', 'NNP'), ('Bush', 'NNP'), ('reacts', 'VBZ'), ('to', 'TO'), ('applause', 'VB'), ('during', 'IN'), ('his', 'PRP$'), ('State', 'NNP'), ('of', 'IN'), ('the', 'DT'), ('Union', 'NNP'), ('Address', 'NNP'), ('at', 'IN'), ('the', 'DT'), ('Capitol', 'NNP'), (',', ','), ('Tuesday', 'NNP'), (',', ','), ('Jan', 'NNP'), ('.', '.')]\n[('31', 'CD'), (',', ','), ('2006', 'CD'), ('.', '.')]\n[('White', 'NNP'), ('House', 'NNP'), ('photo', 'NN'), ('by', 'IN'), ('Eric', 'NNP'), ('DraperEvery', 'NNP'), ('time', 'NN'), ('I', 'PRP'), (\"'m\", 'VBP'), ('invited', 'JJ'), ('to', 'TO'), ('this', 'DT'), ('rostrum', 'NN'), (',', ','), ('I', 'PRP'), (\"'m\", 'VBP'), ('humbled', 'VBN'), ('by', 'IN'), ('the', 'DT'), ('privilege', 'NN'), (',', ','), ('and', 'CC'), ('mindful', 'NN'), ('of', 'IN'), ('the', 'DT'), ('history', 'NN'), ('we', 'PRP'), (\"'ve\", 'VBP'), ('seen', 'VBN'), ('together', 'RB'), ('.', '.')]\n[('We', 'PRP'), ('have', 'VBP'), ('gathered', 'VBN'), ('under', 'IN'), ('this', 'DT'), ('Capitol', 'NNP'), ('dome', 'NN'), ('in', 'IN'), ('moments', 'NNS'), ('of', 'IN'), ('national', 'JJ'), ('mourning', 'NN'), ('and', 'CC'), ('national', 'JJ'), ('achievement', 'NN'), ('.', '.')]\n[('We', 'PRP'), ('have', 'VBP'), ('served', 'VBN'), ('America', 'NNP'), ('through', 'IN'), ('one', 'CD'), ('of', 'IN'), ('the', 'DT'), ('most', 'RBS'), ('consequential', 'JJ'), ('periods', 'NNS'), ('of', 'IN'), ('our', 'PRP$'), ('history', 'NN'), ('--', ':'), ('and', 'CC'), ('it', 'PRP'), ('has', 'VBZ'), ('been', 'VBN'), ('my', 'PRP$'), ('honor', 'NN'), ('to', 'TO'), ('serve', 'VB'), ('with', 'IN'), ('you', 'PRP'), ('.', '.')]\n[('In', 'IN'), ('a', 'DT'), ('system', 'NN'), ('of', 'IN'), ('two', 'CD'), ('parties', 'NNS'), (',', ','), ('two', 'CD'), ('chambers', 'NNS'), (',', ','), ('and', 'CC'), ('two', 'CD'), ('elected', 'JJ'), ('branches', 'NNS'), (',', ','), ('there', 'EX'), ('will', 'MD'), ('always', 'RB'), ('be', 'VB'), ('differences', 'NNS'), ('and', 'CC'), ('debate', 'NN'), ('.', '.')]\n[('But', 'CC'), ('even', 'RB'), ('tough', 'JJ'), ('debates', 'NNS'), ('can', 'MD'), ('be', 'VB'), ('conducted', 'VBN'), ('in', 'IN'), ('a', 'DT'), ('civil', 'JJ'), ('tone', 'NN'), (',', ','), ('and', 'CC'), ('our', 'PRP$'), ('differences', 'NNS'), ('can', 'MD'), ('not', 'RB'), ('be', 'VB'), ('allowed', 'VBN'), ('to', 'TO'), ('harden', 'VB'), ('into', 'IN'), ('anger', 'NN'), ('.', '.')]\n[('To', 'TO'), ('confront', 'VB'), ('the', 'DT'), ('great', 'JJ'), ('issues', 'NNS'), ('before', 'IN'), ('us', 'PRP'), (',', ','), ('we', 'PRP'), ('must', 'MD'), ('act', 'VB'), ('in', 'IN'), ('a', 'DT'), ('spirit', 'NN'), ('of', 'IN'), ('goodwill', 'NN'), ('and', 'CC'), ('respect', 'NN'), ('for', 'IN'), ('one', 'CD'), ('another', 'DT'), ('--', ':'), ('and', 'CC'), ('I', 'PRP'), ('will', 'MD'), ('do', 'VB'), ('my', 'PRP$'), ('part', 'NN'), ('.', '.')]\n[('Tonight', 'NNP'), ('the', 'DT'), ('state', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('Union', 'NNP'), ('is', 'VBZ'), ('strong', 'JJ'), ('--', ':'), ('and', 'CC'), ('together', 'RB'), ('we', 'PRP'), ('will', 'MD'), ('make', 'VB'), ('it', 'PRP'), ('stronger', 'JJR'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('In', 'IN'), ('this', 'DT'), ('decisive', 'JJ'), ('year', 'NN'), (',', ','), ('you', 'PRP'), ('and', 'CC'), ('I', 'PRP'), ('will', 'MD'), ('make', 'VB'), ('choices', 'NNS'), ('that', 'WDT'), ('determine', 'VBP'), ('both', 'DT'), ('the', 'DT'), ('future', 'NN'), ('and', 'CC'), ('the', 'DT'), ('character', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('country', 'NN'), ('.', '.')]\n[('We', 'PRP'), ('will', 'MD'), ('choose', 'VB'), ('to', 'TO'), ('act', 'VB'), ('confidently', 'RB'), ('in', 'IN'), ('pursuing', 'VBG'), ('the', 'DT'), ('enemies', 'NNS'), ('of', 'IN'), ('freedom', 'NN'), ('--', ':'), ('or', 'CC'), ('retreat', 'NN'), ('from', 'IN'), ('our', 'PRP$'), ('duties', 'NNS'), ('in', 'IN'), ('the', 'DT'), ('hope', 'NN'), ('of', 'IN'), ('an', 'DT'), ('easier', 'JJR'), ('life', 'NN'), ('.', '.')]\n[('We', 'PRP'), ('will', 'MD'), ('choose', 'VB'), ('to', 'TO'), ('build', 'VB'), ('our', 'PRP$'), ('prosperity', 'NN'), ('by', 'IN'), ('leading', 'VBG'), ('the', 'DT'), ('world', 'NN'), ('economy', 'NN'), ('--', ':'), ('or', 'CC'), ('shut', 'VB'), ('ourselves', 'PRP'), ('off', 'RP'), ('from', 'IN'), ('trade', 'NN'), ('and', 'CC'), ('opportunity', 'NN'), ('.', '.')]\n[('In', 'IN'), ('a', 'DT'), ('complex', 'JJ'), ('and', 'CC'), ('challenging', 'JJ'), ('time', 'NN'), (',', ','), ('the', 'DT'), ('road', 'NN'), ('of', 'IN'), ('isolationism', 'NN'), ('and', 'CC'), ('protectionism', 'NN'), ('may', 'MD'), ('seem', 'VB'), ('broad', 'JJ'), ('and', 'CC'), ('inviting', 'NN'), ('--', ':'), ('yet', 'CC'), ('it', 'PRP'), ('ends', 'VBZ'), ('in', 'IN'), ('danger', 'NN'), ('and', 'CC'), ('decline', 'NN'), ('.', '.')]\n[('The', 'DT'), ('only', 'JJ'), ('way', 'NN'), ('to', 'TO'), ('protect', 'VB'), ('our', 'PRP$'), ('people', 'NNS'), (',', ','), ('the', 'DT'), ('only', 'JJ'), ('way', 'NN'), ('to', 'TO'), ('secure', 'VB'), ('the', 'DT'), ('peace', 'NN'), (',', ','), ('the', 'DT'), ('only', 'JJ'), ('way', 'NN'), ('to', 'TO'), ('control', 'VB'), ('our', 'PRP$'), ('destiny', 'NN'), ('is', 'VBZ'), ('by', 'IN'), ('our', 'PRP$'), ('leadership', 'NN'), ('--', ':'), ('so', 'IN'), ('the', 'DT'), ('United', 'NNP'), ('States', 'NNPS'), ('of', 'IN'), ('America', 'NNP'), ('will', 'MD'), ('continue', 'VB'), ('to', 'TO'), ('lead', 'VB'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Abroad', 'RB'), (',', ','), ('our', 'PRP$'), ('nation', 'NN'), ('is', 'VBZ'), ('committed', 'VBN'), ('to', 'TO'), ('an', 'DT'), ('historic', 'JJ'), (',', ','), ('long-term', 'JJ'), ('goal', 'NN'), ('--', ':'), ('we', 'PRP'), ('seek', 'VBP'), ('the', 'DT'), ('end', 'NN'), ('of', 'IN'), ('tyranny', 'NN'), ('in', 'IN'), ('our', 'PRP$'), ('world', 'NN'), ('.', '.')]\n[('Some', 'DT'), ('dismiss', 'VBP'), ('that', 'DT'), ('goal', 'NN'), ('as', 'IN'), ('misguided', 'JJ'), ('idealism', 'NN'), ('.', '.')]\n[('In', 'IN'), ('reality', 'NN'), (',', ','), ('the', 'DT'), ('future', 'JJ'), ('security', 'NN'), ('of', 'IN'), ('America', 'NNP'), ('depends', 'VBZ'), ('on', 'IN'), ('it', 'PRP'), ('.', '.')]\n[('On', 'IN'), ('September', 'NNP'), ('the', 'DT'), ('11th', 'CD'), (',', ','), ('2001', 'CD'), (',', ','), ('we', 'PRP'), ('found', 'VBD'), ('that', 'IN'), ('problems', 'NNS'), ('originating', 'VBG'), ('in', 'IN'), ('a', 'DT'), ('failed', 'JJ'), ('and', 'CC'), ('oppressive', 'JJ'), ('state', 'NN'), ('7,000', 'CD'), ('miles', 'NNS'), ('away', 'RB'), ('could', 'MD'), ('bring', 'VB'), ('murder', 'NN'), ('and', 'CC'), ('destruction', 'NN'), ('to', 'TO'), ('our', 'PRP$'), ('country', 'NN'), ('.', '.')]\n[('Dictatorships', 'NNP'), ('shelter', 'NN'), ('terrorists', 'NNS'), (',', ','), ('and', 'CC'), ('feed', 'VB'), ('resentment', 'NN'), ('and', 'CC'), ('radicalism', 'NN'), (',', ','), ('and', 'CC'), ('seek', 'JJ'), ('weapons', 'NNS'), ('of', 'IN'), ('mass', 'NN'), ('destruction', 'NN'), ('.', '.')]\n[('Democracies', 'NNS'), ('replace', 'VB'), ('resentment', 'NN'), ('with', 'IN'), ('hope', 'NN'), (',', ','), ('respect', 'VB'), ('the', 'DT'), ('rights', 'NNS'), ('of', 'IN'), ('their', 'PRP$'), ('citizens', 'NNS'), ('and', 'CC'), ('their', 'PRP$'), ('neighbors', 'NNS'), (',', ','), ('and', 'CC'), ('join', 'VB'), ('the', 'DT'), ('fight', 'NN'), ('against', 'IN'), ('terror', 'NN'), ('.', '.')]\n[('Every', 'DT'), ('step', 'NN'), ('toward', 'IN'), ('freedom', 'NN'), ('in', 'IN'), ('the', 'DT'), ('world', 'NN'), ('makes', 'VBZ'), ('our', 'PRP$'), ('country', 'NN'), ('safer', 'NN'), ('--', ':'), ('so', 'IN'), ('we', 'PRP'), ('will', 'MD'), ('act', 'VB'), ('boldly', 'RB'), ('in', 'IN'), ('freedom', 'NN'), (\"'s\", 'POS'), ('cause', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Far', 'RB'), ('from', 'IN'), ('being', 'VBG'), ('a', 'DT'), ('hopeless', 'NN'), ('dream', 'NN'), (',', ','), ('the', 'DT'), ('advance', 'NN'), ('of', 'IN'), ('freedom', 'NN'), ('is', 'VBZ'), ('the', 'DT'), ('great', 'JJ'), ('story', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('time', 'NN'), ('.', '.')]\n[('In', 'IN'), ('1945', 'CD'), (',', ','), ('there', 'EX'), ('were', 'VBD'), ('about', 'RB'), ('two', 'CD'), ('dozen', 'NN'), ('lonely', 'RB'), ('democracies', 'VBZ'), ('in', 'IN'), ('the', 'DT'), ('world', 'NN'), ('.', '.')]\n[('Today', 'NN'), (',', ','), ('there', 'EX'), ('are', 'VBP'), ('122', 'CD'), ('.', '.')]\n[('And', 'CC'), ('we', 'PRP'), (\"'re\", 'VBP'), ('writing', 'VBG'), ('a', 'DT'), ('new', 'JJ'), ('chapter', 'NN'), ('in', 'IN'), ('the', 'DT'), ('story', 'NN'), ('of', 'IN'), ('self-government', 'JJ'), ('--', ':'), ('with', 'IN'), ('women', 'NNS'), ('lining', 'VBG'), ('up', 'RP'), ('to', 'TO'), ('vote', 'VB'), ('in', 'IN'), ('Afghanistan', 'NNP'), (',', ','), ('and', 'CC'), ('millions', 'NNS'), ('of', 'IN'), ('Iraqis', 'NNP'), ('marking', 'VBG'), ('their', 'PRP$'), ('liberty', 'NN'), ('with', 'IN'), ('purple', 'JJ'), ('ink', 'NN'), (',', ','), ('and', 'CC'), ('men', 'NNS'), ('and', 'CC'), ('women', 'NNS'), ('from', 'IN'), ('Lebanon', 'NNP'), ('to', 'TO'), ('Egypt', 'NNP'), ('debating', 'VBG'), ('the', 'DT'), ('rights', 'NNS'), ('of', 'IN'), ('individuals', 'NNS'), ('and', 'CC'), ('the', 'DT'), ('necessity', 'NN'), ('of', 'IN'), ('freedom', 'NN'), ('.', '.')]\n[('At', 'IN'), ('the', 'DT'), ('start', 'NN'), ('of', 'IN'), ('2006', 'CD'), (',', ','), ('more', 'JJR'), ('than', 'IN'), ('half', 'PDT'), ('the', 'DT'), ('people', 'NNS'), ('of', 'IN'), ('our', 'PRP$'), ('world', 'NN'), ('live', 'VBP'), ('in', 'IN'), ('democratic', 'JJ'), ('nations', 'NNS'), ('.', '.')]\n[('And', 'CC'), ('we', 'PRP'), ('do', 'VBP'), ('not', 'RB'), ('forget', 'VB'), ('the', 'DT'), ('other', 'JJ'), ('half', 'NN'), ('--', ':'), ('in', 'IN'), ('places', 'NNS'), ('like', 'IN'), ('Syria', 'NNP'), ('and', 'CC'), ('Burma', 'NNP'), (',', ','), ('Zimbabwe', 'NNP'), (',', ','), ('North', 'NNP'), ('Korea', 'NNP'), (',', ','), ('and', 'CC'), ('Iran', 'NNP'), ('--', ':'), ('because', 'IN'), ('the', 'DT'), ('demands', 'NNS'), ('of', 'IN'), ('justice', 'NN'), (',', ','), ('and', 'CC'), ('the', 'DT'), ('peace', 'NN'), ('of', 'IN'), ('this', 'DT'), ('world', 'NN'), (',', ','), ('require', 'VBP'), ('their', 'PRP$'), ('freedom', 'NN'), (',', ','), ('as', 'RB'), ('well', 'RB'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('President', 'NNP'), ('George', 'NNP'), ('W.', 'NNP'), ('Bush', 'NNP'), ('delivers', 'VBZ'), ('his', 'PRP$'), ('State', 'NN'), ('of', 'IN'), ('the', 'DT'), ('Union', 'NNP'), ('Address', 'NNP'), ('at', 'IN'), ('the', 'DT'), ('Capitol', 'NNP'), (',', ','), ('Tuesday', 'NNP'), (',', ','), ('Jan', 'NNP'), ('.', '.')]\n[('31', 'CD'), (',', ','), ('2006', 'CD'), ('.', '.')]\n[('White', 'NNP'), ('House', 'NNP'), ('photo', 'NN'), ('by', 'IN'), ('Eric', 'NNP'), ('Draper', 'NNP'), ('No', 'NNP'), ('one', 'NN'), ('can', 'MD'), ('deny', 'VB'), ('the', 'DT'), ('success', 'NN'), ('of', 'IN'), ('freedom', 'NN'), (',', ','), ('but', 'CC'), ('some', 'DT'), ('men', 'NNS'), ('rage', 'VB'), ('and', 'CC'), ('fight', 'VB'), ('against', 'IN'), ('it', 'PRP'), ('.', '.')]\n[('And', 'CC'), ('one', 'CD'), ('of', 'IN'), ('the', 'DT'), ('main', 'JJ'), ('sources', 'NNS'), ('of', 'IN'), ('reaction', 'NN'), ('and', 'CC'), ('opposition', 'NN'), ('is', 'VBZ'), ('radical', 'JJ'), ('Islam', 'NNP'), ('--', ':'), ('the', 'DT'), ('perversion', 'NN'), ('by', 'IN'), ('a', 'DT'), ('few', 'JJ'), ('of', 'IN'), ('a', 'DT'), ('noble', 'JJ'), ('faith', 'NN'), ('into', 'IN'), ('an', 'DT'), ('ideology', 'NN'), ('of', 'IN'), ('terror', 'NN'), ('and', 'CC'), ('death', 'NN'), ('.', '.')]\n[('Terrorists', 'NNS'), ('like', 'IN'), ('bin', 'NN'), ('Laden', 'NNP'), ('are', 'VBP'), ('serious', 'JJ'), ('about', 'IN'), ('mass', 'NN'), ('murder', 'NN'), ('--', ':'), ('and', 'CC'), ('all', 'DT'), ('of', 'IN'), ('us', 'PRP'), ('must', 'MD'), ('take', 'VB'), ('their', 'PRP$'), ('declared', 'JJ'), ('intentions', 'NNS'), ('seriously', 'RB'), ('.', '.')]\n[('They', 'PRP'), ('seek', 'VBP'), ('to', 'TO'), ('impose', 'VB'), ('a', 'DT'), ('heartless', 'NN'), ('system', 'NN'), ('of', 'IN'), ('totalitarian', 'JJ'), ('control', 'NN'), ('throughout', 'IN'), ('the', 'DT'), ('Middle', 'NNP'), ('East', 'NNP'), (',', ','), ('and', 'CC'), ('arm', 'NN'), ('themselves', 'PRP'), ('with', 'IN'), ('weapons', 'NNS'), ('of', 'IN'), ('mass', 'NN'), ('murder', 'NN'), ('.', '.')]\n[('Their', 'PRP$'), ('aim', 'NN'), ('is', 'VBZ'), ('to', 'TO'), ('seize', 'VB'), ('power', 'NN'), ('in', 'IN'), ('Iraq', 'NNP'), (',', ','), ('and', 'CC'), ('use', 'VB'), ('it', 'PRP'), ('as', 'IN'), ('a', 'DT'), ('safe', 'JJ'), ('haven', 'NN'), ('to', 'TO'), ('launch', 'VB'), ('attacks', 'NNS'), ('against', 'IN'), ('America', 'NNP'), ('and', 'CC'), ('the', 'DT'), ('world', 'NN'), ('.', '.')]\n[('Lacking', 'VBG'), ('the', 'DT'), ('military', 'JJ'), ('strength', 'NN'), ('to', 'TO'), ('challenge', 'VB'), ('us', 'PRP'), ('directly', 'RB'), (',', ','), ('the', 'DT'), ('terrorists', 'NNS'), ('have', 'VBP'), ('chosen', 'VBN'), ('the', 'DT'), ('weapon', 'NN'), ('of', 'IN'), ('fear', 'NN'), ('.', '.')]\n[('When', 'WRB'), ('they', 'PRP'), ('murder', 'VBP'), ('children', 'NNS'), ('at', 'IN'), ('a', 'DT'), ('school', 'NN'), ('in', 'IN'), ('Beslan', 'NNP'), (',', ','), ('or', 'CC'), ('blow', 'VB'), ('up', 'RP'), ('commuters', 'NNS'), ('in', 'IN'), ('London', 'NNP'), (',', ','), ('or', 'CC'), ('behead', 'VB'), ('a', 'DT'), ('bound', 'NN'), ('captive', 'NN'), (',', ','), ('the', 'DT'), ('terrorists', 'NNS'), ('hope', 'VBP'), ('these', 'DT'), ('horrors', 'NNS'), ('will', 'MD'), ('break', 'VB'), ('our', 'PRP$'), ('will', 'MD'), (',', ','), ('allowing', 'VBG'), ('the', 'DT'), ('violent', 'NN'), ('to', 'TO'), ('inherit', 'VB'), ('the', 'DT'), ('Earth', 'NNP'), ('.', '.')]\n[('But', 'CC'), ('they', 'PRP'), ('have', 'VBP'), ('miscalculated', 'VBN'), (':', ':'), ('We', 'PRP'), ('love', 'VBP'), ('our', 'PRP$'), ('freedom', 'NN'), (',', ','), ('and', 'CC'), ('we', 'PRP'), ('will', 'MD'), ('fight', 'VB'), ('to', 'TO'), ('keep', 'VB'), ('it', 'PRP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('In', 'IN'), ('a', 'DT'), ('time', 'NN'), ('of', 'IN'), ('testing', 'VBG'), (',', ','), ('we', 'PRP'), ('can', 'MD'), ('not', 'RB'), ('find', 'VB'), ('security', 'NN'), ('by', 'IN'), ('abandoning', 'VBG'), ('our', 'PRP$'), ('commitments', 'NNS'), ('and', 'CC'), ('retreating', 'VBG'), ('within', 'IN'), ('our', 'PRP$'), ('borders', 'NNS'), ('.', '.')]\n[('If', 'IN'), ('we', 'PRP'), ('were', 'VBD'), ('to', 'TO'), ('leave', 'VB'), ('these', 'DT'), ('vicious', 'JJ'), ('attackers', 'NNS'), ('alone', 'RB'), (',', ','), ('they', 'PRP'), ('would', 'MD'), ('not', 'RB'), ('leave', 'VB'), ('us', 'PRP'), ('alone', 'RB'), ('.', '.')]\n[('They', 'PRP'), ('would', 'MD'), ('simply', 'RB'), ('move', 'VB'), ('the', 'DT'), ('battlefield', 'NN'), ('to', 'TO'), ('our', 'PRP$'), ('own', 'JJ'), ('shores', 'NNS'), ('.', '.')]\n[('There', 'EX'), ('is', 'VBZ'), ('no', 'DT'), ('peace', 'NN'), ('in', 'IN'), ('retreat', 'NN'), ('.', '.')]\n[('And', 'CC'), ('there', 'EX'), ('is', 'VBZ'), ('no', 'DT'), ('honor', 'NN'), ('in', 'IN'), ('retreat', 'NN'), ('.', '.')]\n[('By', 'IN'), ('allowing', 'VBG'), ('radical', 'JJ'), ('Islam', 'NNP'), ('to', 'TO'), ('work', 'VB'), ('its', 'PRP$'), ('will', 'MD'), ('--', ':'), ('by', 'IN'), ('leaving', 'VBG'), ('an', 'DT'), ('assaulted', 'JJ'), ('world', 'NN'), ('to', 'TO'), ('fend', 'VB'), ('for', 'IN'), ('itself', 'PRP'), ('--', ':'), ('we', 'PRP'), ('would', 'MD'), ('signal', 'VB'), ('to', 'TO'), ('all', 'PDT'), ('that', 'IN'), ('we', 'PRP'), ('no', 'DT'), ('longer', 'RBR'), ('believe', 'VBP'), ('in', 'IN'), ('our', 'PRP$'), ('own', 'JJ'), ('ideals', 'NNS'), (',', ','), ('or', 'CC'), ('even', 'RB'), ('in', 'IN'), ('our', 'PRP$'), ('own', 'JJ'), ('courage', 'NN'), ('.', '.')]\n[('But', 'CC'), ('our', 'PRP$'), ('enemies', 'NNS'), ('and', 'CC'), ('our', 'PRP$'), ('friends', 'NNS'), ('can', 'MD'), ('be', 'VB'), ('certain', 'JJ'), (':', ':'), ('The', 'DT'), ('United', 'NNP'), ('States', 'NNPS'), ('will', 'MD'), ('not', 'RB'), ('retreat', 'VB'), ('from', 'IN'), ('the', 'DT'), ('world', 'NN'), (',', ','), ('and', 'CC'), ('we', 'PRP'), ('will', 'MD'), ('never', 'RB'), ('surrender', 'VB'), ('to', 'TO'), ('evil', 'VB'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('America', 'NNP'), ('rejects', 'VBZ'), ('the', 'DT'), ('false', 'JJ'), ('comfort', 'NN'), ('of', 'IN'), ('isolationism', 'NN'), ('.', '.')]\n[('We', 'PRP'), ('are', 'VBP'), ('the', 'DT'), ('nation', 'NN'), ('that', 'IN'), ('saved', 'VBD'), ('liberty', 'NN'), ('in', 'IN'), ('Europe', 'NNP'), (',', ','), ('and', 'CC'), ('liberated', 'VBD'), ('death', 'NN'), ('camps', 'NNS'), (',', ','), ('and', 'CC'), ('helped', 'VBD'), ('raise', 'VB'), ('up', 'RP'), ('democracies', 'NNS'), (',', ','), ('and', 'CC'), ('faced', 'VBD'), ('down', 'IN'), ('an', 'DT'), ('evil', 'JJ'), ('empire', 'NN'), ('.', '.')]\n[('Once', 'RB'), ('again', 'RB'), (',', ','), ('we', 'PRP'), ('accept', 'VBP'), ('the', 'DT'), ('call', 'NN'), ('of', 'IN'), ('history', 'NN'), ('to', 'TO'), ('deliver', 'VB'), ('the', 'DT'), ('oppressed', 'VBN'), ('and', 'CC'), ('move', 'VB'), ('this', 'DT'), ('world', 'NN'), ('toward', 'IN'), ('peace', 'NN'), ('.', '.')]\n[('We', 'PRP'), ('remain', 'VBP'), ('on', 'IN'), ('the', 'DT'), ('offensive', 'JJ'), ('against', 'IN'), ('terror', 'NN'), ('networks', 'NNS'), ('.', '.')]\n[('We', 'PRP'), ('have', 'VBP'), ('killed', 'VBN'), ('or', 'CC'), ('captured', 'VBN'), ('many', 'JJ'), ('of', 'IN'), ('their', 'PRP$'), ('leaders', 'NNS'), ('--', ':'), ('and', 'CC'), ('for', 'IN'), ('the', 'DT'), ('others', 'NNS'), (',', ','), ('their', 'PRP$'), ('day', 'NN'), ('will', 'MD'), ('come', 'VB'), ('.', '.')]\n[('President', 'NNP'), ('George', 'NNP'), ('W.', 'NNP'), ('Bush', 'NNP'), ('greets', 'VBZ'), ('members', 'NNS'), ('of', 'IN'), ('Congress', 'NNP'), ('after', 'IN'), ('his', 'PRP$'), ('State', 'NN'), ('of', 'IN'), ('the', 'DT'), ('Union', 'NNP'), ('Address', 'NNP'), ('at', 'IN'), ('the', 'DT'), ('Capitol', 'NNP'), (',', ','), ('Tuesday', 'NNP'), (',', ','), ('Jan', 'NNP'), ('.', '.')]\n[('31', 'CD'), (',', ','), ('2006', 'CD'), ('.', '.')]\n[('White', 'NNP'), ('House', 'NNP'), ('photo', 'NN'), ('by', 'IN'), ('Eric', 'NNP'), ('Draper', 'NNP'), ('We', 'PRP'), ('remain', 'VBP'), ('on', 'IN'), ('the', 'DT'), ('offensive', 'JJ'), ('in', 'IN'), ('Afghanistan', 'NNP'), (',', ','), ('where', 'WRB'), ('a', 'DT'), ('fine', 'JJ'), ('President', 'NNP'), ('and', 'CC'), ('a', 'DT'), ('National', 'NNP'), ('Assembly', 'NNP'), ('are', 'VBP'), ('fighting', 'VBG'), ('terror', 'NN'), ('while', 'IN'), ('building', 'VBG'), ('the', 'DT'), ('institutions', 'NNS'), ('of', 'IN'), ('a', 'DT'), ('new', 'JJ'), ('democracy', 'NN'), ('.', '.')]\n[('We', 'PRP'), (\"'re\", 'VBP'), ('on', 'IN'), ('the', 'DT'), ('offensive', 'JJ'), ('in', 'IN'), ('Iraq', 'NNP'), (',', ','), ('with', 'IN'), ('a', 'DT'), ('clear', 'JJ'), ('plan', 'NN'), ('for', 'IN'), ('victory', 'NN'), ('.', '.')]\n[('First', 'RB'), (',', ','), ('we', 'PRP'), (\"'re\", 'VBP'), ('helping', 'VBG'), ('Iraqis', 'NNP'), ('build', 'VB'), ('an', 'DT'), ('inclusive', 'JJ'), ('government', 'NN'), (',', ','), ('so', 'IN'), ('that', 'DT'), ('old', 'JJ'), ('resentments', 'NNS'), ('will', 'MD'), ('be', 'VB'), ('eased', 'VBN'), ('and', 'CC'), ('the', 'DT'), ('insurgency', 'NN'), ('will', 'MD'), ('be', 'VB'), ('marginalized', 'VBN'), ('.', '.')]\n[('Second', 'JJ'), (',', ','), ('we', 'PRP'), (\"'re\", 'VBP'), ('continuing', 'VBG'), ('reconstruction', 'NN'), ('efforts', 'NNS'), (',', ','), ('and', 'CC'), ('helping', 'VBG'), ('the', 'DT'), ('Iraqi', 'NNP'), ('government', 'NN'), ('to', 'TO'), ('fight', 'VB'), ('corruption', 'NN'), ('and', 'CC'), ('build', 'VB'), ('a', 'DT'), ('modern', 'JJ'), ('economy', 'NN'), (',', ','), ('so', 'IN'), ('all', 'DT'), ('Iraqis', 'NNP'), ('can', 'MD'), ('experience', 'VB'), ('the', 'DT'), ('benefits', 'NNS'), ('of', 'IN'), ('freedom', 'NN'), ('.', '.')]\n[('And', 'CC'), (',', ','), ('third', 'JJ'), (',', ','), ('we', 'PRP'), (\"'re\", 'VBP'), ('striking', 'VBG'), ('terrorist', 'JJ'), ('targets', 'NNS'), ('while', 'IN'), ('we', 'PRP'), ('train', 'VBP'), ('Iraqi', 'JJ'), ('forces', 'NNS'), ('that', 'WDT'), ('are', 'VBP'), ('increasingly', 'RB'), ('capable', 'JJ'), ('of', 'IN'), ('defeating', 'VBG'), ('the', 'DT'), ('enemy', 'NN'), ('.', '.')]\n[('Iraqis', 'NNP'), ('are', 'VBP'), ('showing', 'VBG'), ('their', 'PRP$'), ('courage', 'NN'), ('every', 'DT'), ('day', 'NN'), (',', ','), ('and', 'CC'), ('we', 'PRP'), ('are', 'VBP'), ('proud', 'JJ'), ('to', 'TO'), ('be', 'VB'), ('their', 'PRP$'), ('allies', 'NNS'), ('in', 'IN'), ('the', 'DT'), ('cause', 'NN'), ('of', 'IN'), ('freedom', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Our', 'PRP$'), ('work', 'NN'), ('in', 'IN'), ('Iraq', 'NNP'), ('is', 'VBZ'), ('difficult', 'JJ'), ('because', 'IN'), ('our', 'PRP$'), ('enemy', 'NN'), ('is', 'VBZ'), ('brutal', 'JJ'), ('.', '.')]\n[('But', 'CC'), ('that', 'DT'), ('brutality', 'NN'), ('has', 'VBZ'), ('not', 'RB'), ('stopped', 'VBN'), ('the', 'DT'), ('dramatic', 'JJ'), ('progress', 'NN'), ('of', 'IN'), ('a', 'DT'), ('new', 'JJ'), ('democracy', 'NN'), ('.', '.')]\n[('In', 'IN'), ('less', 'JJR'), ('than', 'IN'), ('three', 'CD'), ('years', 'NNS'), (',', ','), ('the', 'DT'), ('nation', 'NN'), ('has', 'VBZ'), ('gone', 'VBN'), ('from', 'IN'), ('dictatorship', 'NN'), ('to', 'TO'), ('liberation', 'NN'), (',', ','), ('to', 'TO'), ('sovereignty', 'VB'), (',', ','), ('to', 'TO'), ('a', 'DT'), ('constitution', 'NN'), (',', ','), ('to', 'TO'), ('national', 'JJ'), ('elections', 'NNS'), ('.', '.')]\n[('At', 'IN'), ('the', 'DT'), ('same', 'JJ'), ('time', 'NN'), (',', ','), ('our', 'PRP$'), ('coalition', 'NN'), ('has', 'VBZ'), ('been', 'VBN'), ('relentless', 'VBN'), ('in', 'IN'), ('shutting', 'VBG'), ('off', 'RP'), ('terrorist', 'JJ'), ('infiltration', 'NN'), (',', ','), ('clearing', 'VBG'), ('out', 'RP'), ('insurgent', 'JJ'), ('strongholds', 'NNS'), (',', ','), ('and', 'CC'), ('turning', 'VBG'), ('over', 'RP'), ('territory', 'NN'), ('to', 'TO'), ('Iraqi', 'NNP'), ('security', 'NN'), ('forces', 'NNS'), ('.', '.')]\n[('I', 'PRP'), ('am', 'VBP'), ('confident', 'JJ'), ('in', 'IN'), ('our', 'PRP$'), ('plan', 'NN'), ('for', 'IN'), ('victory', 'NN'), (';', ':'), ('I', 'PRP'), ('am', 'VBP'), ('confident', 'JJ'), ('in', 'IN'), ('the', 'DT'), ('will', 'MD'), ('of', 'IN'), ('the', 'DT'), ('Iraqi', 'NNP'), ('people', 'NNS'), (';', ':'), ('I', 'PRP'), ('am', 'VBP'), ('confident', 'JJ'), ('in', 'IN'), ('the', 'DT'), ('skill', 'NN'), ('and', 'CC'), ('spirit', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('military', 'JJ'), ('.', '.')]\n[('Fellow', 'NNP'), ('citizens', 'NNS'), (',', ','), ('we', 'PRP'), ('are', 'VBP'), ('in', 'IN'), ('this', 'DT'), ('fight', 'NN'), ('to', 'TO'), ('win', 'VB'), (',', ','), ('and', 'CC'), ('we', 'PRP'), ('are', 'VBP'), ('winning', 'VBG'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('The', 'DT'), ('road', 'NN'), ('of', 'IN'), ('victory', 'NN'), ('is', 'VBZ'), ('the', 'DT'), ('road', 'NN'), ('that', 'WDT'), ('will', 'MD'), ('take', 'VB'), ('our', 'PRP$'), ('troops', 'NNS'), ('home', 'NN'), ('.', '.')]\n[('As', 'IN'), ('we', 'PRP'), ('make', 'VBP'), ('progress', 'NN'), ('on', 'IN'), ('the', 'DT'), ('ground', 'NN'), (',', ','), ('and', 'CC'), ('Iraqi', 'NNP'), ('forces', 'NNS'), ('increasingly', 'RB'), ('take', 'VBP'), ('the', 'DT'), ('lead', 'NN'), (',', ','), ('we', 'PRP'), ('should', 'MD'), ('be', 'VB'), ('able', 'JJ'), ('to', 'TO'), ('further', 'JJ'), ('decrease', 'VB'), ('our', 'PRP$'), ('troop', 'NN'), ('levels', 'NNS'), ('--', ':'), ('but', 'CC'), ('those', 'DT'), ('decisions', 'NNS'), ('will', 'MD'), ('be', 'VB'), ('made', 'VBN'), ('by', 'IN'), ('our', 'PRP$'), ('military', 'JJ'), ('commanders', 'NNS'), (',', ','), ('not', 'RB'), ('by', 'IN'), ('politicians', 'NNS'), ('in', 'IN'), ('Washington', 'NNP'), (',', ','), ('D.C', 'NNP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Our', 'PRP$'), ('coalition', 'NN'), ('has', 'VBZ'), ('learned', 'VBN'), ('from', 'IN'), ('our', 'PRP$'), ('experience', 'NN'), ('in', 'IN'), ('Iraq', 'NNP'), ('.', '.')]\n[('We', 'PRP'), (\"'ve\", 'VBP'), ('adjusted', 'VBN'), ('our', 'PRP$'), ('military', 'JJ'), ('tactics', 'NNS'), ('and', 'CC'), ('changed', 'VBD'), ('our', 'PRP$'), ('approach', 'NN'), ('to', 'TO'), ('reconstruction', 'NN'), ('.', '.')]\n[('Along', 'IN'), ('the', 'DT'), ('way', 'NN'), (',', ','), ('we', 'PRP'), ('have', 'VBP'), ('benefitted', 'VBN'), ('from', 'IN'), ('responsible', 'JJ'), ('criticism', 'NN'), ('and', 'CC'), ('counsel', 'NN'), ('offered', 'VBN'), ('by', 'IN'), ('members', 'NNS'), ('of', 'IN'), ('Congress', 'NNP'), ('of', 'IN'), ('both', 'DT'), ('parties', 'NNS'), ('.', '.')]\n[('In', 'IN'), ('the', 'DT'), ('coming', 'VBG'), ('year', 'NN'), (',', ','), ('I', 'PRP'), ('will', 'MD'), ('continue', 'VB'), ('to', 'TO'), ('reach', 'VB'), ('out', 'RP'), ('and', 'CC'), ('seek', 'VB'), ('your', 'PRP$'), ('good', 'JJ'), ('advice', 'NN'), ('.', '.')]\n[('Yet', 'RB'), (',', ','), ('there', 'EX'), ('is', 'VBZ'), ('a', 'DT'), ('difference', 'NN'), ('between', 'IN'), ('responsible', 'JJ'), ('criticism', 'NN'), ('that', 'WDT'), ('aims', 'VBZ'), ('for', 'IN'), ('success', 'NN'), (',', ','), ('and', 'CC'), ('defeatism', 'NN'), ('that', 'WDT'), ('refuses', 'VBZ'), ('to', 'TO'), ('acknowledge', 'VB'), ('anything', 'NN'), ('but', 'CC'), ('failure', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Hindsight', 'NNP'), ('alone', 'RB'), ('is', 'VBZ'), ('not', 'RB'), ('wisdom', 'JJ'), (',', ','), ('and', 'CC'), ('second-guessing', 'NN'), ('is', 'VBZ'), ('not', 'RB'), ('a', 'DT'), ('strategy', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('With', 'IN'), ('so', 'RB'), ('much', 'JJ'), ('in', 'IN'), ('the', 'DT'), ('balance', 'NN'), (',', ','), ('those', 'DT'), ('of', 'IN'), ('us', 'PRP'), ('in', 'IN'), ('public', 'JJ'), ('office', 'NN'), ('have', 'VBP'), ('a', 'DT'), ('duty', 'NN'), ('to', 'TO'), ('speak', 'VB'), ('with', 'IN'), ('candor', 'NN'), ('.', '.')]\n[('A', 'DT'), ('sudden', 'JJ'), ('withdrawal', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('forces', 'NNS'), ('from', 'IN'), ('Iraq', 'NNP'), ('would', 'MD'), ('abandon', 'VB'), ('our', 'PRP$'), ('Iraqi', 'NNP'), ('allies', 'NNS'), ('to', 'TO'), ('death', 'NN'), ('and', 'CC'), ('prison', 'NN'), (',', ','), ('would', 'MD'), ('put', 'VB'), ('men', 'NNS'), ('like', 'IN'), ('bin', 'NN'), ('Laden', 'NNP'), ('and', 'CC'), ('Zarqawi', 'NNP'), ('in', 'IN'), ('charge', 'NN'), ('of', 'IN'), ('a', 'DT'), ('strategic', 'JJ'), ('country', 'NN'), (',', ','), ('and', 'CC'), ('show', 'VBP'), ('that', 'IN'), ('a', 'DT'), ('pledge', 'NN'), ('from', 'IN'), ('America', 'NNP'), ('means', 'VBZ'), ('little', 'JJ'), ('.', '.')]\n[('Members', 'NNS'), ('of', 'IN'), ('Congress', 'NNP'), (',', ','), ('however', 'RB'), ('we', 'PRP'), ('feel', 'VBP'), ('about', 'IN'), ('the', 'DT'), ('decisions', 'NNS'), ('and', 'CC'), ('debates', 'NNS'), ('of', 'IN'), ('the', 'DT'), ('past', 'NN'), (',', ','), ('our', 'PRP$'), ('nation', 'NN'), ('has', 'VBZ'), ('only', 'RB'), ('one', 'CD'), ('option', 'NN'), (':', ':'), ('We', 'PRP'), ('must', 'MD'), ('keep', 'VB'), ('our', 'PRP$'), ('word', 'NN'), (',', ','), ('defeat', 'VB'), ('our', 'PRP$'), ('enemies', 'NNS'), (',', ','), ('and', 'CC'), ('stand', 'VBP'), ('behind', 'IN'), ('the', 'DT'), ('American', 'JJ'), ('military', 'NN'), ('in', 'IN'), ('this', 'DT'), ('vital', 'JJ'), ('mission', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Laura', 'NNP'), ('Bush', 'NNP'), ('is', 'VBZ'), ('applauded', 'VBN'), ('as', 'IN'), ('she', 'PRP'), ('is', 'VBZ'), ('introduced', 'VBN'), ('Tuesday', 'NNP'), ('evening', 'NN'), (',', ','), ('Jan', 'NNP'), ('.', '.')]\n[('31', 'CD'), (',', ','), ('2006', 'CD'), ('during', 'IN'), ('the', 'DT'), ('State', 'NNP'), ('of', 'IN'), ('the', 'DT'), ('Union', 'NNP'), ('Address', 'NNP'), ('at', 'IN'), ('United', 'NNP'), ('States', 'NNPS'), ('Capitol', 'NNP'), ('in', 'IN'), ('Washington', 'NNP'), ('.', '.')]\n[('White', 'NNP'), ('House', 'NNP'), ('photo', 'NN'), ('by', 'IN'), ('Eric', 'NNP'), ('Draper', 'NNP'), ('Our', 'PRP$'), ('men', 'NNS'), ('and', 'CC'), ('women', 'NNS'), ('in', 'IN'), ('uniform', 'JJ'), ('are', 'VBP'), ('making', 'VBG'), ('sacrifices', 'NNS'), ('--', ':'), ('and', 'CC'), ('showing', 'VBG'), ('a', 'DT'), ('sense', 'NN'), ('of', 'IN'), ('duty', 'NN'), ('stronger', 'JJR'), ('than', 'IN'), ('all', 'DT'), ('fear', 'NN'), ('.', '.')]\n[('They', 'PRP'), ('know', 'VBP'), ('what', 'WP'), ('it', 'PRP'), (\"'s\", 'VBZ'), ('like', 'IN'), ('to', 'TO'), ('fight', 'VB'), ('house', 'NN'), ('to', 'TO'), ('house', 'NN'), ('in', 'IN'), ('a', 'DT'), ('maze', 'NN'), ('of', 'IN'), ('streets', 'NNS'), (',', ','), ('to', 'TO'), ('wear', 'VB'), ('heavy', 'JJ'), ('gear', 'NN'), ('in', 'IN'), ('the', 'DT'), ('desert', 'NN'), ('heat', 'NN'), (',', ','), ('to', 'TO'), ('see', 'VB'), ('a', 'DT'), ('comrade', 'NN'), ('killed', 'VBN'), ('by', 'IN'), ('a', 'DT'), ('roadside', 'NN'), ('bomb', 'NN'), ('.', '.')]\n[('And', 'CC'), ('those', 'DT'), ('who', 'WP'), ('know', 'VBP'), ('the', 'DT'), ('costs', 'NNS'), ('also', 'RB'), ('know', 'VBP'), ('the', 'DT'), ('stakes', 'NNS'), ('.', '.')]\n[('Marine', 'JJ'), ('Staff', 'NNP'), ('Sergeant', 'NNP'), ('Dan', 'NNP'), ('Clay', 'NNP'), ('was', 'VBD'), ('killed', 'VBN'), ('last', 'JJ'), ('month', 'NN'), ('fighting', 'VBG'), ('in', 'IN'), ('Fallujah', 'NNP'), ('.', '.')]\n[('He', 'PRP'), ('left', 'VBD'), ('behind', 'RP'), ('a', 'DT'), ('letter', 'NN'), ('to', 'TO'), ('his', 'PRP$'), ('family', 'NN'), (',', ','), ('but', 'CC'), ('his', 'PRP$'), ('words', 'NNS'), ('could', 'MD'), ('just', 'RB'), ('as', 'RB'), ('well', 'RB'), ('be', 'VB'), ('addressed', 'VBN'), ('to', 'TO'), ('every', 'DT'), ('American', 'NNP'), ('.', '.')]\n[('Here', 'RB'), ('is', 'VBZ'), ('what', 'WP'), ('Dan', 'NNP'), ('wrote', 'VBD'), (':', ':'), ('``', '``'), ('I', 'PRP'), ('know', 'VBP'), ('what', 'WP'), ('honor', 'NN'), ('is', 'VBZ'), ('.', '.')]\n[('...', ':')]\n[('It', 'PRP'), ('has', 'VBZ'), ('been', 'VBN'), ('an', 'DT'), ('honor', 'NN'), ('to', 'TO'), ('protect', 'VB'), ('and', 'CC'), ('serve', 'VB'), ('all', 'DT'), ('of', 'IN'), ('you', 'PRP'), ('.', '.')]\n[('I', 'PRP'), ('faced', 'VBD'), ('death', 'NN'), ('with', 'IN'), ('the', 'DT'), ('secure', 'NN'), ('knowledge', 'NN'), ('that', 'IN'), ('you', 'PRP'), ('would', 'MD'), ('not', 'RB'), ('have', 'VB'), ('to', 'TO'), ('...', ':'), ('.', '.')]\n[('Never', 'RB'), ('falter', 'NN'), ('!', '.')]\n[('Do', 'VBP'), (\"n't\", 'RB'), ('hesitate', 'VB'), ('to', 'TO'), ('honor', 'VB'), ('and', 'CC'), ('support', 'VB'), ('those', 'DT'), ('of', 'IN'), ('us', 'PRP'), ('who', 'WP'), ('have', 'VBP'), ('the', 'DT'), ('honor', 'NN'), ('of', 'IN'), ('protecting', 'VBG'), ('that', 'DT'), ('which', 'WDT'), ('is', 'VBZ'), ('worth', 'JJ'), ('protecting', 'VBG'), ('.', '.'), (\"''\", \"''\")]\n[('Staff', 'NNP'), ('Sergeant', 'NNP'), ('Dan', 'NNP'), ('Clay', 'NNP'), (\"'s\", 'POS'), ('wife', 'NN'), (',', ','), ('Lisa', 'NNP'), (',', ','), ('and', 'CC'), ('his', 'PRP$'), ('mom', 'NN'), ('and', 'CC'), ('dad', 'NN'), (',', ','), ('Sara', 'NNP'), ('Jo', 'NNP'), ('and', 'CC'), ('Bud', 'NNP'), (',', ','), ('are', 'VBP'), ('with', 'IN'), ('us', 'PRP'), ('this', 'DT'), ('evening', 'NN'), ('.', '.')]\n[('Welcome', 'NNP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Our', 'PRP$'), ('nation', 'NN'), ('is', 'VBZ'), ('grateful', 'JJ'), ('to', 'TO'), ('the', 'DT'), ('fallen', 'VBN'), (',', ','), ('who', 'WP'), ('live', 'VBP'), ('in', 'IN'), ('the', 'DT'), ('memory', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('country', 'NN'), ('.', '.')]\n[('We', 'PRP'), (\"'re\", 'VBP'), ('grateful', 'JJ'), ('to', 'TO'), ('all', 'DT'), ('who', 'WP'), ('volunteer', 'VBP'), ('to', 'TO'), ('wear', 'VB'), ('our', 'PRP$'), ('nation', 'NN'), (\"'s\", 'POS'), ('uniform', 'NN'), ('--', ':'), ('and', 'CC'), ('as', 'IN'), ('we', 'PRP'), ('honor', 'VBP'), ('our', 'PRP$'), ('brave', 'NN'), ('troops', 'NNS'), (',', ','), ('let', 'VB'), ('us', 'PRP'), ('never', 'RB'), ('forget', 'VBP'), ('the', 'DT'), ('sacrifices', 'NNS'), ('of', 'IN'), ('America', 'NNP'), (\"'s\", 'POS'), ('military', 'JJ'), ('families', 'NNS'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Our', 'PRP$'), ('offensive', 'JJ'), ('against', 'IN'), ('terror', 'NN'), ('involves', 'VBZ'), ('more', 'JJR'), ('than', 'IN'), ('military', 'JJ'), ('action', 'NN'), ('.', '.')]\n[('Ultimately', 'RB'), (',', ','), ('the', 'DT'), ('only', 'JJ'), ('way', 'NN'), ('to', 'TO'), ('defeat', 'VB'), ('the', 'DT'), ('terrorists', 'NNS'), ('is', 'VBZ'), ('to', 'TO'), ('defeat', 'VB'), ('their', 'PRP$'), ('dark', 'JJ'), ('vision', 'NN'), ('of', 'IN'), ('hatred', 'VBN'), ('and', 'CC'), ('fear', 'VBN'), ('by', 'IN'), ('offering', 'VBG'), ('the', 'DT'), ('hopeful', 'JJ'), ('alternative', 'NN'), ('of', 'IN'), ('political', 'JJ'), ('freedom', 'NN'), ('and', 'CC'), ('peaceful', 'JJ'), ('change', 'NN'), ('.', '.')]\n[('So', 'IN'), ('the', 'DT'), ('United', 'NNP'), ('States', 'NNPS'), ('of', 'IN'), ('America', 'NNP'), ('supports', 'NNS'), ('democratic', 'JJ'), ('reform', 'NN'), ('across', 'IN'), ('the', 'DT'), ('broader', 'JJR'), ('Middle', 'NNP'), ('East', 'NNP'), ('.', '.')]\n[('Elections', 'NNS'), ('are', 'VBP'), ('vital', 'JJ'), (',', ','), ('but', 'CC'), ('they', 'PRP'), ('are', 'VBP'), ('only', 'RB'), ('the', 'DT'), ('beginning', 'NN'), ('.', '.')]\n[('Raising', 'VBG'), ('up', 'RP'), ('a', 'DT'), ('democracy', 'NN'), ('requires', 'VBZ'), ('the', 'DT'), ('rule', 'NN'), ('of', 'IN'), ('law', 'NN'), (',', ','), ('and', 'CC'), ('protection', 'NN'), ('of', 'IN'), ('minorities', 'NNS'), (',', ','), ('and', 'CC'), ('strong', 'JJ'), (',', ','), ('accountable', 'JJ'), ('institutions', 'NNS'), ('that', 'IN'), ('last', 'JJ'), ('longer', 'JJR'), ('than', 'IN'), ('a', 'DT'), ('single', 'JJ'), ('vote', 'NN'), ('.', '.')]\n[('The', 'DT'), ('great', 'JJ'), ('people', 'NNS'), ('of', 'IN'), ('Egypt', 'NNP'), ('have', 'VBP'), ('voted', 'VBN'), ('in', 'IN'), ('a', 'DT'), ('multi-party', 'JJ'), ('presidential', 'JJ'), ('election', 'NN'), ('--', ':'), ('and', 'CC'), ('now', 'RB'), ('their', 'PRP$'), ('government', 'NN'), ('should', 'MD'), ('open', 'VB'), ('paths', 'NNS'), ('of', 'IN'), ('peaceful', 'JJ'), ('opposition', 'NN'), ('that', 'WDT'), ('will', 'MD'), ('reduce', 'VB'), ('the', 'DT'), ('appeal', 'NN'), ('of', 'IN'), ('radicalism', 'NN'), ('.', '.')]\n[('The', 'DT'), ('Palestinian', 'JJ'), ('people', 'NNS'), ('have', 'VBP'), ('voted', 'VBN'), ('in', 'IN'), ('elections', 'NNS'), ('.', '.')]\n[('And', 'CC'), ('now', 'RB'), ('the', 'DT'), ('leaders', 'NNS'), ('of', 'IN'), ('Hamas', 'NNP'), ('must', 'MD'), ('recognize', 'VB'), ('Israel', 'NNP'), (',', ','), ('disarm', 'NN'), (',', ','), ('reject', 'JJ'), ('terrorism', 'NN'), (',', ','), ('and', 'CC'), ('work', 'NN'), ('for', 'IN'), ('lasting', 'VBG'), ('peace', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Saudi', 'NNP'), ('Arabia', 'NNP'), ('has', 'VBZ'), ('taken', 'VBN'), ('the', 'DT'), ('first', 'JJ'), ('steps', 'NNS'), ('of', 'IN'), ('reform', 'NN'), ('--', ':'), ('now', 'RB'), ('it', 'PRP'), ('can', 'MD'), ('offer', 'VB'), ('its', 'PRP$'), ('people', 'NNS'), ('a', 'DT'), ('better', 'JJR'), ('future', 'NN'), ('by', 'IN'), ('pressing', 'VBG'), ('forward', 'RB'), ('with', 'IN'), ('those', 'DT'), ('efforts', 'NNS'), ('.', '.')]\n[('Democracies', 'NNS'), ('in', 'IN'), ('the', 'DT'), ('Middle', 'NNP'), ('East', 'NNP'), ('will', 'MD'), ('not', 'RB'), ('look', 'VB'), ('like', 'IN'), ('our', 'PRP$'), ('own', 'JJ'), (',', ','), ('because', 'IN'), ('they', 'PRP'), ('will', 'MD'), ('reflect', 'VB'), ('the', 'DT'), ('traditions', 'NNS'), ('of', 'IN'), ('their', 'PRP$'), ('own', 'JJ'), ('citizens', 'NNS'), ('.', '.')]\n[('Yet', 'RB'), ('liberty', 'NN'), ('is', 'VBZ'), ('the', 'DT'), ('future', 'NN'), ('of', 'IN'), ('every', 'DT'), ('nation', 'NN'), ('in', 'IN'), ('the', 'DT'), ('Middle', 'NNP'), ('East', 'NNP'), (',', ','), ('because', 'IN'), ('liberty', 'NN'), ('is', 'VBZ'), ('the', 'DT'), ('right', 'NN'), ('and', 'CC'), ('hope', 'NN'), ('of', 'IN'), ('all', 'DT'), ('humanity', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('President', 'NNP'), ('George', 'NNP'), ('W.', 'NNP'), ('Bush', 'NNP'), ('waves', 'VBZ'), ('toward', 'IN'), ('the', 'DT'), ('upper', 'JJ'), ('visitors', 'NNS'), ('gallery', 'NN'), ('of', 'IN'), ('the', 'DT'), ('House', 'NNP'), ('Chamber', 'NNP'), ('following', 'VBG'), ('his', 'PRP$'), ('State', 'NN'), ('of', 'IN'), ('the', 'DT'), ('Union', 'NNP'), ('remarks', 'NNS'), ('Tuesday', 'NNP'), (',', ','), ('Jan', 'NNP'), ('.', '.')]\n[('31', 'CD'), (',', ','), ('2006', 'CD'), ('at', 'IN'), ('the', 'DT'), ('United', 'NNP'), ('States', 'NNPS'), ('Capitol', 'NNP'), ('.', '.')]\n[('White', 'NNP'), ('House', 'NNP'), ('photo', 'NN'), ('by', 'IN'), ('Eric', 'NNP'), ('Draper', 'NNP'), ('The', 'DT'), ('same', 'JJ'), ('is', 'VBZ'), ('true', 'JJ'), ('of', 'IN'), ('Iran', 'NNP'), (',', ','), ('a', 'DT'), ('nation', 'NN'), ('now', 'RB'), ('held', 'VBN'), ('hostage', 'NN'), ('by', 'IN'), ('a', 'DT'), ('small', 'JJ'), ('clerical', 'JJ'), ('elite', 'NN'), ('that', 'WDT'), ('is', 'VBZ'), ('isolating', 'VBG'), ('and', 'CC'), ('repressing', 'VBG'), ('its', 'PRP$'), ('people', 'NNS'), ('.', '.')]\n[('The', 'DT'), ('regime', 'NN'), ('in', 'IN'), ('that', 'DT'), ('country', 'NN'), ('sponsors', 'NNS'), ('terrorists', 'NNS'), ('in', 'IN'), ('the', 'DT'), ('Palestinian', 'JJ'), ('territories', 'NNS'), ('and', 'CC'), ('in', 'IN'), ('Lebanon', 'NNP'), ('--', ':'), ('and', 'CC'), ('that', 'DT'), ('must', 'MD'), ('come', 'VB'), ('to', 'TO'), ('an', 'DT'), ('end', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('The', 'DT'), ('Iranian', 'JJ'), ('government', 'NN'), ('is', 'VBZ'), ('defying', 'VBG'), ('the', 'DT'), ('world', 'NN'), ('with', 'IN'), ('its', 'PRP$'), ('nuclear', 'JJ'), ('ambitions', 'NNS'), (',', ','), ('and', 'CC'), ('the', 'DT'), ('nations', 'NNS'), ('of', 'IN'), ('the', 'DT'), ('world', 'NN'), ('must', 'MD'), ('not', 'RB'), ('permit', 'VB'), ('the', 'DT'), ('Iranian', 'JJ'), ('regime', 'NN'), ('to', 'TO'), ('gain', 'VB'), ('nuclear', 'JJ'), ('weapons', 'NNS'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('America', 'NNP'), ('will', 'MD'), ('continue', 'VB'), ('to', 'TO'), ('rally', 'VB'), ('the', 'DT'), ('world', 'NN'), ('to', 'TO'), ('confront', 'VB'), ('these', 'DT'), ('threats', 'NNS'), ('.', '.')]\n[('Tonight', 'NNP'), (',', ','), ('let', 'VB'), ('me', 'PRP'), ('speak', 'VB'), ('directly', 'RB'), ('to', 'TO'), ('the', 'DT'), ('citizens', 'NNS'), ('of', 'IN'), ('Iran', 'NNP'), (':', ':'), ('America', 'NNP'), ('respects', 'VBZ'), ('you', 'PRP'), (',', ','), ('and', 'CC'), ('we', 'PRP'), ('respect', 'VBP'), ('your', 'PRP$'), ('country', 'NN'), ('.', '.')]\n[('We', 'PRP'), ('respect', 'VBP'), ('your', 'PRP$'), ('right', 'NN'), ('to', 'TO'), ('choose', 'VB'), ('your', 'PRP$'), ('own', 'JJ'), ('future', 'NN'), ('and', 'CC'), ('win', 'VB'), ('your', 'PRP$'), ('own', 'JJ'), ('freedom', 'NN'), ('.', '.')]\n[('And', 'CC'), ('our', 'PRP$'), ('nation', 'NN'), ('hopes', 'VBZ'), ('one', 'CD'), ('day', 'NN'), ('to', 'TO'), ('be', 'VB'), ('the', 'DT'), ('closest', 'JJS'), ('of', 'IN'), ('friends', 'NNS'), ('with', 'IN'), ('a', 'DT'), ('free', 'JJ'), ('and', 'CC'), ('democratic', 'JJ'), ('Iran', 'NNP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('To', 'TO'), ('overcome', 'VB'), ('dangers', 'NNS'), ('in', 'IN'), ('our', 'PRP$'), ('world', 'NN'), (',', ','), ('we', 'PRP'), ('must', 'MD'), ('also', 'RB'), ('take', 'VB'), ('the', 'DT'), ('offensive', 'JJ'), ('by', 'IN'), ('encouraging', 'VBG'), ('economic', 'JJ'), ('progress', 'NN'), (',', ','), ('and', 'CC'), ('fighting', 'VBG'), ('disease', 'NN'), (',', ','), ('and', 'CC'), ('spreading', 'VBG'), ('hope', 'NN'), ('in', 'IN'), ('hopeless', 'JJ'), ('lands', 'NNS'), ('.', '.')]\n[('Isolationism', 'NNP'), ('would', 'MD'), ('not', 'RB'), ('only', 'RB'), ('tie', 'VB'), ('our', 'PRP$'), ('hands', 'NNS'), ('in', 'IN'), ('fighting', 'VBG'), ('enemies', 'NNS'), (',', ','), ('it', 'PRP'), ('would', 'MD'), ('keep', 'VB'), ('us', 'PRP'), ('from', 'IN'), ('helping', 'VBG'), ('our', 'PRP$'), ('friends', 'NNS'), ('in', 'IN'), ('desperate', 'JJ'), ('need', 'NN'), ('.', '.')]\n[('We', 'PRP'), ('show', 'VBP'), ('compassion', 'JJ'), ('abroad', 'RB'), ('because', 'IN'), ('Americans', 'NNPS'), ('believe', 'VBP'), ('in', 'IN'), ('the', 'DT'), ('God-given', 'NNP'), ('dignity', 'NN'), ('and', 'CC'), ('worth', 'NN'), ('of', 'IN'), ('a', 'DT'), ('villager', 'NN'), ('with', 'IN'), ('HIV/AIDS', 'NNP'), (',', ','), ('or', 'CC'), ('an', 'DT'), ('infant', 'NN'), ('with', 'IN'), ('malaria', 'NNS'), (',', ','), ('or', 'CC'), ('a', 'DT'), ('refugee', 'JJ'), ('fleeing', 'NN'), ('genocide', 'NN'), (',', ','), ('or', 'CC'), ('a', 'DT'), ('young', 'JJ'), ('girl', 'NN'), ('sold', 'VBN'), ('into', 'IN'), ('slavery', 'NN'), ('.', '.')]\n[('We', 'PRP'), ('also', 'RB'), ('show', 'VBP'), ('compassion', 'NN'), ('abroad', 'RB'), ('because', 'IN'), ('regions', 'NNS'), ('overwhelmed', 'VBN'), ('by', 'IN'), ('poverty', 'NN'), (',', ','), ('corruption', 'NN'), (',', ','), ('and', 'CC'), ('despair', 'NN'), ('are', 'VBP'), ('sources', 'NNS'), ('of', 'IN'), ('terrorism', 'NN'), (',', ','), ('and', 'CC'), ('organized', 'VBD'), ('crime', 'NN'), (',', ','), ('and', 'CC'), ('human', 'JJ'), ('trafficking', 'NN'), (',', ','), ('and', 'CC'), ('the', 'DT'), ('drug', 'NN'), ('trade', 'NN'), ('.', '.')]\n[('In', 'IN'), ('recent', 'JJ'), ('years', 'NNS'), (',', ','), ('you', 'PRP'), ('and', 'CC'), ('I', 'PRP'), ('have', 'VBP'), ('taken', 'VBN'), ('unprecedented', 'JJ'), ('action', 'NN'), ('to', 'TO'), ('fight', 'VB'), ('AIDS', 'NNP'), ('and', 'CC'), ('malaria', 'NNS'), (',', ','), ('expand', 'VBP'), ('the', 'DT'), ('education', 'NN'), ('of', 'IN'), ('girls', 'NNS'), (',', ','), ('and', 'CC'), ('reward', 'RB'), ('developing', 'VBG'), ('nations', 'NNS'), ('that', 'WDT'), ('are', 'VBP'), ('moving', 'VBG'), ('forward', 'RB'), ('with', 'IN'), ('economic', 'JJ'), ('and', 'CC'), ('political', 'JJ'), ('reform', 'NN'), ('.', '.')]\n[('For', 'IN'), ('people', 'NNS'), ('everywhere', 'RB'), (',', ','), ('the', 'DT'), ('United', 'NNP'), ('States', 'NNPS'), ('is', 'VBZ'), ('a', 'DT'), ('partner', 'NN'), ('for', 'IN'), ('a', 'DT'), ('better', 'JJR'), ('life', 'NN'), ('.', '.')]\n[('Short-changing', 'VBG'), ('these', 'DT'), ('efforts', 'NNS'), ('would', 'MD'), ('increase', 'VB'), ('the', 'DT'), ('suffering', 'NN'), ('and', 'CC'), ('chaos', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('world', 'NN'), (',', ','), ('undercut', 'JJ'), ('our', 'PRP$'), ('long-term', 'JJ'), ('security', 'NN'), (',', ','), ('and', 'CC'), ('dull', 'VB'), ('the', 'DT'), ('conscience', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('country', 'NN'), ('.', '.')]\n[('I', 'PRP'), ('urge', 'VBP'), ('members', 'NNS'), ('of', 'IN'), ('Congress', 'NNP'), ('to', 'TO'), ('serve', 'VB'), ('the', 'DT'), ('interests', 'NNS'), ('of', 'IN'), ('America', 'NNP'), ('by', 'IN'), ('showing', 'VBG'), ('the', 'DT'), ('compassion', 'NN'), ('of', 'IN'), ('America', 'NNP'), ('.', '.')]\n[('Our', 'PRP$'), ('country', 'NN'), ('must', 'MD'), ('also', 'RB'), ('remain', 'VB'), ('on', 'IN'), ('the', 'DT'), ('offensive', 'JJ'), ('against', 'IN'), ('terrorism', 'NN'), ('here', 'RB'), ('at', 'IN'), ('home', 'NN'), ('.', '.')]\n[('The', 'DT'), ('enemy', 'NN'), ('has', 'VBZ'), ('not', 'RB'), ('lost', 'VBN'), ('the', 'DT'), ('desire', 'NN'), ('or', 'CC'), ('capability', 'NN'), ('to', 'TO'), ('attack', 'VB'), ('us', 'PRP'), ('.', '.')]\n[('Fortunately', 'RB'), (',', ','), ('this', 'DT'), ('nation', 'NN'), ('has', 'VBZ'), ('superb', 'VBN'), ('professionals', 'NNS'), ('in', 'IN'), ('law', 'NN'), ('enforcement', 'NN'), (',', ','), ('intelligence', 'NN'), (',', ','), ('the', 'DT'), ('military', 'JJ'), (',', ','), ('and', 'CC'), ('homeland', 'VBP'), ('security', 'NN'), ('.', '.')]\n[('These', 'DT'), ('men', 'NNS'), ('and', 'CC'), ('women', 'NNS'), ('are', 'VBP'), ('dedicating', 'VBG'), ('their', 'PRP$'), ('lives', 'NNS'), (',', ','), ('protecting', 'VBG'), ('us', 'PRP'), ('all', 'DT'), (',', ','), ('and', 'CC'), ('they', 'PRP'), ('deserve', 'VBP'), ('our', 'PRP$'), ('support', 'NN'), ('and', 'CC'), ('our', 'PRP$'), ('thanks', 'NNS'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('They', 'PRP'), ('also', 'RB'), ('deserve', 'VBP'), ('the', 'DT'), ('same', 'JJ'), ('tools', 'NNS'), ('they', 'PRP'), ('already', 'RB'), ('use', 'VBP'), ('to', 'TO'), ('fight', 'VB'), ('drug', 'NN'), ('trafficking', 'NN'), ('and', 'CC'), ('organized', 'VBN'), ('crime', 'NN'), ('--', ':'), ('so', 'RB'), ('I', 'PRP'), ('ask', 'VBP'), ('you', 'PRP'), ('to', 'TO'), ('reauthorize', 'VB'), ('the', 'DT'), ('Patriot', 'NNP'), ('Act', 'NNP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('It', 'PRP'), ('is', 'VBZ'), ('said', 'VBD'), ('that', 'IN'), ('prior', 'JJ'), ('to', 'TO'), ('the', 'DT'), ('attacks', 'NNS'), ('of', 'IN'), ('September', 'NNP'), ('the', 'DT'), ('11th', 'CD'), (',', ','), ('our', 'PRP$'), ('government', 'NN'), ('failed', 'VBD'), ('to', 'TO'), ('connect', 'VB'), ('the', 'DT'), ('dots', 'NNS'), ('of', 'IN'), ('the', 'DT'), ('conspiracy', 'NN'), ('.', '.')]\n[('We', 'PRP'), ('now', 'RB'), ('know', 'VBP'), ('that', 'IN'), ('two', 'CD'), ('of', 'IN'), ('the', 'DT'), ('hijackers', 'NNS'), ('in', 'IN'), ('the', 'DT'), ('United', 'NNP'), ('States', 'NNPS'), ('placed', 'VBD'), ('telephone', 'NN'), ('calls', 'NNS'), ('to', 'TO'), ('al', 'VB'), ('Qaeda', 'NNP'), ('operatives', 'VBZ'), ('overseas', 'RB'), ('.', '.')]\n[('But', 'CC'), ('we', 'PRP'), ('did', 'VBD'), ('not', 'RB'), ('know', 'VB'), ('about', 'IN'), ('their', 'PRP$'), ('plans', 'NNS'), ('until', 'IN'), ('it', 'PRP'), ('was', 'VBD'), ('too', 'RB'), ('late', 'JJ'), ('.', '.')]\n[('So', 'RB'), ('to', 'TO'), ('prevent', 'VB'), ('another', 'DT'), ('attack', 'NN'), ('--', ':'), ('based', 'VBN'), ('on', 'IN'), ('authority', 'NN'), ('given', 'VBN'), ('to', 'TO'), ('me', 'PRP'), ('by', 'IN'), ('the', 'DT'), ('Constitution', 'NNP'), ('and', 'CC'), ('by', 'IN'), ('statute', 'NN'), ('--', ':'), ('I', 'PRP'), ('have', 'VBP'), ('authorized', 'VBN'), ('a', 'DT'), ('terrorist', 'JJ'), ('surveillance', 'NN'), ('program', 'NN'), ('to', 'TO'), ('aggressively', 'RB'), ('pursue', 'VB'), ('the', 'DT'), ('international', 'JJ'), ('communications', 'NNS'), ('of', 'IN'), ('suspected', 'JJ'), ('al', 'JJ'), ('Qaeda', 'NNP'), ('operatives', 'NNS'), ('and', 'CC'), ('affiliates', 'NNS'), ('to', 'TO'), ('and', 'CC'), ('from', 'IN'), ('America', 'NNP'), ('.', '.')]\n[('Previous', 'JJ'), ('Presidents', 'NNS'), ('have', 'VBP'), ('used', 'VBN'), ('the', 'DT'), ('same', 'JJ'), ('constitutional', 'JJ'), ('authority', 'NN'), ('I', 'PRP'), ('have', 'VBP'), (',', ','), ('and', 'CC'), ('federal', 'JJ'), ('courts', 'NNS'), ('have', 'VBP'), ('approved', 'VBN'), ('the', 'DT'), ('use', 'NN'), ('of', 'IN'), ('that', 'DT'), ('authority', 'NN'), ('.', '.')]\n[('Appropriate', 'JJ'), ('members', 'NNS'), ('of', 'IN'), ('Congress', 'NNP'), ('have', 'VBP'), ('been', 'VBN'), ('kept', 'VBN'), ('informed', 'VBN'), ('.', '.')]\n[('The', 'DT'), ('terrorist', 'JJ'), ('surveillance', 'NN'), ('program', 'NN'), ('has', 'VBZ'), ('helped', 'VBN'), ('prevent', 'VB'), ('terrorist', 'JJ'), ('attacks', 'NNS'), ('.', '.')]\n[('It', 'PRP'), ('remains', 'VBZ'), ('essential', 'JJ'), ('to', 'TO'), ('the', 'DT'), ('security', 'NN'), ('of', 'IN'), ('America', 'NNP'), ('.', '.')]\n[('If', 'IN'), ('there', 'EX'), ('are', 'VBP'), ('people', 'NNS'), ('inside', 'IN'), ('our', 'PRP$'), ('country', 'NN'), ('who', 'WP'), ('are', 'VBP'), ('talking', 'VBG'), ('with', 'IN'), ('al', 'NN'), ('Qaeda', 'NNP'), (',', ','), ('we', 'PRP'), ('want', 'VBP'), ('to', 'TO'), ('know', 'VB'), ('about', 'IN'), ('it', 'PRP'), (',', ','), ('because', 'IN'), ('we', 'PRP'), ('will', 'MD'), ('not', 'RB'), ('sit', 'VB'), ('back', 'RB'), ('and', 'CC'), ('wait', 'NN'), ('to', 'TO'), ('be', 'VB'), ('hit', 'VBN'), ('again', 'RB'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('In', 'IN'), ('all', 'PDT'), ('these', 'DT'), ('areas', 'NNS'), ('--', ':'), ('from', 'IN'), ('the', 'DT'), ('disruption', 'NN'), ('of', 'IN'), ('terror', 'NN'), ('networks', 'NNS'), (',', ','), ('to', 'TO'), ('victory', 'NN'), ('in', 'IN'), ('Iraq', 'NNP'), (',', ','), ('to', 'TO'), ('the', 'DT'), ('spread', 'NN'), ('of', 'IN'), ('freedom', 'NN'), ('and', 'CC'), ('hope', 'NN'), ('in', 'IN'), ('troubled', 'JJ'), ('regions', 'NNS'), ('--', ':'), ('we', 'PRP'), ('need', 'VBP'), ('the', 'DT'), ('support', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('friends', 'NNS'), ('and', 'CC'), ('allies', 'NNS'), ('.', '.')]\n[('To', 'TO'), ('draw', 'VB'), ('that', 'DT'), ('support', 'NN'), (',', ','), ('we', 'PRP'), ('must', 'MD'), ('always', 'RB'), ('be', 'VB'), ('clear', 'JJ'), ('in', 'IN'), ('our', 'PRP$'), ('principles', 'NNS'), ('and', 'CC'), ('willing', 'JJ'), ('to', 'TO'), ('act', 'VB'), ('.', '.')]\n[('The', 'DT'), ('only', 'JJ'), ('alternative', 'NN'), ('to', 'TO'), ('American', 'JJ'), ('leadership', 'NN'), ('is', 'VBZ'), ('a', 'DT'), ('dramatically', 'RB'), ('more', 'RBR'), ('dangerous', 'JJ'), ('and', 'CC'), ('anxious', 'JJ'), ('world', 'NN'), ('.', '.')]\n[('Yet', 'CC'), ('we', 'PRP'), ('also', 'RB'), ('choose', 'VBP'), ('to', 'TO'), ('lead', 'VB'), ('because', 'IN'), ('it', 'PRP'), ('is', 'VBZ'), ('a', 'DT'), ('privilege', 'NN'), ('to', 'TO'), ('serve', 'VB'), ('the', 'DT'), ('values', 'NNS'), ('that', 'WDT'), ('gave', 'VBD'), ('us', 'PRP'), ('birth', 'NN'), ('.', '.')]\n[('American', 'JJ'), ('leaders', 'NNS'), ('--', ':'), ('from', 'IN'), ('Roosevelt', 'NNP'), ('to', 'TO'), ('Truman', 'NNP'), ('to', 'TO'), ('Kennedy', 'NNP'), ('to', 'TO'), ('Reagan', 'NNP'), ('--', ':'), ('rejected', 'VBD'), ('isolation', 'NN'), ('and', 'CC'), ('retreat', 'NN'), (',', ','), ('because', 'IN'), ('they', 'PRP'), ('knew', 'VBD'), ('that', 'IN'), ('America', 'NNP'), ('is', 'VBZ'), ('always', 'RB'), ('more', 'RBR'), ('secure', 'JJ'), ('when', 'WRB'), ('freedom', 'NN'), ('is', 'VBZ'), ('on', 'IN'), ('the', 'DT'), ('march', 'NN'), ('.', '.')]\n[('Our', 'PRP$'), ('own', 'JJ'), ('generation', 'NN'), ('is', 'VBZ'), ('in', 'IN'), ('a', 'DT'), ('long', 'JJ'), ('war', 'NN'), ('against', 'IN'), ('a', 'DT'), ('determined', 'JJ'), ('enemy', 'NN'), ('--', ':'), ('a', 'DT'), ('war', 'NN'), ('that', 'WDT'), ('will', 'MD'), ('be', 'VB'), ('fought', 'VBN'), ('by', 'IN'), ('Presidents', 'NNS'), ('of', 'IN'), ('both', 'DT'), ('parties', 'NNS'), (',', ','), ('who', 'WP'), ('will', 'MD'), ('need', 'VB'), ('steady', 'JJ'), ('bipartisan', 'JJ'), ('support', 'NN'), ('from', 'IN'), ('the', 'DT'), ('Congress', 'NNP'), ('.', '.')]\n[('And', 'CC'), ('tonight', 'NN'), ('I', 'PRP'), ('ask', 'VBP'), ('for', 'IN'), ('yours', 'NNS'), ('.', '.')]\n[('Together', 'RB'), (',', ','), ('let', 'VB'), ('us', 'PRP'), ('protect', 'VB'), ('our', 'PRP$'), ('country', 'NN'), (',', ','), ('support', 'VB'), ('the', 'DT'), ('men', 'NNS'), ('and', 'CC'), ('women', 'NNS'), ('who', 'WP'), ('defend', 'VBP'), ('us', 'PRP'), (',', ','), ('and', 'CC'), ('lead', 'VB'), ('this', 'DT'), ('world', 'NN'), ('toward', 'IN'), ('freedom', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Here', 'RB'), ('at', 'IN'), ('home', 'NN'), (',', ','), ('America', 'NNP'), ('also', 'RB'), ('has', 'VBZ'), ('a', 'DT'), ('great', 'JJ'), ('opportunity', 'NN'), (':', ':'), ('We', 'PRP'), ('will', 'MD'), ('build', 'VB'), ('the', 'DT'), ('prosperity', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('country', 'NN'), ('by', 'IN'), ('strengthening', 'VBG'), ('our', 'PRP$'), ('economic', 'JJ'), ('leadership', 'NN'), ('in', 'IN'), ('the', 'DT'), ('world', 'NN'), ('.', '.')]\n[('Our', 'PRP$'), ('economy', 'NN'), ('is', 'VBZ'), ('healthy', 'JJ'), ('and', 'CC'), ('vigorous', 'JJ'), (',', ','), ('and', 'CC'), ('growing', 'VBG'), ('faster', 'RBR'), ('than', 'IN'), ('other', 'JJ'), ('major', 'JJ'), ('industrialized', 'VBN'), ('nations', 'NNS'), ('.', '.')]\n[('In', 'IN'), ('the', 'DT'), ('last', 'JJ'), ('two-and-a-half', 'JJ'), ('years', 'NNS'), (',', ','), ('America', 'NNP'), ('has', 'VBZ'), ('created', 'VBN'), ('4.6', 'CD'), ('million', 'CD'), ('new', 'JJ'), ('jobs', 'NNS'), ('--', ':'), ('more', 'JJR'), ('than', 'IN'), ('Japan', 'NNP'), ('and', 'CC'), ('the', 'DT'), ('European', 'NNP'), ('Union', 'NNP'), ('combined', 'VBD'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Even', 'RB'), ('in', 'IN'), ('the', 'DT'), ('face', 'NN'), ('of', 'IN'), ('higher', 'JJR'), ('energy', 'NN'), ('prices', 'NNS'), ('and', 'CC'), ('natural', 'JJ'), ('disasters', 'NNS'), (',', ','), ('the', 'DT'), ('American', 'JJ'), ('people', 'NNS'), ('have', 'VBP'), ('turned', 'VBN'), ('in', 'IN'), ('an', 'DT'), ('economic', 'JJ'), ('performance', 'NN'), ('that', 'WDT'), ('is', 'VBZ'), ('the', 'DT'), ('envy', 'NN'), ('of', 'IN'), ('the', 'DT'), ('world', 'NN'), ('.', '.')]\n[('The', 'DT'), ('American', 'JJ'), ('economy', 'NN'), ('is', 'VBZ'), ('preeminent', 'JJ'), (',', ','), ('but', 'CC'), ('we', 'PRP'), ('can', 'MD'), ('not', 'RB'), ('afford', 'VB'), ('to', 'TO'), ('be', 'VB'), ('complacent', 'JJ'), ('.', '.')]\n[('In', 'IN'), ('a', 'DT'), ('dynamic', 'JJ'), ('world', 'NN'), ('economy', 'NN'), (',', ','), ('we', 'PRP'), ('are', 'VBP'), ('seeing', 'VBG'), ('new', 'JJ'), ('competitors', 'NNS'), (',', ','), ('like', 'IN'), ('China', 'NNP'), ('and', 'CC'), ('India', 'NNP'), (',', ','), ('and', 'CC'), ('this', 'DT'), ('creates', 'VBZ'), ('uncertainty', 'NN'), (',', ','), ('which', 'WDT'), ('makes', 'VBZ'), ('it', 'PRP'), ('easier', 'JJR'), ('to', 'TO'), ('feed', 'VB'), ('people', 'NNS'), (\"'s\", 'POS'), ('fears', 'NNS'), ('.', '.')]\n[('So', 'IN'), ('we', 'PRP'), (\"'re\", 'VBP'), ('seeing', 'VBG'), ('some', 'DT'), ('old', 'JJ'), ('temptations', 'NNS'), ('return', 'NN'), ('.', '.')]\n[('Protectionists', 'NNS'), ('want', 'VBP'), ('to', 'TO'), ('escape', 'VB'), ('competition', 'NN'), (',', ','), ('pretending', 'VBG'), ('that', 'IN'), ('we', 'PRP'), ('can', 'MD'), ('keep', 'VB'), ('our', 'PRP$'), ('high', 'JJ'), ('standard', 'NN'), ('of', 'IN'), ('living', 'NN'), ('while', 'IN'), ('walling', 'VBG'), ('off', 'RP'), ('our', 'PRP$'), ('economy', 'NN'), ('.', '.')]\n[('Others', 'NNS'), ('say', 'VBP'), ('that', 'IN'), ('the', 'DT'), ('government', 'NN'), ('needs', 'VBZ'), ('to', 'TO'), ('take', 'VB'), ('a', 'DT'), ('larger', 'JJR'), ('role', 'NN'), ('in', 'IN'), ('directing', 'VBG'), ('the', 'DT'), ('economy', 'NN'), (',', ','), ('centralizing', 'VBG'), ('more', 'JJR'), ('power', 'NN'), ('in', 'IN'), ('Washington', 'NNP'), ('and', 'CC'), ('increasing', 'VBG'), ('taxes', 'NNS'), ('.', '.')]\n[('We', 'PRP'), ('hear', 'VBP'), ('claims', 'NNS'), ('that', 'IN'), ('immigrants', 'NNS'), ('are', 'VBP'), ('somehow', 'RB'), ('bad', 'JJ'), ('for', 'IN'), ('the', 'DT'), ('economy', 'NN'), ('--', ':'), ('even', 'RB'), ('though', 'IN'), ('this', 'DT'), ('economy', 'NN'), ('could', 'MD'), ('not', 'RB'), ('function', 'VB'), ('without', 'IN'), ('them', 'PRP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('All', 'PDT'), ('these', 'DT'), ('are', 'VBP'), ('forms', 'NNS'), ('of', 'IN'), ('economic', 'JJ'), ('retreat', 'NN'), (',', ','), ('and', 'CC'), ('they', 'PRP'), ('lead', 'VBP'), ('in', 'IN'), ('the', 'DT'), ('same', 'JJ'), ('direction', 'NN'), ('--', ':'), ('toward', 'IN'), ('a', 'DT'), ('stagnant', 'JJ'), ('and', 'CC'), ('second-rate', 'JJ'), ('economy', 'NN'), ('.', '.')]\n[('Tonight', 'NNP'), ('I', 'PRP'), ('will', 'MD'), ('set', 'VB'), ('out', 'RP'), ('a', 'DT'), ('better', 'JJR'), ('path', 'NN'), (':', ':'), ('an', 'DT'), ('agenda', 'NN'), ('for', 'IN'), ('a', 'DT'), ('nation', 'NN'), ('that', 'WDT'), ('competes', 'VBZ'), ('with', 'IN'), ('confidence', 'NN'), (';', ':'), ('an', 'DT'), ('agenda', 'NN'), ('that', 'WDT'), ('will', 'MD'), ('raise', 'VB'), ('standards', 'NNS'), ('of', 'IN'), ('living', 'NN'), ('and', 'CC'), ('generate', 'VB'), ('new', 'JJ'), ('jobs', 'NNS'), ('.', '.')]\n[('Americans', 'NNPS'), ('should', 'MD'), ('not', 'RB'), ('fear', 'VB'), ('our', 'PRP$'), ('economic', 'JJ'), ('future', 'NN'), (',', ','), ('because', 'IN'), ('we', 'PRP'), ('intend', 'VBP'), ('to', 'TO'), ('shape', 'VB'), ('it', 'PRP'), ('.', '.')]\n[('Keeping', 'VBG'), ('America', 'NNP'), ('competitive', 'JJ'), ('begins', 'NNS'), ('with', 'IN'), ('keeping', 'VBG'), ('our', 'PRP$'), ('economy', 'NN'), ('growing', 'VBG'), ('.', '.')]\n[('And', 'CC'), ('our', 'PRP$'), ('economy', 'NN'), ('grows', 'VBZ'), ('when', 'WRB'), ('Americans', 'NNPS'), ('have', 'VBP'), ('more', 'JJR'), ('of', 'IN'), ('their', 'PRP$'), ('own', 'JJ'), ('money', 'NN'), ('to', 'TO'), ('spend', 'VB'), (',', ','), ('save', 'VB'), (',', ','), ('and', 'CC'), ('invest', 'JJS'), ('.', '.')]\n[('In', 'IN'), ('the', 'DT'), ('last', 'JJ'), ('five', 'CD'), ('years', 'NNS'), (',', ','), ('the', 'DT'), ('tax', 'NN'), ('relief', 'NN'), ('you', 'PRP'), ('passed', 'VBN'), ('has', 'VBZ'), ('left', 'VBN'), ('$', '$'), ('880', 'CD'), ('billion', 'CD'), ('in', 'IN'), ('the', 'DT'), ('hands', 'NNS'), ('of', 'IN'), ('American', 'JJ'), ('workers', 'NNS'), (',', ','), ('investors', 'NNS'), (',', ','), ('small', 'JJ'), ('businesses', 'NNS'), (',', ','), ('and', 'CC'), ('families', 'NNS'), ('--', ':'), ('and', 'CC'), ('they', 'PRP'), ('have', 'VBP'), ('used', 'VBN'), ('it', 'PRP'), ('to', 'TO'), ('help', 'VB'), ('produce', 'VB'), ('more', 'JJR'), ('than', 'IN'), ('four', 'CD'), ('years', 'NNS'), ('of', 'IN'), ('uninterrupted', 'JJ'), ('economic', 'JJ'), ('growth', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Yet', 'RB'), ('the', 'DT'), ('tax', 'NN'), ('relief', 'NN'), ('is', 'VBZ'), ('set', 'VBN'), ('to', 'TO'), ('expire', 'VB'), ('in', 'IN'), ('the', 'DT'), ('next', 'JJ'), ('few', 'JJ'), ('years', 'NNS'), ('.', '.')]\n[('If', 'IN'), ('we', 'PRP'), ('do', 'VBP'), ('nothing', 'NN'), (',', ','), ('American', 'NNP'), ('families', 'NNS'), ('will', 'MD'), ('face', 'VB'), ('a', 'DT'), ('massive', 'JJ'), ('tax', 'NN'), ('increase', 'NN'), ('they', 'PRP'), ('do', 'VBP'), ('not', 'RB'), ('expect', 'VB'), ('and', 'CC'), ('will', 'MD'), ('not', 'RB'), ('welcome', 'VB'), ('.', '.')]\n[('Because', 'IN'), ('America', 'NNP'), ('needs', 'VBZ'), ('more', 'JJR'), ('than', 'IN'), ('a', 'DT'), ('temporary', 'JJ'), ('expansion', 'NN'), (',', ','), ('we', 'PRP'), ('need', 'VBP'), ('more', 'JJR'), ('than', 'IN'), ('temporary', 'JJ'), ('tax', 'NN'), ('relief', 'NN'), ('.', '.')]\n[('I', 'PRP'), ('urge', 'VBP'), ('the', 'DT'), ('Congress', 'NNP'), ('to', 'TO'), ('act', 'VB'), ('responsibly', 'RB'), (',', ','), ('and', 'CC'), ('make', 'VB'), ('the', 'DT'), ('tax', 'NN'), ('cuts', 'NNS'), ('permanent', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Keeping', 'VBG'), ('America', 'NNP'), ('competitive', 'JJ'), ('requires', 'VBZ'), ('us', 'PRP'), ('to', 'TO'), ('be', 'VB'), ('good', 'JJ'), ('stewards', 'NNS'), ('of', 'IN'), ('tax', 'NN'), ('dollars', 'NNS'), ('.', '.')]\n[('Every', 'DT'), ('year', 'NN'), ('of', 'IN'), ('my', 'PRP$'), ('presidency', 'NN'), (',', ','), ('we', 'PRP'), (\"'ve\", 'VBP'), ('reduced', 'VBN'), ('the', 'DT'), ('growth', 'NN'), ('of', 'IN'), ('non-security', 'JJ'), ('discretionary', 'JJ'), ('spending', 'NN'), (',', ','), ('and', 'CC'), ('last', 'JJ'), ('year', 'NN'), ('you', 'PRP'), ('passed', 'VBD'), ('bills', 'NNS'), ('that', 'IN'), ('cut', 'VBD'), ('this', 'DT'), ('spending', 'NN'), ('.', '.')]\n[('This', 'DT'), ('year', 'NN'), ('my', 'PRP$'), ('budget', 'NN'), ('will', 'MD'), ('cut', 'VB'), ('it', 'PRP'), ('again', 'RB'), (',', ','), ('and', 'CC'), ('reduce', 'VB'), ('or', 'CC'), ('eliminate', 'VB'), ('more', 'JJR'), ('than', 'IN'), ('140', 'CD'), ('programs', 'NNS'), ('that', 'WDT'), ('are', 'VBP'), ('performing', 'VBG'), ('poorly', 'RB'), ('or', 'CC'), ('not', 'RB'), ('fulfilling', 'JJ'), ('essential', 'JJ'), ('priorities', 'NNS'), ('.', '.')]\n[('By', 'IN'), ('passing', 'VBG'), ('these', 'DT'), ('reforms', 'NNS'), (',', ','), ('we', 'PRP'), ('will', 'MD'), ('save', 'VB'), ('the', 'DT'), ('American', 'NNP'), ('taxpayer', 'NN'), ('another', 'DT'), ('$', '$'), ('14', 'CD'), ('billion', 'CD'), ('next', 'JJ'), ('year', 'NN'), (',', ','), ('and', 'CC'), ('stay', 'VB'), ('on', 'IN'), ('track', 'NN'), ('to', 'TO'), ('cut', 'VB'), ('the', 'DT'), ('deficit', 'NN'), ('in', 'IN'), ('half', 'NN'), ('by', 'IN'), ('2009', 'CD'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('I', 'PRP'), ('am', 'VBP'), ('pleased', 'JJ'), ('that', 'IN'), ('members', 'NNS'), ('of', 'IN'), ('Congress', 'NNP'), ('are', 'VBP'), ('working', 'VBG'), ('on', 'IN'), ('earmark', 'NN'), ('reform', 'NN'), (',', ','), ('because', 'IN'), ('the', 'DT'), ('federal', 'JJ'), ('budget', 'NN'), ('has', 'VBZ'), ('too', 'RB'), ('many', 'JJ'), ('special', 'JJ'), ('interest', 'NN'), ('projects', 'NNS'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('And', 'CC'), ('we', 'PRP'), ('can', 'MD'), ('tackle', 'VB'), ('this', 'DT'), ('problem', 'NN'), ('together', 'RB'), (',', ','), ('if', 'IN'), ('you', 'PRP'), ('pass', 'VBP'), ('the', 'DT'), ('line-item', 'JJ'), ('veto', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('We', 'PRP'), ('must', 'MD'), ('also', 'RB'), ('confront', 'VB'), ('the', 'DT'), ('larger', 'JJR'), ('challenge', 'NN'), ('of', 'IN'), ('mandatory', 'JJ'), ('spending', 'NN'), (',', ','), ('or', 'CC'), ('entitlements', 'NNS'), ('.', '.')]\n[('This', 'DT'), ('year', 'NN'), (',', ','), ('the', 'DT'), ('first', 'JJ'), ('of', 'IN'), ('about', 'RB'), ('78', 'CD'), ('million', 'CD'), ('baby', 'NN'), ('boomers', 'NNS'), ('turn', 'VBP'), ('60', 'CD'), (',', ','), ('including', 'VBG'), ('two', 'CD'), ('of', 'IN'), ('my', 'PRP$'), ('Dad', 'NNP'), (\"'s\", 'POS'), ('favorite', 'JJ'), ('people', 'NNS'), ('--', ':'), ('me', 'PRP'), ('and', 'CC'), ('President', 'NNP'), ('Clinton', 'NNP'), ('.', '.')]\n[('(', '('), ('Laughter', 'NNP'), ('.', '.'), (')', ')')]\n[('This', 'DT'), ('milestone', 'NN'), ('is', 'VBZ'), ('more', 'JJR'), ('than', 'IN'), ('a', 'DT'), ('personal', 'JJ'), ('crisis', 'NN'), ('--', ':'), ('(', '('), ('laughter', 'NN'), (')', ')'), ('--', ':'), ('it', 'PRP'), ('is', 'VBZ'), ('a', 'DT'), ('national', 'JJ'), ('challenge', 'NN'), ('.', '.')]\n[('The', 'DT'), ('retirement', 'NN'), ('of', 'IN'), ('the', 'DT'), ('baby', 'NN'), ('boom', 'NN'), ('generation', 'NN'), ('will', 'MD'), ('put', 'VB'), ('unprecedented', 'JJ'), ('strains', 'NNS'), ('on', 'IN'), ('the', 'DT'), ('federal', 'JJ'), ('government', 'NN'), ('.', '.')]\n[('By', 'IN'), ('2030', 'CD'), (',', ','), ('spending', 'VBG'), ('for', 'IN'), ('Social', 'NNP'), ('Security', 'NNP'), (',', ','), ('Medicare', 'NNP'), ('and', 'CC'), ('Medicaid', 'NNP'), ('alone', 'RB'), ('will', 'MD'), ('be', 'VB'), ('almost', 'RB'), ('60', 'CD'), ('percent', 'NN'), ('of', 'IN'), ('the', 'DT'), ('entire', 'JJ'), ('federal', 'JJ'), ('budget', 'NN'), ('.', '.')]\n[('And', 'CC'), ('that', 'DT'), ('will', 'MD'), ('present', 'VB'), ('future', 'JJ'), ('Congresses', 'NNS'), ('with', 'IN'), ('impossible', 'JJ'), ('choices', 'NNS'), ('--', ':'), ('staggering', 'VBG'), ('tax', 'NN'), ('increases', 'NNS'), (',', ','), ('immense', 'JJ'), ('deficits', 'NNS'), (',', ','), ('or', 'CC'), ('deep', 'JJ'), ('cuts', 'NNS'), ('in', 'IN'), ('every', 'DT'), ('category', 'NN'), ('of', 'IN'), ('spending', 'NN'), ('.', '.')]\n[('Congress', 'NNP'), ('did', 'VBD'), ('not', 'RB'), ('act', 'VB'), ('last', 'JJ'), ('year', 'NN'), ('on', 'IN'), ('my', 'PRP$'), ('proposal', 'NN'), ('to', 'TO'), ('save', 'VB'), ('Social', 'NNP'), ('Security', 'NNP'), ('--', ':'), ('(', '('), ('applause', 'NN'), (')', ')'), ('--', ':'), ('yet', 'RB'), ('the', 'DT'), ('rising', 'VBG'), ('cost', 'NN'), ('of', 'IN'), ('entitlements', 'NNS'), ('is', 'VBZ'), ('a', 'DT'), ('problem', 'NN'), ('that', 'WDT'), ('is', 'VBZ'), ('not', 'RB'), ('going', 'VBG'), ('away', 'RB'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('And', 'CC'), ('every', 'DT'), ('year', 'NN'), ('we', 'PRP'), ('fail', 'VBP'), ('to', 'TO'), ('act', 'VB'), (',', ','), ('the', 'DT'), ('situation', 'NN'), ('gets', 'VBZ'), ('worse', 'JJR'), ('.', '.')]\n[('So', 'RB'), ('tonight', 'JJ'), (',', ','), ('I', 'PRP'), ('ask', 'VBP'), ('you', 'PRP'), ('to', 'TO'), ('join', 'VB'), ('me', 'PRP'), ('in', 'IN'), ('creating', 'VBG'), ('a', 'DT'), ('commission', 'NN'), ('to', 'TO'), ('examine', 'VB'), ('the', 'DT'), ('full', 'JJ'), ('impact', 'NN'), ('of', 'IN'), ('baby', 'NN'), ('boom', 'NN'), ('retirements', 'NNS'), ('on', 'IN'), ('Social', 'NNP'), ('Security', 'NNP'), (',', ','), ('Medicare', 'NNP'), (',', ','), ('and', 'CC'), ('Medicaid', 'NNP'), ('.', '.')]\n[('This', 'DT'), ('commission', 'NN'), ('should', 'MD'), ('include', 'VB'), ('members', 'NNS'), ('of', 'IN'), ('Congress', 'NNP'), ('of', 'IN'), ('both', 'DT'), ('parties', 'NNS'), (',', ','), ('and', 'CC'), ('offer', 'VBP'), ('bipartisan', 'JJ'), ('solutions', 'NNS'), ('.', '.')]\n[('We', 'PRP'), ('need', 'VBP'), ('to', 'TO'), ('put', 'VB'), ('aside', 'RP'), ('partisan', 'JJ'), ('politics', 'NNS'), ('and', 'CC'), ('work', 'NN'), ('together', 'RB'), ('and', 'CC'), ('get', 'VB'), ('this', 'DT'), ('problem', 'NN'), ('solved', 'VBD'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Keeping', 'VBG'), ('America', 'NNP'), ('competitive', 'JJ'), ('requires', 'VBZ'), ('us', 'PRP'), ('to', 'TO'), ('open', 'VB'), ('more', 'JJR'), ('markets', 'NNS'), ('for', 'IN'), ('all', 'DT'), ('that', 'DT'), ('Americans', 'NNPS'), ('make', 'VBP'), ('and', 'CC'), ('grow', 'VB'), ('.', '.')]\n[('One', 'CD'), ('out', 'NN'), ('of', 'IN'), ('every', 'DT'), ('five', 'CD'), ('factory', 'NN'), ('jobs', 'NNS'), ('in', 'IN'), ('America', 'NNP'), ('is', 'VBZ'), ('related', 'VBN'), ('to', 'TO'), ('global', 'JJ'), ('trade', 'NN'), (',', ','), ('and', 'CC'), ('we', 'PRP'), ('want', 'VBP'), ('people', 'NNS'), ('everywhere', 'RB'), ('to', 'TO'), ('buy', 'VB'), ('American', 'NNP'), ('.', '.')]\n[('With', 'IN'), ('open', 'JJ'), ('markets', 'NNS'), ('and', 'CC'), ('a', 'DT'), ('level', 'JJ'), ('playing', 'NN'), ('field', 'NN'), (',', ','), ('no', 'DT'), ('one', 'NN'), ('can', 'MD'), ('out-produce', 'VB'), ('or', 'CC'), ('out-compete', 'VB'), ('the', 'DT'), ('American', 'JJ'), ('worker', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Keeping', 'VBG'), ('America', 'NNP'), ('competitive', 'JJ'), ('requires', 'VBZ'), ('an', 'DT'), ('immigration', 'NN'), ('system', 'NN'), ('that', 'WDT'), ('upholds', 'VBZ'), ('our', 'PRP$'), ('laws', 'NNS'), (',', ','), ('reflects', 'VBZ'), ('our', 'PRP$'), ('values', 'NNS'), (',', ','), ('and', 'CC'), ('serves', 'VBZ'), ('the', 'DT'), ('interests', 'NNS'), ('of', 'IN'), ('our', 'PRP$'), ('economy', 'NN'), ('.', '.')]\n[('Our', 'PRP$'), ('nation', 'NN'), ('needs', 'VBZ'), ('orderly', 'JJ'), ('and', 'CC'), ('secure', 'JJ'), ('borders', 'NNS'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('To', 'TO'), ('meet', 'VB'), ('this', 'DT'), ('goal', 'NN'), (',', ','), ('we', 'PRP'), ('must', 'MD'), ('have', 'VB'), ('stronger', 'JJR'), ('immigration', 'NN'), ('enforcement', 'NN'), ('and', 'CC'), ('border', 'NN'), ('protection', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('And', 'CC'), ('we', 'PRP'), ('must', 'MD'), ('have', 'VB'), ('a', 'DT'), ('rational', 'JJ'), (',', ','), ('humane', 'JJ'), ('guest', 'JJS'), ('worker', 'NN'), ('program', 'NN'), ('that', 'WDT'), ('rejects', 'VBZ'), ('amnesty', 'JJ'), (',', ','), ('allows', 'VBZ'), ('temporary', 'JJ'), ('jobs', 'NNS'), ('for', 'IN'), ('people', 'NNS'), ('who', 'WP'), ('seek', 'VBP'), ('them', 'PRP'), ('legally', 'RB'), (',', ','), ('and', 'CC'), ('reduces', 'NNS'), ('smuggling', 'VBG'), ('and', 'CC'), ('crime', 'NN'), ('at', 'IN'), ('the', 'DT'), ('border', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Keeping', 'VBG'), ('America', 'NNP'), ('competitive', 'JJ'), ('requires', 'VBZ'), ('affordable', 'JJ'), ('health', 'NN'), ('care', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Our', 'PRP$'), ('government', 'NN'), ('has', 'VBZ'), ('a', 'DT'), ('responsibility', 'NN'), ('to', 'TO'), ('provide', 'VB'), ('health', 'NN'), ('care', 'NN'), ('for', 'IN'), ('the', 'DT'), ('poor', 'JJ'), ('and', 'CC'), ('the', 'DT'), ('elderly', 'JJ'), (',', ','), ('and', 'CC'), ('we', 'PRP'), ('are', 'VBP'), ('meeting', 'VBG'), ('that', 'IN'), ('responsibility', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('For', 'IN'), ('all', 'DT'), ('Americans', 'NNPS'), ('--', ':'), ('for', 'IN'), ('all', 'DT'), ('Americans', 'NNPS'), (',', ','), ('we', 'PRP'), ('must', 'MD'), ('confront', 'VB'), ('the', 'DT'), ('rising', 'VBG'), ('cost', 'NN'), ('of', 'IN'), ('care', 'NN'), (',', ','), ('strengthen', 'VB'), ('the', 'DT'), ('doctor-patient', 'JJ'), ('relationship', 'NN'), (',', ','), ('and', 'CC'), ('help', 'NN'), ('people', 'NNS'), ('afford', 'VBP'), ('the', 'DT'), ('insurance', 'NN'), ('coverage', 'NN'), ('they', 'PRP'), ('need', 'VBP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('We', 'PRP'), ('will', 'MD'), ('make', 'VB'), ('wider', 'JJR'), ('use', 'NN'), ('of', 'IN'), ('electronic', 'JJ'), ('records', 'NNS'), ('and', 'CC'), ('other', 'JJ'), ('health', 'NN'), ('information', 'NN'), ('technology', 'NN'), (',', ','), ('to', 'TO'), ('help', 'VB'), ('control', 'VB'), ('costs', 'NNS'), ('and', 'CC'), ('reduce', 'VB'), ('dangerous', 'JJ'), ('medical', 'JJ'), ('errors', 'NNS'), ('.', '.')]\n[('We', 'PRP'), ('will', 'MD'), ('strengthen', 'VB'), ('health', 'NN'), ('savings', 'NNS'), ('accounts', 'NNS'), ('--', ':'), ('making', 'VBG'), ('sure', 'JJ'), ('individuals', 'NNS'), ('and', 'CC'), ('small', 'JJ'), ('business', 'NN'), ('employees', 'NNS'), ('can', 'MD'), ('buy', 'VB'), ('insurance', 'NN'), ('with', 'IN'), ('the', 'DT'), ('same', 'JJ'), ('advantages', 'VBZ'), ('that', 'IN'), ('people', 'NNS'), ('working', 'VBG'), ('for', 'IN'), ('big', 'JJ'), ('businesses', 'NNS'), ('now', 'RB'), ('get', 'VBP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('We', 'PRP'), ('will', 'MD'), ('do', 'VB'), ('more', 'JJR'), ('to', 'TO'), ('make', 'VB'), ('this', 'DT'), ('coverage', 'NN'), ('portable', 'JJ'), (',', ','), ('so', 'IN'), ('workers', 'NNS'), ('can', 'MD'), ('switch', 'VB'), ('jobs', 'NNS'), ('without', 'IN'), ('having', 'VBG'), ('to', 'TO'), ('worry', 'VB'), ('about', 'IN'), ('losing', 'VBG'), ('their', 'PRP$'), ('health', 'NN'), ('insurance', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('And', 'CC'), ('because', 'IN'), ('lawsuits', 'NNS'), ('are', 'VBP'), ('driving', 'VBG'), ('many', 'JJ'), ('good', 'JJ'), ('doctors', 'NNS'), ('out', 'IN'), ('of', 'IN'), ('practice', 'NN'), ('--', ':'), ('leaving', 'VBG'), ('women', 'NNS'), ('in', 'IN'), ('nearly', 'RB'), ('1,500', 'CD'), ('American', 'JJ'), ('counties', 'NNS'), ('without', 'IN'), ('a', 'DT'), ('single', 'JJ'), ('OB/GYN', 'NNP'), ('--', ':'), ('I', 'PRP'), ('ask', 'VBP'), ('the', 'DT'), ('Congress', 'NNP'), ('to', 'TO'), ('pass', 'VB'), ('medical', 'JJ'), ('liability', 'NN'), ('reform', 'NN'), ('this', 'DT'), ('year', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Keeping', 'VBG'), ('America', 'NNP'), ('competitive', 'JJ'), ('requires', 'VBZ'), ('affordable', 'JJ'), ('energy', 'NN'), ('.', '.')]\n[('And', 'CC'), ('here', 'RB'), ('we', 'PRP'), ('have', 'VBP'), ('a', 'DT'), ('serious', 'JJ'), ('problem', 'NN'), (':', ':'), ('America', 'NNP'), ('is', 'VBZ'), ('addicted', 'VBN'), ('to', 'TO'), ('oil', 'NN'), (',', ','), ('which', 'WDT'), ('is', 'VBZ'), ('often', 'RB'), ('imported', 'VBN'), ('from', 'IN'), ('unstable', 'JJ'), ('parts', 'NNS'), ('of', 'IN'), ('the', 'DT'), ('world', 'NN'), ('.', '.')]\n[('The', 'DT'), ('best', 'JJS'), ('way', 'NN'), ('to', 'TO'), ('break', 'VB'), ('this', 'DT'), ('addiction', 'NN'), ('is', 'VBZ'), ('through', 'IN'), ('technology', 'NN'), ('.', '.')]\n[('Since', 'IN'), ('2001', 'CD'), (',', ','), ('we', 'PRP'), ('have', 'VBP'), ('spent', 'VBN'), ('nearly', 'RB'), ('$', '$'), ('10', 'CD'), ('billion', 'CD'), ('to', 'TO'), ('develop', 'VB'), ('cleaner', 'JJR'), (',', ','), ('cheaper', 'JJR'), (',', ','), ('and', 'CC'), ('more', 'RBR'), ('reliable', 'JJ'), ('alternative', 'JJ'), ('energy', 'NN'), ('sources', 'NNS'), ('--', ':'), ('and', 'CC'), ('we', 'PRP'), ('are', 'VBP'), ('on', 'IN'), ('the', 'DT'), ('threshold', 'NN'), ('of', 'IN'), ('incredible', 'JJ'), ('advances', 'NNS'), ('.', '.')]\n[('So', 'RB'), ('tonight', 'JJ'), (',', ','), ('I', 'PRP'), ('announce', 'VBP'), ('the', 'DT'), ('Advanced', 'NNP'), ('Energy', 'NNP'), ('Initiative', 'NNP'), ('--', ':'), ('a', 'DT'), ('22-percent', 'JJ'), ('increase', 'NN'), ('in', 'IN'), ('clean-energy', 'JJ'), ('research', 'NN'), ('--', ':'), ('at', 'IN'), ('the', 'DT'), ('Department', 'NNP'), ('of', 'IN'), ('Energy', 'NNP'), (',', ','), ('to', 'TO'), ('push', 'VB'), ('for', 'IN'), ('breakthroughs', 'NNS'), ('in', 'IN'), ('two', 'CD'), ('vital', 'JJ'), ('areas', 'NNS'), ('.', '.')]\n[('To', 'TO'), ('change', 'VB'), ('how', 'WRB'), ('we', 'PRP'), ('power', 'NN'), ('our', 'PRP$'), ('homes', 'NNS'), ('and', 'CC'), ('offices', 'NNS'), (',', ','), ('we', 'PRP'), ('will', 'MD'), ('invest', 'VB'), ('more', 'RBR'), ('in', 'IN'), ('zero-emission', 'JJ'), ('coal-fired', 'JJ'), ('plants', 'NNS'), (',', ','), ('revolutionary', 'JJ'), ('solar', 'NN'), ('and', 'CC'), ('wind', 'NN'), ('technologies', 'NNS'), (',', ','), ('and', 'CC'), ('clean', 'JJ'), (',', ','), ('safe', 'JJ'), ('nuclear', 'JJ'), ('energy', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('We', 'PRP'), ('must', 'MD'), ('also', 'RB'), ('change', 'VB'), ('how', 'WRB'), ('we', 'PRP'), ('power', 'NN'), ('our', 'PRP$'), ('automobiles', 'NNS'), ('.', '.')]\n[('We', 'PRP'), ('will', 'MD'), ('increase', 'VB'), ('our', 'PRP$'), ('research', 'NN'), ('in', 'IN'), ('better', 'JJR'), ('batteries', 'NNS'), ('for', 'IN'), ('hybrid', 'JJ'), ('and', 'CC'), ('electric', 'JJ'), ('cars', 'NNS'), (',', ','), ('and', 'CC'), ('in', 'IN'), ('pollution-free', 'JJ'), ('cars', 'NNS'), ('that', 'WDT'), ('run', 'VBP'), ('on', 'IN'), ('hydrogen', 'NN'), ('.', '.')]\n[('We', 'PRP'), (\"'ll\", 'MD'), ('also', 'RB'), ('fund', 'VB'), ('additional', 'JJ'), ('research', 'NN'), ('in', 'IN'), ('cutting-edge', 'JJ'), ('methods', 'NNS'), ('of', 'IN'), ('producing', 'VBG'), ('ethanol', 'NN'), (',', ','), ('not', 'RB'), ('just', 'RB'), ('from', 'IN'), ('corn', 'NN'), (',', ','), ('but', 'CC'), ('from', 'IN'), ('wood', 'NN'), ('chips', 'NNS'), ('and', 'CC'), ('stalks', 'NNS'), (',', ','), ('or', 'CC'), ('switch', 'VB'), ('grass', 'NN'), ('.', '.')]\n[('Our', 'PRP$'), ('goal', 'NN'), ('is', 'VBZ'), ('to', 'TO'), ('make', 'VB'), ('this', 'DT'), ('new', 'JJ'), ('kind', 'NN'), ('of', 'IN'), ('ethanol', 'JJ'), ('practical', 'JJ'), ('and', 'CC'), ('competitive', 'JJ'), ('within', 'IN'), ('six', 'CD'), ('years', 'NNS'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Breakthroughs', 'NNS'), ('on', 'IN'), ('this', 'DT'), ('and', 'CC'), ('other', 'JJ'), ('new', 'JJ'), ('technologies', 'NNS'), ('will', 'MD'), ('help', 'VB'), ('us', 'PRP'), ('reach', 'VB'), ('another', 'DT'), ('great', 'JJ'), ('goal', 'NN'), (':', ':'), ('to', 'TO'), ('replace', 'VB'), ('more', 'JJR'), ('than', 'IN'), ('75', 'CD'), ('percent', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('oil', 'NN'), ('imports', 'NNS'), ('from', 'IN'), ('the', 'DT'), ('Middle', 'NNP'), ('East', 'NNP'), ('by', 'IN'), ('2025', 'CD'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('By', 'IN'), ('applying', 'VBG'), ('the', 'DT'), ('talent', 'NN'), ('and', 'CC'), ('technology', 'NN'), ('of', 'IN'), ('America', 'NNP'), (',', ','), ('this', 'DT'), ('country', 'NN'), ('can', 'MD'), ('dramatically', 'RB'), ('improve', 'VB'), ('our', 'PRP$'), ('environment', 'NN'), (',', ','), ('move', 'VB'), ('beyond', 'IN'), ('a', 'DT'), ('petroleum-based', 'JJ'), ('economy', 'NN'), (',', ','), ('and', 'CC'), ('make', 'VB'), ('our', 'PRP$'), ('dependence', 'NN'), ('on', 'IN'), ('Middle', 'NNP'), ('Eastern', 'NNP'), ('oil', 'NN'), ('a', 'DT'), ('thing', 'NN'), ('of', 'IN'), ('the', 'DT'), ('past', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('And', 'CC'), ('to', 'TO'), ('keep', 'VB'), ('America', 'NNP'), ('competitive', 'JJ'), (',', ','), ('one', 'CD'), ('commitment', 'NN'), ('is', 'VBZ'), ('necessary', 'JJ'), ('above', 'IN'), ('all', 'DT'), (':', ':'), ('We', 'PRP'), ('must', 'MD'), ('continue', 'VB'), ('to', 'TO'), ('lead', 'VB'), ('the', 'DT'), ('world', 'NN'), ('in', 'IN'), ('human', 'JJ'), ('talent', 'NN'), ('and', 'CC'), ('creativity', 'NN'), ('.', '.')]\n[('Our', 'PRP$'), ('greatest', 'JJS'), ('advantage', 'NN'), ('in', 'IN'), ('the', 'DT'), ('world', 'NN'), ('has', 'VBZ'), ('always', 'RB'), ('been', 'VBN'), ('our', 'PRP$'), ('educated', 'VBN'), (',', ','), ('hardworking', 'VBG'), (',', ','), ('ambitious', 'JJ'), ('people', 'NNS'), ('--', ':'), ('and', 'CC'), ('we', 'PRP'), (\"'re\", 'VBP'), ('going', 'VBG'), ('to', 'TO'), ('keep', 'VB'), ('that', 'DT'), ('edge', 'NN'), ('.', '.')]\n[('Tonight', 'NN'), ('I', 'PRP'), ('announce', 'VBP'), ('an', 'DT'), ('American', 'JJ'), ('Competitiveness', 'NNP'), ('Initiative', 'NNP'), (',', ','), ('to', 'TO'), ('encourage', 'VB'), ('innovation', 'NN'), ('throughout', 'IN'), ('our', 'PRP$'), ('economy', 'NN'), (',', ','), ('and', 'CC'), ('to', 'TO'), ('give', 'VB'), ('our', 'PRP$'), ('nation', 'NN'), (\"'s\", 'POS'), ('children', 'NNS'), ('a', 'DT'), ('firm', 'NN'), ('grounding', 'VBG'), ('in', 'IN'), ('math', 'NN'), ('and', 'CC'), ('science', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('First', 'RB'), (',', ','), ('I', 'PRP'), ('propose', 'VBP'), ('to', 'TO'), ('double', 'VB'), ('the', 'DT'), ('federal', 'JJ'), ('commitment', 'NN'), ('to', 'TO'), ('the', 'DT'), ('most', 'RBS'), ('critical', 'JJ'), ('basic', 'JJ'), ('research', 'NN'), ('programs', 'NNS'), ('in', 'IN'), ('the', 'DT'), ('physical', 'JJ'), ('sciences', 'NNS'), ('over', 'IN'), ('the', 'DT'), ('next', 'JJ'), ('10', 'CD'), ('years', 'NNS'), ('.', '.')]\n[('This', 'DT'), ('funding', 'NN'), ('will', 'MD'), ('support', 'VB'), ('the', 'DT'), ('work', 'NN'), ('of', 'IN'), ('America', 'NNP'), (\"'s\", 'POS'), ('most', 'RBS'), ('creative', 'JJ'), ('minds', 'NNS'), ('as', 'IN'), ('they', 'PRP'), ('explore', 'VBP'), ('promising', 'VBG'), ('areas', 'NNS'), ('such', 'JJ'), ('as', 'IN'), ('nanotechnology', 'NN'), (',', ','), ('supercomputing', 'NN'), (',', ','), ('and', 'CC'), ('alternative', 'JJ'), ('energy', 'NN'), ('sources', 'NNS'), ('.', '.')]\n[('Second', 'JJ'), (',', ','), ('I', 'PRP'), ('propose', 'VBP'), ('to', 'TO'), ('make', 'VB'), ('permanent', 'JJ'), ('the', 'DT'), ('research', 'NN'), ('and', 'CC'), ('development', 'NN'), ('tax', 'NN'), ('credit', 'NN'), ('--', ':'), ('(', '('), ('applause', 'NN'), (')', ')'), ('--', ':'), ('to', 'TO'), ('encourage', 'VB'), ('bolder', 'VB'), ('private-sector', 'JJ'), ('initiatives', 'NNS'), ('in', 'IN'), ('technology', 'NN'), ('.', '.')]\n[('With', 'IN'), ('more', 'JJR'), ('research', 'NN'), ('in', 'IN'), ('both', 'CC'), ('the', 'DT'), ('public', 'NN'), ('and', 'CC'), ('private', 'JJ'), ('sectors', 'NNS'), (',', ','), ('we', 'PRP'), ('will', 'MD'), ('improve', 'VB'), ('our', 'PRP$'), ('quality', 'NN'), ('of', 'IN'), ('life', 'NN'), ('--', ':'), ('and', 'CC'), ('ensure', 'VB'), ('that', 'DT'), ('America', 'NNP'), ('will', 'MD'), ('lead', 'VB'), ('the', 'DT'), ('world', 'NN'), ('in', 'IN'), ('opportunity', 'NN'), ('and', 'CC'), ('innovation', 'NN'), ('for', 'IN'), ('decades', 'NNS'), ('to', 'TO'), ('come', 'VB'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Third', 'NNP'), (',', ','), ('we', 'PRP'), ('need', 'VBP'), ('to', 'TO'), ('encourage', 'VB'), ('children', 'NNS'), ('to', 'TO'), ('take', 'VB'), ('more', 'JJR'), ('math', 'NN'), ('and', 'CC'), ('science', 'NN'), (',', ','), ('and', 'CC'), ('to', 'TO'), ('make', 'VB'), ('sure', 'JJ'), ('those', 'DT'), ('courses', 'NNS'), ('are', 'VBP'), ('rigorous', 'JJ'), ('enough', 'RB'), ('to', 'TO'), ('compete', 'VB'), ('with', 'IN'), ('other', 'JJ'), ('nations', 'NNS'), ('.', '.')]\n[('We', 'PRP'), (\"'ve\", 'VBP'), ('made', 'VBN'), ('a', 'DT'), ('good', 'JJ'), ('start', 'NN'), ('in', 'IN'), ('the', 'DT'), ('early', 'JJ'), ('grades', 'NNS'), ('with', 'IN'), ('the', 'DT'), ('No', 'NNP'), ('Child', 'NNP'), ('Left', 'NNP'), ('Behind', 'NNP'), ('Act', 'NNP'), (',', ','), ('which', 'WDT'), ('is', 'VBZ'), ('raising', 'VBG'), ('standards', 'NNS'), ('and', 'CC'), ('lifting', 'VBG'), ('test', 'NN'), ('scores', 'NNS'), ('across', 'IN'), ('our', 'PRP$'), ('country', 'NN'), ('.', '.')]\n[('Tonight', 'NNP'), ('I', 'PRP'), ('propose', 'VBP'), ('to', 'TO'), ('train', 'VB'), ('70,000', 'CD'), ('high', 'JJ'), ('school', 'NN'), ('teachers', 'NNS'), ('to', 'TO'), ('lead', 'VB'), ('advanced-placement', 'JJ'), ('courses', 'NNS'), ('in', 'IN'), ('math', 'NN'), ('and', 'CC'), ('science', 'NN'), (',', ','), ('bring', 'VBG'), ('30,000', 'CD'), ('math', 'NN'), ('and', 'CC'), ('science', 'NN'), ('professionals', 'NNS'), ('to', 'TO'), ('teach', 'VB'), ('in', 'IN'), ('classrooms', 'NNS'), (',', ','), ('and', 'CC'), ('give', 'VB'), ('early', 'JJ'), ('help', 'NN'), ('to', 'TO'), ('students', 'NNS'), ('who', 'WP'), ('struggle', 'VBP'), ('with', 'IN'), ('math', 'NN'), (',', ','), ('so', 'IN'), ('they', 'PRP'), ('have', 'VBP'), ('a', 'DT'), ('better', 'JJR'), ('chance', 'NN'), ('at', 'IN'), ('good', 'JJ'), (',', ','), ('high-wage', 'JJ'), ('jobs', 'NNS'), ('.', '.')]\n[('If', 'IN'), ('we', 'PRP'), ('ensure', 'VB'), ('that', 'IN'), ('America', 'NNP'), (\"'s\", 'POS'), ('children', 'NNS'), ('succeed', 'VB'), ('in', 'IN'), ('life', 'NN'), (',', ','), ('they', 'PRP'), ('will', 'MD'), ('ensure', 'VB'), ('that', 'IN'), ('America', 'NNP'), ('succeeds', 'VBZ'), ('in', 'IN'), ('the', 'DT'), ('world', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Preparing', 'VBG'), ('our', 'PRP$'), ('nation', 'NN'), ('to', 'TO'), ('compete', 'VB'), ('in', 'IN'), ('the', 'DT'), ('world', 'NN'), ('is', 'VBZ'), ('a', 'DT'), ('goal', 'NN'), ('that', 'IN'), ('all', 'DT'), ('of', 'IN'), ('us', 'PRP'), ('can', 'MD'), ('share', 'NN'), ('.', '.')]\n[('I', 'PRP'), ('urge', 'VBP'), ('you', 'PRP'), ('to', 'TO'), ('support', 'VB'), ('the', 'DT'), ('American', 'JJ'), ('Competitiveness', 'NNP'), ('Initiative', 'NNP'), (',', ','), ('and', 'CC'), ('together', 'RB'), ('we', 'PRP'), ('will', 'MD'), ('show', 'VB'), ('the', 'DT'), ('world', 'NN'), ('what', 'WP'), ('the', 'DT'), ('American', 'JJ'), ('people', 'NNS'), ('can', 'MD'), ('achieve', 'VB'), ('.', '.')]\n[('America', 'NNP'), ('is', 'VBZ'), ('a', 'DT'), ('great', 'JJ'), ('force', 'NN'), ('for', 'IN'), ('freedom', 'NN'), ('and', 'CC'), ('prosperity', 'NN'), ('.', '.')]\n[('Yet', 'RB'), ('our', 'PRP$'), ('greatness', 'NN'), ('is', 'VBZ'), ('not', 'RB'), ('measured', 'VBN'), ('in', 'IN'), ('power', 'NN'), ('or', 'CC'), ('luxuries', 'NNS'), (',', ','), ('but', 'CC'), ('by', 'IN'), ('who', 'WP'), ('we', 'PRP'), ('are', 'VBP'), ('and', 'CC'), ('how', 'WRB'), ('we', 'PRP'), ('treat', 'VBP'), ('one', 'CD'), ('another', 'DT'), ('.', '.')]\n[('So', 'IN'), ('we', 'PRP'), ('strive', 'VBP'), ('to', 'TO'), ('be', 'VB'), ('a', 'DT'), ('compassionate', 'NN'), (',', ','), ('decent', 'NN'), (',', ','), ('hopeful', 'JJ'), ('society', 'NN'), ('.', '.')]\n[('In', 'IN'), ('recent', 'JJ'), ('years', 'NNS'), (',', ','), ('America', 'NNP'), ('has', 'VBZ'), ('become', 'VBN'), ('a', 'DT'), ('more', 'RBR'), ('hopeful', 'JJ'), ('nation', 'NN'), ('.', '.')]\n[('Violent', 'JJ'), ('crime', 'NN'), ('rates', 'NNS'), ('have', 'VBP'), ('fallen', 'VBN'), ('to', 'TO'), ('their', 'PRP$'), ('lowest', 'JJS'), ('levels', 'NNS'), ('since', 'IN'), ('the', 'DT'), ('1970s', 'CD'), ('.', '.')]\n[('Welfare', 'NN'), ('cases', 'NNS'), ('have', 'VBP'), ('dropped', 'VBN'), ('by', 'IN'), ('more', 'JJR'), ('than', 'IN'), ('half', 'NN'), ('over', 'IN'), ('the', 'DT'), ('past', 'JJ'), ('decade', 'NN'), ('.', '.')]\n[('Drug', 'NN'), ('use', 'NN'), ('among', 'IN'), ('youth', 'NN'), ('is', 'VBZ'), ('down', 'RB'), ('19', 'CD'), ('percent', 'NN'), ('since', 'IN'), ('2001', 'CD'), ('.', '.')]\n[('There', 'EX'), ('are', 'VBP'), ('fewer', 'JJR'), ('abortions', 'NNS'), ('in', 'IN'), ('America', 'NNP'), ('than', 'IN'), ('at', 'IN'), ('any', 'DT'), ('point', 'NN'), ('in', 'IN'), ('the', 'DT'), ('last', 'JJ'), ('three', 'CD'), ('decades', 'NNS'), (',', ','), ('and', 'CC'), ('the', 'DT'), ('number', 'NN'), ('of', 'IN'), ('children', 'NNS'), ('born', 'VBN'), ('to', 'TO'), ('teenage', 'VB'), ('mothers', 'NNS'), ('has', 'VBZ'), ('been', 'VBN'), ('falling', 'VBG'), ('for', 'IN'), ('a', 'DT'), ('dozen', 'NN'), ('years', 'NNS'), ('in', 'IN'), ('a', 'DT'), ('row', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('These', 'DT'), ('gains', 'NNS'), ('are', 'VBP'), ('evidence', 'NN'), ('of', 'IN'), ('a', 'DT'), ('quiet', 'JJ'), ('transformation', 'NN'), ('--', ':'), ('a', 'DT'), ('revolution', 'NN'), ('of', 'IN'), ('conscience', 'NN'), (',', ','), ('in', 'IN'), ('which', 'WDT'), ('a', 'DT'), ('rising', 'VBG'), ('generation', 'NN'), ('is', 'VBZ'), ('finding', 'VBG'), ('that', 'IN'), ('a', 'DT'), ('life', 'NN'), ('of', 'IN'), ('personal', 'JJ'), ('responsibility', 'NN'), ('is', 'VBZ'), ('a', 'DT'), ('life', 'NN'), ('of', 'IN'), ('fulfillment', 'NN'), ('.', '.')]\n[('Government', 'NNP'), ('has', 'VBZ'), ('played', 'VBN'), ('a', 'DT'), ('role', 'NN'), ('.', '.')]\n[('Wise', 'NNP'), ('policies', 'NNS'), (',', ','), ('such', 'JJ'), ('as', 'IN'), ('welfare', 'NN'), ('reform', 'NN'), ('and', 'CC'), ('drug', 'NN'), ('education', 'NN'), ('and', 'CC'), ('support', 'NN'), ('for', 'IN'), ('abstinence', 'NN'), ('and', 'CC'), ('adoption', 'NN'), ('have', 'VBP'), ('made', 'VBN'), ('a', 'DT'), ('difference', 'NN'), ('in', 'IN'), ('the', 'DT'), ('character', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('country', 'NN'), ('.', '.')]\n[('And', 'CC'), ('everyone', 'NN'), ('here', 'RB'), ('tonight', 'RB'), (',', ','), ('Democrat', 'NNP'), ('and', 'CC'), ('Republican', 'NNP'), (',', ','), ('has', 'VBZ'), ('a', 'DT'), ('right', 'NN'), ('to', 'TO'), ('be', 'VB'), ('proud', 'JJ'), ('of', 'IN'), ('this', 'DT'), ('record', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Yet', 'RB'), ('many', 'JJ'), ('Americans', 'NNPS'), (',', ','), ('especially', 'RB'), ('parents', 'NNS'), (',', ','), ('still', 'RB'), ('have', 'VBP'), ('deep', 'JJ'), ('concerns', 'NNS'), ('about', 'IN'), ('the', 'DT'), ('direction', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('culture', 'NN'), (',', ','), ('and', 'CC'), ('the', 'DT'), ('health', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('most', 'JJS'), ('basic', 'JJ'), ('institutions', 'NNS'), ('.', '.')]\n[('They', 'PRP'), (\"'re\", 'VBP'), ('concerned', 'VBN'), ('about', 'IN'), ('unethical', 'JJ'), ('conduct', 'NN'), ('by', 'IN'), ('public', 'JJ'), ('officials', 'NNS'), (',', ','), ('and', 'CC'), ('discouraged', 'VBN'), ('by', 'IN'), ('activist', 'NN'), ('courts', 'NNS'), ('that', 'WDT'), ('try', 'VBP'), ('to', 'TO'), ('redefine', 'VB'), ('marriage', 'NN'), ('.', '.')]\n[('They', 'PRP'), ('worry', 'VBP'), ('about', 'IN'), ('children', 'NNS'), ('in', 'IN'), ('our', 'PRP$'), ('society', 'NN'), ('who', 'WP'), ('need', 'VBP'), ('direction', 'NN'), ('and', 'CC'), ('love', 'NN'), (',', ','), ('and', 'CC'), ('about', 'IN'), ('fellow', 'JJ'), ('citizens', 'NNS'), ('still', 'RB'), ('displaced', 'VBN'), ('by', 'IN'), ('natural', 'JJ'), ('disaster', 'NN'), (',', ','), ('and', 'CC'), ('about', 'IN'), ('suffering', 'VBG'), ('caused', 'VBN'), ('by', 'IN'), ('treatable', 'JJ'), ('diseases', 'NNS'), ('.', '.')]\n[('As', 'IN'), ('we', 'PRP'), ('look', 'VBP'), ('at', 'IN'), ('these', 'DT'), ('challenges', 'NNS'), (',', ','), ('we', 'PRP'), ('must', 'MD'), ('never', 'RB'), ('give', 'VB'), ('in', 'IN'), ('to', 'TO'), ('the', 'DT'), ('belief', 'NN'), ('that', 'IN'), ('America', 'NNP'), ('is', 'VBZ'), ('in', 'IN'), ('decline', 'NN'), (',', ','), ('or', 'CC'), ('that', 'IN'), ('our', 'PRP$'), ('culture', 'NN'), ('is', 'VBZ'), ('doomed', 'VBN'), ('to', 'TO'), ('unravel', 'VB'), ('.', '.')]\n[('The', 'DT'), ('American', 'JJ'), ('people', 'NNS'), ('know', 'VBP'), ('better', 'JJR'), ('than', 'IN'), ('that', 'DT'), ('.', '.')]\n[('We', 'PRP'), ('have', 'VBP'), ('proven', 'VBN'), ('the', 'DT'), ('pessimists', 'NNS'), ('wrong', 'JJ'), ('before', 'RB'), ('--', ':'), ('and', 'CC'), ('we', 'PRP'), ('will', 'MD'), ('do', 'VB'), ('it', 'PRP'), ('again', 'RB'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('A', 'DT'), ('hopeful', 'JJ'), ('society', 'NN'), ('depends', 'VBZ'), ('on', 'IN'), ('courts', 'NNS'), ('that', 'IN'), ('deliver', 'VBP'), ('equal', 'JJ'), ('justice', 'NN'), ('under', 'IN'), ('the', 'DT'), ('law', 'NN'), ('.', '.')]\n[('The', 'DT'), ('Supreme', 'NNP'), ('Court', 'NNP'), ('now', 'RB'), ('has', 'VBZ'), ('two', 'CD'), ('superb', 'JJ'), ('new', 'JJ'), ('members', 'NNS'), ('--', ':'), ('new', 'JJ'), ('members', 'NNS'), ('on', 'IN'), ('its', 'PRP$'), ('bench', 'NN'), (':', ':'), ('Chief', 'JJ'), ('Justice', 'NNP'), ('John', 'NNP'), ('Roberts', 'NNP'), ('and', 'CC'), ('Justice', 'NNP'), ('Sam', 'NNP'), ('Alito', 'NNP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('I', 'PRP'), ('thank', 'VBD'), ('the', 'DT'), ('Senate', 'NNP'), ('for', 'IN'), ('confirming', 'VBG'), ('both', 'DT'), ('of', 'IN'), ('them', 'PRP'), ('.', '.')]\n[('I', 'PRP'), ('will', 'MD'), ('continue', 'VB'), ('to', 'TO'), ('nominate', 'VB'), ('men', 'NNS'), ('and', 'CC'), ('women', 'NNS'), ('who', 'WP'), ('understand', 'VBP'), ('that', 'IN'), ('judges', 'NNS'), ('must', 'MD'), ('be', 'VB'), ('servants', 'NNS'), ('of', 'IN'), ('the', 'DT'), ('law', 'NN'), (',', ','), ('and', 'CC'), ('not', 'RB'), ('legislate', 'VB'), ('from', 'IN'), ('the', 'DT'), ('bench', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Today', 'NN'), ('marks', 'VBZ'), ('the', 'DT'), ('official', 'JJ'), ('retirement', 'NN'), ('of', 'IN'), ('a', 'DT'), ('very', 'RB'), ('special', 'JJ'), ('American', 'NNP'), ('.', '.')]\n[('For', 'IN'), ('24', 'CD'), ('years', 'NNS'), ('of', 'IN'), ('faithful', 'JJ'), ('service', 'NN'), ('to', 'TO'), ('our', 'PRP$'), ('nation', 'NN'), (',', ','), ('the', 'DT'), ('United', 'NNP'), ('States', 'NNPS'), ('is', 'VBZ'), ('grateful', 'JJ'), ('to', 'TO'), ('Justice', 'NNP'), ('Sandra', 'NNP'), ('Day', 'NNP'), (\"O'Connor\", 'NNP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('A', 'DT'), ('hopeful', 'JJ'), ('society', 'NN'), ('has', 'VBZ'), ('institutions', 'NNS'), ('of', 'IN'), ('science', 'NN'), ('and', 'CC'), ('medicine', 'NN'), ('that', 'WDT'), ('do', 'VBP'), ('not', 'RB'), ('cut', 'VB'), ('ethical', 'JJ'), ('corners', 'NNS'), (',', ','), ('and', 'CC'), ('that', 'IN'), ('recognize', 'VBP'), ('the', 'DT'), ('matchless', 'NN'), ('value', 'NN'), ('of', 'IN'), ('every', 'DT'), ('life', 'NN'), ('.', '.')]\n[('Tonight', 'NNP'), ('I', 'PRP'), ('ask', 'VBP'), ('you', 'PRP'), ('to', 'TO'), ('pass', 'VB'), ('legislation', 'NN'), ('to', 'TO'), ('prohibit', 'VB'), ('the', 'DT'), ('most', 'RBS'), ('egregious', 'JJ'), ('abuses', 'NNS'), ('of', 'IN'), ('medical', 'JJ'), ('research', 'NN'), (':', ':'), ('human', 'JJ'), ('cloning', 'VBG'), ('in', 'IN'), ('all', 'DT'), ('its', 'PRP$'), ('forms', 'NNS'), (',', ','), ('creating', 'VBG'), ('or', 'CC'), ('implanting', 'VBG'), ('embryos', 'NN'), ('for', 'IN'), ('experiments', 'NNS'), (',', ','), ('creating', 'VBG'), ('human-animal', 'JJ'), ('hybrids', 'NNS'), (',', ','), ('and', 'CC'), ('buying', 'NN'), (',', ','), ('selling', 'NN'), (',', ','), ('or', 'CC'), ('patenting', 'VBG'), ('human', 'JJ'), ('embryos', 'NN'), ('.', '.')]\n[('Human', 'NNP'), ('life', 'NN'), ('is', 'VBZ'), ('a', 'DT'), ('gift', 'NN'), ('from', 'IN'), ('our', 'PRP$'), ('Creator', 'NNP'), ('--', ':'), ('and', 'CC'), ('that', 'IN'), ('gift', 'NN'), ('should', 'MD'), ('never', 'RB'), ('be', 'VB'), ('discarded', 'VBN'), (',', ','), ('devalued', 'VBD'), ('or', 'CC'), ('put', 'VB'), ('up', 'RP'), ('for', 'IN'), ('sale', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('A', 'DT'), ('hopeful', 'JJ'), ('society', 'NN'), ('expects', 'VBZ'), ('elected', 'VBN'), ('officials', 'NNS'), ('to', 'TO'), ('uphold', 'VB'), ('the', 'DT'), ('public', 'JJ'), ('trust', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Honorable', 'JJ'), ('people', 'NNS'), ('in', 'IN'), ('both', 'DT'), ('parties', 'NNS'), ('are', 'VBP'), ('working', 'VBG'), ('on', 'IN'), ('reforms', 'NNS'), ('to', 'TO'), ('strengthen', 'VB'), ('the', 'DT'), ('ethical', 'JJ'), ('standards', 'NNS'), ('of', 'IN'), ('Washington', 'NNP'), ('--', ':'), ('I', 'PRP'), ('support', 'VBP'), ('your', 'PRP$'), ('efforts', 'NNS'), ('.', '.')]\n[('Each', 'DT'), ('of', 'IN'), ('us', 'PRP'), ('has', 'VBZ'), ('made', 'VBN'), ('a', 'DT'), ('pledge', 'NN'), ('to', 'TO'), ('be', 'VB'), ('worthy', 'JJ'), ('of', 'IN'), ('public', 'JJ'), ('responsibility', 'NN'), ('--', ':'), ('and', 'CC'), ('that', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('pledge', 'NN'), ('we', 'PRP'), ('must', 'MD'), ('never', 'RB'), ('forget', 'VB'), (',', ','), ('never', 'RB'), ('dismiss', 'NN'), (',', ','), ('and', 'CC'), ('never', 'RB'), ('betray', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('As', 'IN'), ('we', 'PRP'), ('renew', 'VBP'), ('the', 'DT'), ('promise', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('institutions', 'NNS'), (',', ','), ('let', 'VB'), ('us', 'PRP'), ('also', 'RB'), ('show', 'VBP'), ('the', 'DT'), ('character', 'NN'), ('of', 'IN'), ('America', 'NNP'), ('in', 'IN'), ('our', 'PRP$'), ('compassion', 'NN'), ('and', 'CC'), ('care', 'NN'), ('for', 'IN'), ('one', 'CD'), ('another', 'DT'), ('.', '.')]\n[('A', 'DT'), ('hopeful', 'JJ'), ('society', 'NN'), ('gives', 'VBZ'), ('special', 'JJ'), ('attention', 'NN'), ('to', 'TO'), ('children', 'NNS'), ('who', 'WP'), ('lack', 'VBP'), ('direction', 'NN'), ('and', 'CC'), ('love', 'NN'), ('.', '.')]\n[('Through', 'IN'), ('the', 'DT'), ('Helping', 'NNP'), ('America', 'NNP'), (\"'s\", 'POS'), ('Youth', 'NNP'), ('Initiative', 'NNP'), (',', ','), ('we', 'PRP'), ('are', 'VBP'), ('encouraging', 'VBG'), ('caring', 'VBG'), ('adults', 'NNS'), ('to', 'TO'), ('get', 'VB'), ('involved', 'VBN'), ('in', 'IN'), ('the', 'DT'), ('life', 'NN'), ('of', 'IN'), ('a', 'DT'), ('child', 'NN'), ('--', ':'), ('and', 'CC'), ('this', 'DT'), ('good', 'JJ'), ('work', 'NN'), ('is', 'VBZ'), ('being', 'VBG'), ('led', 'VBN'), ('by', 'IN'), ('our', 'PRP$'), ('First', 'NNP'), ('Lady', 'NNP'), (',', ','), ('Laura', 'NNP'), ('Bush', 'NNP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('This', 'DT'), ('year', 'NN'), ('we', 'PRP'), ('will', 'MD'), ('add', 'VB'), ('resources', 'NNS'), ('to', 'TO'), ('encourage', 'VB'), ('young', 'JJ'), ('people', 'NNS'), ('to', 'TO'), ('stay', 'VB'), ('in', 'IN'), ('school', 'NN'), (',', ','), ('so', 'RB'), ('more', 'JJR'), ('of', 'IN'), ('America', 'NNP'), (\"'s\", 'POS'), ('youth', 'NN'), ('can', 'MD'), ('raise', 'VB'), ('their', 'PRP$'), ('sights', 'NNS'), ('and', 'CC'), ('achieve', 'VBP'), ('their', 'PRP$'), ('dreams', 'NNS'), ('.', '.')]\n[('A', 'DT'), ('hopeful', 'JJ'), ('society', 'NN'), ('comes', 'VBZ'), ('to', 'TO'), ('the', 'DT'), ('aid', 'NN'), ('of', 'IN'), ('fellow', 'JJ'), ('citizens', 'NNS'), ('in', 'IN'), ('times', 'NNS'), ('of', 'IN'), ('suffering', 'NN'), ('and', 'CC'), ('emergency', 'NN'), ('--', ':'), ('and', 'CC'), ('stays', 'NNS'), ('at', 'IN'), ('it', 'PRP'), ('until', 'IN'), ('they', 'PRP'), (\"'re\", 'VBP'), ('back', 'RB'), ('on', 'IN'), ('their', 'PRP$'), ('feet', 'NNS'), ('.', '.')]\n[('So', 'RB'), ('far', 'RB'), ('the', 'DT'), ('federal', 'JJ'), ('government', 'NN'), ('has', 'VBZ'), ('committed', 'VBN'), ('$', '$'), ('85', 'CD'), ('billion', 'CD'), ('to', 'TO'), ('the', 'DT'), ('people', 'NNS'), ('of', 'IN'), ('the', 'DT'), ('Gulf', 'NNP'), ('Coast', 'NNP'), ('and', 'CC'), ('New', 'NNP'), ('Orleans', 'NNP'), ('.', '.')]\n[('We', 'PRP'), (\"'re\", 'VBP'), ('removing', 'VBG'), ('debris', 'NN'), ('and', 'CC'), ('repairing', 'NN'), ('highways', 'NNS'), ('and', 'CC'), ('rebuilding', 'VBG'), ('stronger', 'JJR'), ('levees', 'NNS'), ('.', '.')]\n[('We', 'PRP'), (\"'re\", 'VBP'), ('providing', 'VBG'), ('business', 'NN'), ('loans', 'NNS'), ('and', 'CC'), ('housing', 'NN'), ('assistance', 'NN'), ('.', '.')]\n[('Yet', 'RB'), ('as', 'IN'), ('we', 'PRP'), ('meet', 'VBP'), ('these', 'DT'), ('immediate', 'JJ'), ('needs', 'NNS'), (',', ','), ('we', 'PRP'), ('must', 'MD'), ('also', 'RB'), ('address', 'VB'), ('deeper', 'JJR'), ('challenges', 'NNS'), ('that', 'WDT'), ('existed', 'VBD'), ('before', 'IN'), ('the', 'DT'), ('storm', 'NN'), ('arrived', 'VBD'), ('.', '.')]\n[('In', 'IN'), ('New', 'NNP'), ('Orleans', 'NNP'), ('and', 'CC'), ('in', 'IN'), ('other', 'JJ'), ('places', 'NNS'), (',', ','), ('many', 'JJ'), ('of', 'IN'), ('our', 'PRP$'), ('fellow', 'JJ'), ('citizens', 'NNS'), ('have', 'VBP'), ('felt', 'VBN'), ('excluded', 'VBN'), ('from', 'IN'), ('the', 'DT'), ('promise', 'NN'), ('of', 'IN'), ('our', 'PRP$'), ('country', 'NN'), ('.', '.')]\n[('The', 'DT'), ('answer', 'NN'), ('is', 'VBZ'), ('not', 'RB'), ('only', 'RB'), ('temporary', 'JJ'), ('relief', 'NN'), (',', ','), ('but', 'CC'), ('schools', 'NNS'), ('that', 'WDT'), ('teach', 'VBP'), ('every', 'DT'), ('child', 'NN'), (',', ','), ('and', 'CC'), ('job', 'NN'), ('skills', 'NNS'), ('that', 'IN'), ('bring', 'VBG'), ('upward', 'JJ'), ('mobility', 'NN'), (',', ','), ('and', 'CC'), ('more', 'JJR'), ('opportunities', 'NNS'), ('to', 'TO'), ('own', 'VB'), ('a', 'DT'), ('home', 'NN'), ('and', 'CC'), ('start', 'VB'), ('a', 'DT'), ('business', 'NN'), ('.', '.')]\n[('As', 'IN'), ('we', 'PRP'), ('recover', 'VBP'), ('from', 'IN'), ('a', 'DT'), ('disaster', 'NN'), (',', ','), ('let', 'VB'), ('us', 'PRP'), ('also', 'RB'), ('work', 'NN'), ('for', 'IN'), ('the', 'DT'), ('day', 'NN'), ('when', 'WRB'), ('all', 'DT'), ('Americans', 'NNPS'), ('are', 'VBP'), ('protected', 'VBN'), ('by', 'IN'), ('justice', 'NN'), (',', ','), ('equal', 'JJ'), ('in', 'IN'), ('hope', 'NN'), (',', ','), ('and', 'CC'), ('rich', 'JJ'), ('in', 'IN'), ('opportunity', 'NN'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('A', 'DT'), ('hopeful', 'JJ'), ('society', 'NN'), ('acts', 'NNS'), ('boldly', 'RB'), ('to', 'TO'), ('fight', 'VB'), ('diseases', 'NNS'), ('like', 'IN'), ('HIV/AIDS', 'NNP'), (',', ','), ('which', 'WDT'), ('can', 'MD'), ('be', 'VB'), ('prevented', 'VBN'), (',', ','), ('and', 'CC'), ('treated', 'VBD'), (',', ','), ('and', 'CC'), ('defeated', 'VBD'), ('.', '.')]\n[('More', 'JJR'), ('than', 'IN'), ('a', 'DT'), ('million', 'CD'), ('Americans', 'NNPS'), ('live', 'VBP'), ('with', 'IN'), ('HIV', 'NNP'), (',', ','), ('and', 'CC'), ('half', 'NN'), ('of', 'IN'), ('all', 'DT'), ('AIDS', 'NNP'), ('cases', 'NNS'), ('occur', 'VBP'), ('among', 'IN'), ('African', 'JJ'), ('Americans', 'NNPS'), ('.', '.')]\n[('I', 'PRP'), ('ask', 'VBP'), ('Congress', 'NNP'), ('to', 'TO'), ('reform', 'VB'), ('and', 'CC'), ('reauthorize', 'VB'), ('the', 'DT'), ('Ryan', 'NNP'), ('White', 'NNP'), ('Act', 'NNP'), (',', ','), ('and', 'CC'), ('provide', 'VB'), ('new', 'JJ'), ('funding', 'NN'), ('to', 'TO'), ('states', 'NNS'), (',', ','), ('so', 'IN'), ('we', 'PRP'), ('end', 'VBP'), ('the', 'DT'), ('waiting', 'NN'), ('lists', 'NNS'), ('for', 'IN'), ('AIDS', 'NNP'), ('medicines', 'NNS'), ('in', 'IN'), ('America', 'NNP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('We', 'PRP'), ('will', 'MD'), ('also', 'RB'), ('lead', 'VB'), ('a', 'DT'), ('nationwide', 'JJ'), ('effort', 'NN'), (',', ','), ('working', 'VBG'), ('closely', 'RB'), ('with', 'IN'), ('African', 'JJ'), ('American', 'JJ'), ('churches', 'NNS'), ('and', 'CC'), ('faith-based', 'JJ'), ('groups', 'NNS'), (',', ','), ('to', 'TO'), ('deliver', 'VB'), ('rapid', 'JJ'), ('HIV', 'NNP'), ('tests', 'NNS'), ('to', 'TO'), ('millions', 'NNS'), (',', ','), ('end', 'VBP'), ('the', 'DT'), ('stigma', 'NN'), ('of', 'IN'), ('AIDS', 'NNP'), (',', ','), ('and', 'CC'), ('come', 'VB'), ('closer', 'JJR'), ('to', 'TO'), ('the', 'DT'), ('day', 'NN'), ('when', 'WRB'), ('there', 'EX'), ('are', 'VBP'), ('no', 'DT'), ('new', 'JJ'), ('infections', 'NNS'), ('in', 'IN'), ('America', 'NNP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('Fellow', 'NNP'), ('citizens', 'NNS'), (',', ','), ('we', 'PRP'), (\"'ve\", 'VBP'), ('been', 'VBN'), ('called', 'VBN'), ('to', 'TO'), ('leadership', 'NN'), ('in', 'IN'), ('a', 'DT'), ('period', 'NN'), ('of', 'IN'), ('consequence', 'NN'), ('.', '.')]\n[('We', 'PRP'), (\"'ve\", 'VBP'), ('entered', 'VBN'), ('a', 'DT'), ('great', 'JJ'), ('ideological', 'JJ'), ('conflict', 'NN'), ('we', 'PRP'), ('did', 'VBD'), ('nothing', 'NN'), ('to', 'TO'), ('invite', 'VB'), ('.', '.')]\n[('We', 'PRP'), ('see', 'VBP'), ('great', 'JJ'), ('changes', 'NNS'), ('in', 'IN'), ('science', 'NN'), ('and', 'CC'), ('commerce', 'NN'), ('that', 'WDT'), ('will', 'MD'), ('influence', 'VB'), ('all', 'DT'), ('our', 'PRP$'), ('lives', 'NNS'), ('.', '.')]\n[('Sometimes', 'RB'), ('it', 'PRP'), ('can', 'MD'), ('seem', 'VB'), ('that', 'DT'), ('history', 'NN'), ('is', 'VBZ'), ('turning', 'VBG'), ('in', 'IN'), ('a', 'DT'), ('wide', 'JJ'), ('arc', 'NN'), (',', ','), ('toward', 'IN'), ('an', 'DT'), ('unknown', 'JJ'), ('shore', 'NN'), ('.', '.')]\n[('Yet', 'CC'), ('the', 'DT'), ('destination', 'NN'), ('of', 'IN'), ('history', 'NN'), ('is', 'VBZ'), ('determined', 'VBN'), ('by', 'IN'), ('human', 'JJ'), ('action', 'NN'), (',', ','), ('and', 'CC'), ('every', 'DT'), ('great', 'JJ'), ('movement', 'NN'), ('of', 'IN'), ('history', 'NN'), ('comes', 'VBZ'), ('to', 'TO'), ('a', 'DT'), ('point', 'NN'), ('of', 'IN'), ('choosing', 'NN'), ('.', '.')]\n[('Lincoln', 'NNP'), ('could', 'MD'), ('have', 'VB'), ('accepted', 'VBN'), ('peace', 'NN'), ('at', 'IN'), ('the', 'DT'), ('cost', 'NN'), ('of', 'IN'), ('disunity', 'NN'), ('and', 'CC'), ('continued', 'JJ'), ('slavery', 'NN'), ('.', '.')]\n[('Martin', 'NNP'), ('Luther', 'NNP'), ('King', 'NNP'), ('could', 'MD'), ('have', 'VB'), ('stopped', 'VBN'), ('at', 'IN'), ('Birmingham', 'NNP'), ('or', 'CC'), ('at', 'IN'), ('Selma', 'NNP'), (',', ','), ('and', 'CC'), ('achieved', 'VBD'), ('only', 'RB'), ('half', 'PDT'), ('a', 'DT'), ('victory', 'NN'), ('over', 'IN'), ('segregation', 'NN'), ('.', '.')]\n[('The', 'DT'), ('United', 'NNP'), ('States', 'NNPS'), ('could', 'MD'), ('have', 'VB'), ('accepted', 'VBN'), ('the', 'DT'), ('permanent', 'JJ'), ('division', 'NN'), ('of', 'IN'), ('Europe', 'NNP'), (',', ','), ('and', 'CC'), ('been', 'VBN'), ('complicit', 'NNS'), ('in', 'IN'), ('the', 'DT'), ('oppression', 'NN'), ('of', 'IN'), ('others', 'NNS'), ('.', '.')]\n[('Today', 'NN'), (',', ','), ('having', 'VBG'), ('come', 'VBN'), ('far', 'RB'), ('in', 'IN'), ('our', 'PRP$'), ('own', 'JJ'), ('historical', 'JJ'), ('journey', 'NN'), (',', ','), ('we', 'PRP'), ('must', 'MD'), ('decide', 'VB'), (':', ':'), ('Will', 'MD'), ('we', 'PRP'), ('turn', 'VB'), ('back', 'RP'), (',', ','), ('or', 'CC'), ('finish', 'VB'), ('well', 'RB'), ('?', '.')]\n[('Before', 'IN'), ('history', 'NN'), ('is', 'VBZ'), ('written', 'VBN'), ('down', 'RP'), ('in', 'IN'), ('books', 'NNS'), (',', ','), ('it', 'PRP'), ('is', 'VBZ'), ('written', 'VBN'), ('in', 'IN'), ('courage', 'NN'), ('.', '.')]\n[('Like', 'IN'), ('Americans', 'NNPS'), ('before', 'IN'), ('us', 'PRP'), (',', ','), ('we', 'PRP'), ('will', 'MD'), ('show', 'VB'), ('that', 'DT'), ('courage', 'NN'), ('and', 'CC'), ('we', 'PRP'), ('will', 'MD'), ('finish', 'VB'), ('well', 'RB'), ('.', '.')]\n[('We', 'PRP'), ('will', 'MD'), ('lead', 'VB'), ('freedom', 'NN'), (\"'s\", 'POS'), ('advance', 'NN'), ('.', '.')]\n[('We', 'PRP'), ('will', 'MD'), ('compete', 'VB'), ('and', 'CC'), ('excel', 'VB'), ('in', 'IN'), ('the', 'DT'), ('global', 'JJ'), ('economy', 'NN'), ('.', '.')]\n[('We', 'PRP'), ('will', 'MD'), ('renew', 'VB'), ('the', 'DT'), ('defining', 'VBG'), ('moral', 'JJ'), ('commitments', 'NNS'), ('of', 'IN'), ('this', 'DT'), ('land', 'NN'), ('.', '.')]\n[('And', 'CC'), ('so', 'RB'), ('we', 'PRP'), ('move', 'VBP'), ('forward', 'RB'), ('--', ':'), ('optimistic', 'JJ'), ('about', 'IN'), ('our', 'PRP$'), ('country', 'NN'), (',', ','), ('faithful', 'JJ'), ('to', 'TO'), ('its', 'PRP$'), ('cause', 'NN'), (',', ','), ('and', 'CC'), ('confident', 'NN'), ('of', 'IN'), ('the', 'DT'), ('victories', 'NNS'), ('to', 'TO'), ('come', 'VB'), ('.', '.')]\n[('May', 'NNP'), ('God', 'NNP'), ('bless', 'NN'), ('America', 'NNP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n"
],
[
"",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
e721a00d1d4e24c6e76e47f641d60b790b76bc23 | 5,066 | ipynb | Jupyter Notebook | 07_Visualization/Scores/Exercises.ipynb | isisfisica/pandas_exercises | 7abaf157db239b1da502f978e565eff90968ce2c | [
"BSD-3-Clause"
] | null | null | null | 07_Visualization/Scores/Exercises.ipynb | isisfisica/pandas_exercises | 7abaf157db239b1da502f978e565eff90968ce2c | [
"BSD-3-Clause"
] | null | null | null | 07_Visualization/Scores/Exercises.ipynb | isisfisica/pandas_exercises | 7abaf157db239b1da502f978e565eff90968ce2c | [
"BSD-3-Clause"
] | null | null | null | 23.453704 | 122 | 0.406632 | [
[
[
"# Scores",
"_____no_output_____"
],
[
"### Step 2. Create the DataFrame that should look like the one below.",
"_____no_output_____"
],
[
"### Introduction:\n\nThis time you will create the data.\n\n***Exercise based on [Chris Albon](http://chrisalbon.com/) work, the credits belong to him.***\n\n### Step 1. Import the necessary libraries",
"_____no_output_____"
],
[
"### Step 3. Create a Scatterplot of preTestScore and postTestScore, with the size of each point determined by age\n#### Hint: Don't forget to place the labels",
"_____no_output_____"
],
[
"### Step 4. Create a Scatterplot of preTestScore and postTestScore.\n### This time the size should be 4.5 times the postTestScore and the color determined by sex",
"_____no_output_____"
],
[
"### BONUS: Create your own question and answer it.",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e721abd3260766869417e8412a48531fcf887734 | 9,884 | ipynb | Jupyter Notebook | docs/ipynb/image_classification.ipynb | Leo2691/autokeras | 5343a38fffa10e41e69af361fe65119e3b6b5a31 | [
"MIT"
] | null | null | null | docs/ipynb/image_classification.ipynb | Leo2691/autokeras | 5343a38fffa10e41e69af361fe65119e3b6b5a31 | [
"MIT"
] | null | null | null | docs/ipynb/image_classification.ipynb | Leo2691/autokeras | 5343a38fffa10e41e69af361fe65119e3b6b5a31 | [
"MIT"
] | null | null | null | 28.816327 | 96 | 0.58013 | [
[
[
"!pip install autokeras\n!pip install git+https://github.com/keras-team/[email protected]\n",
"_____no_output_____"
]
],
[
[
"## A Simple Example\nThe first step is to prepare your data. Here we use the MNIST dataset as an example\n",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.python.keras.utils.data_utils import Sequence\nimport autokeras as ak\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nprint(x_train.shape) # (60000, 28, 28)\nprint(y_train.shape) # (60000,)\nprint(y_train[:3]) # array([7, 2, 1], dtype=uint8)\n",
"_____no_output_____"
]
],
[
[
"The second step is to run the ImageClassifier.\nIt is recommended have more trials for more complicated datasets.\nThis is just a quick demo of MNIST, so we set max_trials to 1.\n",
"_____no_output_____"
]
],
[
[
"# Initialize the image classifier.\nclf = ak.ImageClassifier(\n overwrite=True,\n max_trials=1)\n# Feed the image classifier with training data.\nclf.fit(x_train, y_train, epochs=10)\n\n\n# Predict with the best model.\npredicted_y = clf.predict(x_test)\nprint(predicted_y)\n\n\n# Evaluate the best model with testing data.\nprint(clf.evaluate(x_test, y_test))\n",
"_____no_output_____"
]
],
[
[
"## Validation Data\nBy default, AutoKeras use the last 20% of training data as validation data. As shown in\nthe example below, you can use validation_split to specify the percentage.\n",
"_____no_output_____"
]
],
[
[
"clf.fit(\n x_train,\n y_train,\n # Split the training data and use the last 15% as validation data.\n validation_split=0.15,\n epochs=10,\n)\n",
"_____no_output_____"
]
],
[
[
"You can also use your own validation set instead of splitting it from the training data\nwith validation_data.\n",
"_____no_output_____"
]
],
[
[
"split = 50000\nx_val = x_train[split:]\ny_val = y_train[split:]\nx_train = x_train[:split]\ny_train = y_train[:split]\nclf.fit(\n x_train,\n y_train,\n # Use your own validation set.\n validation_data=(x_val, y_val),\n epochs=10,\n)\n",
"_____no_output_____"
]
],
[
[
"## Customized Search Space\nFor advanced users, you may customize your search space by using AutoModel instead of\nImageClassifier. You can configure the ImageBlock for some high-level configurations,\ne.g., block_type for the type of neural network to search, normalize for whether to do\ndata normalization, augment for whether to do data augmentation. You can also do not\nspecify these arguments, which would leave the different choices to be tuned\nautomatically. See the following example for detail.\n",
"_____no_output_____"
]
],
[
[
"input_node = ak.ImageInput()\noutput_node = ak.ImageBlock(\n # Only search ResNet architectures.\n block_type=\"resnet\",\n # Normalize the dataset.\n normalize=True,\n # Do not do data augmentation.\n augment=False,\n)(input_node)\noutput_node = ak.ClassificationHead()(output_node)\nclf = ak.AutoModel(\n inputs=input_node,\n outputs=output_node,\n overwrite=True,\n max_trials=1)\nclf.fit(x_train, y_train, epochs=10)\n",
"_____no_output_____"
]
],
[
[
"The usage of AutoModel is similar to the functional API of Keras. Basically, you are\nbuilding a graph, whose edges are blocks and the nodes are intermediate outputs of\nblocks. To add an edge from input_node to output_node with output_node =\nak.[some_block]([block_args])(input_node).\n\nYou can even also use more fine grained blocks to customize the search space even\nfurther. See the following example.\n",
"_____no_output_____"
]
],
[
[
"input_node = ak.ImageInput()\noutput_node = ak.Normalization()(input_node)\noutput_node = ak.ImageAugmentation(horizontal_flip=False)(output_node)\noutput_node = ak.ResNetBlock(version=\"v2\")(output_node)\noutput_node = ak.ClassificationHead()(output_node)\nclf = ak.AutoModel(\n inputs=input_node,\n outputs=output_node,\n overwrite=True,\n max_trials=1)\nclf.fit(x_train, y_train, epochs=10)\n",
"_____no_output_____"
]
],
[
[
"## Data Format\nThe AutoKeras ImageClassifier is quite flexible for the data format.\n\nFor the image, it accepts data formats both with and without the channel dimension. The\nimages in the MNIST dataset do not have the channel dimension. Each image is a matrix\nwith shape (28, 28). AutoKeras also accepts images of three dimensions with the channel\ndimension at last, e.g., (32, 32, 3), (28, 28, 1).\n\nFor the classification labels, AutoKeras accepts both plain labels, i.e. strings or\nintegers, and one-hot encoded encoded labels, i.e. vectors of 0s and 1s.\n\nSo if you prepare your data in the following way, the ImageClassifier should still work.\n",
"_____no_output_____"
]
],
[
[
"(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n# Reshape the images to have the channel dimension.\nx_train = x_train.reshape(x_train.shape + (1,))\nx_test = x_test.reshape(x_test.shape + (1,))\n\n# One-hot encode the labels.\neye = np.eye(10)\ny_train = eye[y_train]\ny_test = eye[y_test]\n\nprint(x_train.shape) # (60000, 28, 28, 1)\nprint(y_train.shape) # (60000, 10)\nprint(y_train[:3])\n# array([[0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],\n# [1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n# [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.]])\n",
"_____no_output_____"
]
],
[
[
"We also support using tf.data.Dataset format for the training data. In this case, the\nimages would have to be 3-dimentional. The labels have to be one-hot encoded for\nmulti-class classification to be wrapped into tensorflow Dataset.\n",
"_____no_output_____"
]
],
[
[
"train_set = tf.data.Dataset.from_tensor_slices(((x_train,), (y_train,)))\ntest_set = tf.data.Dataset.from_tensor_slices(((x_test,), (y_test,)))\n\nclf = ak.ImageClassifier(\n overwrite=True,\n max_trials=1)\n# Feed the tensorflow Dataset to the classifier.\nclf.fit(train_set, epochs=10)\n# Predict with the best model.\npredicted_y = clf.predict(test_set)\n# Evaluate the best model with testing data.\nprint(clf.evaluate(test_set))\n",
"_____no_output_____"
]
],
[
[
"## Reference\n[ImageClassifier](/image_classifier),\n[AutoModel](/auto_model/#automodel-class),\n[ImageBlock](/block/#imageblock-class),\n[Normalization](/block/#normalization-class),\n[ImageAugmentation](/block/#image-augmentation-class),\n[ResNetBlock](/block/#resnetblock-class),\n[ImageInput](/node/#imageinput-class),\n[ClassificationHead](/block/#classificationhead-class).\n",
"_____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"
]
] |
e721b31bd1631b28d12cb1eeb5f70e1e71fc3394 | 4,679 | ipynb | Jupyter Notebook | day07.ipynb | jimcarson/Advent-of-Code-2021 | f7cc49dd9f77adc4a553a11526899f2f81aec544 | [
"MIT"
] | null | null | null | day07.ipynb | jimcarson/Advent-of-Code-2021 | f7cc49dd9f77adc4a553a11526899f2f81aec544 | [
"MIT"
] | null | null | null | day07.ipynb | jimcarson/Advent-of-Code-2021 | f7cc49dd9f77adc4a553a11526899f2f81aec544 | [
"MIT"
] | null | null | null | 21.171946 | 75 | 0.442189 | [
[
[
"# Advent of Code, Day 7 - Jim Carson. \nimport numpy as np\n\n# Roll up input into lifecycle : quantity\ndef parse(puzzle_input):\n with open(puzzle_input,\"r\") as fp:\n f = fp.read()\n return np.array([int(i) for i in f.split(\",\")])",
"_____no_output_____"
],
[
"testdata = parse(\"input_files/day07.test.txt\")\ndata = parse(\"input_files/day07.txt\")",
"_____no_output_____"
],
[
"dist = { i : i * (i + 1) / 2 for i in range(min(data), max(data)+1 )}",
"_____no_output_____"
],
[
"def fuel_calc(l, pos):\n return np.sum(abs(l - pos))\n\ndef find_min_pos(d, increasing = False):\n dist = {}\n s = 0\n for i in range(min(d), max(d) + 1):\n dist[i] = s\n if increasing:\n s = s + (i - 1) + 1\n else: \n s = 1\n fpos = np.inf\n min_value = np.inf\n for i in range(min(d), max(d)):\n f = fuel_calc(d,i)\n if f < min_value:\n fpos = i\n min_value = f\n return(fpos, min_value)",
"_____no_output_____"
],
[
"# part 1, test slot 2, cost 37\nf,m = find_min_pos(testdata)\nprint(f,m)",
"2 37\n"
],
[
"# part 1, 323, cost 336,040\nf,m = find_min_pos(data)\nprint(f,m)",
"323 336040\n"
],
[
"def find_min_pos2(d):\n fpos = max(d)\n min_value = np.inf\n for i in range(min(d), max(d)):\n f = fuel_calc2(d,i)\n if f < min_value:\n print(i,f)\n fpos = i\n min_value = f\n return(fpos, min_value)",
"_____no_output_____"
],
[
"def fuel_calc2(d):\n fpos = max(d)\n mpos = min(d)\n qpos = 0\n mindist = np.inf\n for i in range(mpos, fpos+1):\n s = 0\n for j in d: \n s = s + dist[abs(i-j)]\n if s < mindist:\n # print(qpos, mindist)\n mindist = s\n qpos = i\n print(qpos, mindist)",
"_____no_output_____"
],
[
"fuel_calc2(testdata)\n# 168",
"5 168.0\n"
],
[
"fuel_calc2(data) \n# 94813675",
"463 94813675.0\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e721baf3ef1b3c3dbd5ec405161a5e5145ce6dc3 | 3,237 | ipynb | Jupyter Notebook | .ipynb_checkpoints/predict-checkpoint.ipynb | truongnmt/DeepECG | c32a38631c3df031f0be5cc6f4581c526a314531 | [
"MIT"
] | 23 | 2018-06-14T14:40:39.000Z | 2022-03-23T01:11:24.000Z | predict.ipynb | jayceyxc/DeepLearningECG | 6cf1c2fad64ab665d7f1905474f549a777b1578a | [
"MIT"
] | null | null | null | predict.ipynb | jayceyxc/DeepLearningECG | 6cf1c2fad64ab665d7f1905474f549a777b1578a | [
"MIT"
] | 12 | 2018-11-16T16:12:57.000Z | 2022-02-16T05:27:32.000Z | 26.975 | 108 | 0.564103 | [
[
[
"import os\nimport sys\nfrom functools import partial\n\nimport numpy as np\nimport tensorflow as tf\nfrom scipy.stats import beta\n\nsys.path.append(os.path.join(\"..\", \"..\", \"..\"))\nimport cardio.dataset as ds\nfrom cardio import EcgDataset\nfrom cardio.dataset import B, V, F\nfrom cardio.models.dirichlet_model import DirichletModel, concatenate_ecg_batch\nfrom cardio.models.metrics import f1_score, classification_report, confusion_matrix",
"_____no_output_____"
],
[
"signal_path = os.path.expanduser(\"~\")+\"/coding/cnn/DeepECG/raw/A00001.mat\"\n# signal_path = sys.argv[1]\nMODEL_PATH = os.path.expanduser(\"~\")+\"/coding/cnn/DeepECG/dirichlet_model\"\nBATCH_SIZE = 100",
"_____no_output_____"
],
[
"gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5, allow_growth=True)\n\nmodel_config = {\n \"session\": {\"config\": tf.ConfigProto(gpu_options=gpu_options)},\n \"build\": False,\n \"load\": {\"path\": MODEL_PATH},\n}",
"_____no_output_____"
],
[
"template_predict_ppl = (\n ds.Pipeline()\n .init_model(\"static\", DirichletModel, name=\"dirichlet\", config=model_config)\n .init_variable(\"predictions_list\", init_on_each_run=list)\n .load(fmt=\"wfdb\", components=[\"signal\", \"meta\"])\n .flip_signals()\n .split_signals(2048, 2048)\n .predict_model(\"dirichlet\", make_data=partial(concatenate_ecg_batch, return_targets=False),\n fetches=\"predictions\", save_to=V(\"predictions_list\"), mode=\"e\")\n .run(batch_size=BATCH_SIZE, shuffle=False, drop_last=False, n_epochs=1, lazy=True)\n)",
"_____no_output_____"
],
[
"predict_eds = EcgDataset(path=signal_path, no_ext=True, sort=True)\npredict_ppl = (predict_eds >> template_predict_ppl).run()",
"_____no_output_____"
],
[
"predict_ppl.get_variable(\"predictions_list\")",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e721bfdbd2a12ba92cb7823ab84a9142a313a683 | 1,919 | ipynb | Jupyter Notebook | cclhm0069/mod2/sem5.ipynb | ericbrasiln/intro-historia-digital | 5733dc55396beffeb916693c552fd4eb987472d0 | [
"MIT"
] | null | null | null | cclhm0069/mod2/sem5.ipynb | ericbrasiln/intro-historia-digital | 5733dc55396beffeb916693c552fd4eb987472d0 | [
"MIT"
] | null | null | null | cclhm0069/mod2/sem5.ipynb | ericbrasiln/intro-historia-digital | 5733dc55396beffeb916693c552fd4eb987472d0 | [
"MIT"
] | null | null | null | 29.523077 | 328 | 0.576863 | [
[
[
"# Semana 5\n\n**Período**: 08/11/2021 a 12/11/2021",
"_____no_output_____"
],
[
"## Encontro Virtual 3 (AS)\n\n**Tema**: Repositórios de fontes online e a pesquisa digital\n\n```{Note}\nPara essa aula é indicado ler o artigo [BRASIL, Eric; NASCIMENTO, Leonardo F. História digital: reflexões a partir da Hemeroteca Digital Brasileira e do uso de CAQDAS na reelaboração da pesquisa histórica. *Revista Estudos Históricos*, v. 33, n. 69, p. 196–219, 2020](http://dx.doi.org/10.1590/S2178-14942020000100011).\n```\n\n**Data**: 10/11/2021\n\n**Horário**: 19h - 21h\n\n**CH**: 2 horas\n\n**Plataforma**: `Google Meet` - link enviado por e-mail.\n\n```{Attention}\n[_Clique aqui para acessar a apresentação da aula_](https://ericbrasiln.github.io/intro-historia-digital/mod2/sem5_ap.html).\n```",
"_____no_output_____"
],
[
"## Tarefa 2 (AA)\n\n**Tema**: Levantamento bibliográfico / HDB \n\n**Data**: 10/11/2021 - 16/11/2021\n\n**CH**: 1 hora\n\n1. Escolha uma das opções para realizar a tarefa:\n * [] Levantamento Bibliográfico online com Google Acadêmico\n * [] Pesquisa na Hemeroteca Digital Brasileira\n2. Faça buscas com dois termos distintos e utilize o máximo de parâmetros e opções para filtrar suas buscas.\n3. Registre os parâmetros utilizados na busca e o resultado obtido em um arquivo de texto simples (sem formatação, salvo no formato txt).\n",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
]
] |
e721cb3f2d513e691fd8f4488b298dbd987eb812 | 9,207 | ipynb | Jupyter Notebook | visualization/scripts/Zoltar Truth Data.ipynb | varshaskrish/covid19-forecast-hub | bd7203de7609b03e4e641ec1b5894f3353b4e35a | [
"MIT"
] | null | null | null | visualization/scripts/Zoltar Truth Data.ipynb | varshaskrish/covid19-forecast-hub | bd7203de7609b03e4e641ec1b5894f3353b4e35a | [
"MIT"
] | null | null | null | visualization/scripts/Zoltar Truth Data.ipynb | varshaskrish/covid19-forecast-hub | bd7203de7609b03e4e641ec1b5894f3353b4e35a | [
"MIT"
] | null | null | null | 40.92 | 161 | 0.518519 | [
[
[
"## Calculate Zoltar Truth Data\nWith JHU Truth.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport pymmwr as pm\nimport datetime\nimport warnings\nwarnings.simplefilter(action='ignore')\n#pd.set_option(\"display.max_rows\", None, \"display.max_columns\", None)\nfrom zoltpy import util\nimport json\n\ndef get_epi_data(date):\n format_str = '%m/%d/%y' # The format\n dt = datetime.datetime.strptime(date, format_str).date()\n epi = pm.date_to_epiweek(dt)\n return epi.year, epi.week, epi.day\n\ndef get_epi_data_TZ(date):\n format_str = '%Y-%m-%d' # The format\n dt = datetime.datetime.strptime(date, format_str).date()\n epi = pm.date_to_epiweek(dt)\n epi_week = epi.week\n epi_day = epi.day\n if epi_day >=3: # cut off is Tuesday\n epi_week = epi_week + 1\n return epi.year, epi_week, epi.day\n\ndef get_available_timezeros(project_name):\n conn = util.authenticate()\n project = [project for project in conn.projects if project.name == project_name][0]\n project_timezeros = project.timezeros\n timezero = []\n for timezero_array in project_timezeros:\n timezero += [timezero_array.timezero_date]\n return timezero\n\n\ndef configure_JHU_data(df, target):\n # convert matrix to repeating row format\n df_truth = df.unstack()\n df_truth = df_truth.reset_index()\n\n # get epi data from date\n df_truth['year'], df_truth['week'], df_truth['day'] = \\\n zip(*df_truth['level_0'].map(get_epi_data))\n\n # rename columns\n df_truth = df_truth.rename(columns={0: \"value\",\n \"level_1\": \"location_long\"})\n \n # Get state IDs\n df_truth = df_truth.merge(fips_codes, left_on='location_long', right_on='state_name', how='left')\n df_truth.loc[df_truth[\"location_long\"] == \"US\", \"state_code\"] = \"US\"\n df_truth[\"state_code\"].replace({\"US\": 1000}, inplace=True) # so that can be converted to int\n\n # convert FIPS code to int\n df_truth = df_truth.dropna(subset=['state_code'])\n df_truth[\"state_code\"] = df_truth[\"state_code\"].astype(int)\n\n # add leading zeros to state code\n df_truth['state_code'] = df_truth['state_code'].apply(lambda x: '{0:0>2}'.format(x))\n\n # convert 1000 back to US\n df_truth[\"state_code\"].replace({\"1000\": \"US\"}, inplace=True)\n df_truth.loc[df_truth[\"location_long\"] == \"US\", \"state\"] = \"nat\"\n \n # Observed data on the seventh day\n # or group by week for incident deaths\n if target == 'Incident Deaths':\n df_vis = df_truth.groupby(['week', 'location_long'], as_index=False).agg({'level_0': 'last',\n 'value': 'sum', \n 'year': 'last', \n 'day': 'last', \n 'state_code': 'last',\n 'state': 'last',\n 'state_name': 'last' })\n else:\n df_vis = df_truth\n df_vis['week'] = df_vis['week'] + 1 # shift epiweek on axis\n \n # add leading zeros to epi week\n df_vis['week'] = df_vis['week'].apply(lambda x: '{0:0>2}'.format(x))\n\n # define epiweek\n df_vis['epiweek'] = df_vis['year'].astype(str) + df_vis['week']\n\n # only output \"location\", \"epiweek\", \"value\"\n df_vis = df_vis.rename(columns={\"state\": \"location\"})\n \n # rename location\n df_truth_long = df_vis.rename(columns={\"week\": \"epiweek\",\n \"state_code\": \"unit\",\n \"level_0\": \"date\"})\n # get timezero\n df_truth_long['date'] = pd.to_datetime(df_truth_long['date'])\n \n # initialize df_targets\n df_targets = pd.DataFrame(columns=list(df_truth_long.columns).append('target'))\n \n # use Saturday truth values\n df_truth_values = df_truth_long[df_truth_long['day'] == 7]\n \n # find week-ahead targets\n for i in range(4):\n weeks_ahead = i + 1\n days_back = 5 + ((weeks_ahead - 1) * 7) # timezero is on Mondays\n\n df_calc = df_truth_values # initialize df\n\n # find timezero and target\n df_calc['timezero'] = df_calc['date'] - datetime.timedelta(days=days_back)\n if target == \"Cumulative Deaths\":\n df_calc['target'] = \"%i wk ahead cum death\" % weeks_ahead\n else:\n df_calc['target'] = \"%i wk ahead inc death\" % weeks_ahead\n # concatenate truth\n df_targets = pd.concat([df_targets, df_calc])\n \n # get epi data from Timezero\n df_targets['timezero'] = df_targets['timezero'].astype(str)\n df_targets['tz_year'], df_targets['tz_week'], df_targets['tz_day'] = \\\n zip(*df_targets['timezero'].map(get_epi_data_TZ))\n \n # truth targets by timezero week\n df_targets = df_targets[[\"tz_week\", \"unit\", \"target\", \"value\"]]\n \n # Map all timezeros in Zoltar to Corresponding weeks\n df_map_wk_to_tz = pd.DataFrame(columns=['timezero'])\n df_map_wk_to_tz['timezero'] = get_available_timezeros(\"COVID-19 Forecasts\")\n df_map_wk_to_tz['tz_year'], df_map_wk_to_tz['tz_week'], df_map_wk_to_tz['tz_day'] = \\\n zip(*df_map_wk_to_tz['timezero'].map(get_epi_data_TZ))\n \n # Merge timezeros with truth values and targets\n df_final = pd.merge(df_targets, df_map_wk_to_tz, how='right', on=['tz_week'])\n \n # select columns\n df_final = df_final[[\"timezero\", \"unit\", \"target\", \"value\"]]\n \n # drop empty rows\n nan_value = float(\"NaN\")\n df_final.replace(\"\", nan_value, inplace=True)\n df_final.dropna(inplace=True)\n return df_final",
"_____no_output_____"
],
[
"df = pd.read_csv(\n \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_US.csv\")\nfips_codes = pd.read_csv('../../template/state_fips_codes.csv')\n\n# aggregate by state and nationally\nstate_agg = df.groupby(['Province_State']).sum()\nus_nat = df.groupby(['Country_Region']).sum()\ndf_state_nat = state_agg.append(us_nat)\n\n# drop unnecessary columns\ncols = list(range(0, 6))\ndf_truth = df_state_nat.drop(df_state_nat.columns[cols], axis=1)\n\n# calculate incidents from cumulative\ndf_truth_cumulative = df_truth\ndf_truth_incident = df_truth - df_truth.shift(periods=1, axis='columns') \n\n# re-format files\ndf_cum_death = configure_JHU_data(df_truth_cumulative, \"Cumulative Deaths\")\ndf_inc_death = configure_JHU_data(df_truth_incident, \"Incident Deaths\")\n\n# concatenate targers\nzoltar_truth = pd.concat([df_cum_death,df_inc_death])\n\n# write truth to csv\nfile_path = '../../data-truth/zoltar-truth.csv'\nzoltar_truth.to_csv(file_path, index=False)",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
]
] |
e721d1a871b905ba76c615a78e777534275caeb2 | 27,916 | ipynb | Jupyter Notebook | examples/torch/data_poisoning_attack.ipynb | spenrich/cvxpylayers | 83f3dc287b633242254604b74173dcb4708e8fca | [
"Apache-2.0"
] | null | null | null | examples/torch/data_poisoning_attack.ipynb | spenrich/cvxpylayers | 83f3dc287b633242254604b74173dcb4708e8fca | [
"Apache-2.0"
] | null | null | null | examples/torch/data_poisoning_attack.ipynb | spenrich/cvxpylayers | 83f3dc287b633242254604b74173dcb4708e8fca | [
"Apache-2.0"
] | 1 | 2022-03-22T11:32:02.000Z | 2022-03-22T11:32:02.000Z | 125.747748 | 20,084 | 0.85202 | [
[
[
"# Data poisoning attack\n\nIn this notebook, we use a convex optimization layer to perform a *data poisoning attack*; i.e., we show how to perturb the data used to train a logistic regression classifier so as to maximally increase the test loss. This example is also presented in section 6.1 of the paper *Differentiable convex optimization layers*.",
"_____no_output_____"
]
],
[
[
"import cvxpy as cp\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\n\nfrom cvxpylayers.torch import CvxpyLayer",
"_____no_output_____"
]
],
[
[
"We are given training data $(x_i, y_i)_{i=1}^{N}$,\nwhere $x_i\\in\\mathbf{R}^n$ are feature vectors and $y_i\\in\\{0,1\\}$ are the labels.\nSuppose we fit a model for this classification problem by solving\n\\begin{equation}\n\\begin{array}{ll}\n\\mbox{minimize} & \\frac{1}{N}\\sum_{i=1}^N \\ell(\\theta; x_i, y_i) + r(\\theta),\n\\end{array}\n\\label{eq:trainlinear}\n\\end{equation}\nwhere the loss function $\\ell(\\theta; x_i, y_i)$ is convex in $\\theta \\in \\mathbf{R}^n$ and $r(\\theta)$ is a convex\nregularizer. We hope that the test loss $\\mathcal{L}^{\\mathrm{test}}(\\theta) =\n\\frac{1}{M}\\sum_{i=1}^M \\ell(\\theta; \\tilde x_i, \\tilde y_i)$ is small, where\n$(\\tilde x_i, \\tilde y_i)_{i=1}^{M}$ is our test set. In this example, we use the logistic loss\n\n\\begin{equation}\n\\ell(\\theta; x_i, y_i) = 1 + \\exp(\\beta^Tx_i + b)) - y_i(\\beta^Tx_i + b)\n\\end{equation}\n\nwith elastic net regularization\n\n\\begin{equation}\nr(\\theta) = 0.1\\|\\beta\\|_1 + 0.1\\|\\beta\\|_2^2.\n\\end{equation}",
"_____no_output_____"
]
],
[
[
"from sklearn.datasets import make_blobs\nfrom sklearn.model_selection import train_test_split\n\ntorch.manual_seed(0)\nnp.random.seed(0)\nn = 2\nN = 60\nX, y = make_blobs(N, n, centers=np.array([[2, 2], [-2, -2]]), cluster_std=3)\nXtrain, Xtest, ytrain, ytest = train_test_split(X, y, test_size=.5)\n\nXtrain, Xtest, ytrain, ytest = map(\n torch.from_numpy, [Xtrain, Xtest, ytrain, ytest])\nXtrain.requires_grad_(True)\nm = Xtrain.shape[0]\n\na = cp.Variable((n, 1))\nb = cp.Variable((1, 1))\nX = cp.Parameter((m, n))\nY = ytrain.numpy()[:, np.newaxis]\n\nlog_likelihood = (1. / m) * cp.sum(\n cp.multiply(Y, X @ a + b) - cp.logistic(X @ a + b)\n)\nregularization = - 0.1 * cp.norm(a, 1) - 0.1 * cp.sum_squares(a)\nprob = cp.Problem(cp.Maximize(log_likelihood + regularization))\nfit_logreg = CvxpyLayer(prob, [X], [a, b])",
"_____no_output_____"
]
],
[
[
"Assume that our training data is subject to a data poisoning attack,\nbefore it is supplied to us. The adversary has full knowledge of our modeling\nchoice, meaning that they know the form of the optimization problem above, and seeks\nto perturb the data to maximally increase our loss on the test\nset, to which they also have access. The adversary is permitted to apply an\nadditive perturbation $\\delta_i \\in \\mathbf{R}^n$ to each of the training points $x_i$,\nwith the perturbations satisfying $\\|\\delta_i\\|_\\infty \\leq 0.01$.\n\nLet $\\theta^\\star$ be optimal.\nThe gradient of\nthe test loss with respect to a training data point, $\\nabla_{x_i}\n\\mathcal{L}^{\\mathrm{test}}(\\theta^\\star)$, gives the direction\nin which the point should be moved to achieve the greatest\nincrease in test loss. Hence, one reasonable adversarial policy is to set $x_i\n:= x_i +\n.01\\mathrm{sign}(\\nabla_{x_i}\\mathcal{L}^{\\mathrm{test}}(\\theta^\\star))$. The\nquantity $0.01\\sum_{i=1}^N \\|\\nabla_{x_i}\n\\mathcal{L}^{\\mathrm{test}}(\\theta^\\star)\\|_1$ is the predicted increase in\nour test loss due to the poisoning.",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LogisticRegression\n\na_tch, b_tch = fit_logreg(Xtrain)\nloss = 300 * torch.nn.BCEWithLogitsLoss()((Xtest @ a_tch + b_tch).squeeze(), ytest*1.0)\nloss.backward()\nXtrain_grad = Xtrain.grad",
"_____no_output_____"
]
],
[
[
"Below, we plot the gradient of the test loss with respect to the training data points. The blue and orange points are training data, belonging to different classes. The red line is the hyperplane learned by fitting the the model, while the blue line is the hyperplane that minimizes the test loss. The gradients are visualized as black lines, attached to the data points. Moving the points in the gradient directions torques the learned hyperplane away from the optimal hyperplane for the test set.",
"_____no_output_____"
]
],
[
[
"lr = LogisticRegression(solver='lbfgs')\nlr.fit(Xtest.numpy(), ytest.numpy())\nbeta_train = a_tch.detach().numpy().flatten()\nbeta_test = lr.coef_.flatten()\nb_train = b_tch.squeeze().detach().numpy()\nb_test = lr.intercept_[0]\nhyperplane = lambda x, beta, b: - (b + beta[0] * x) / beta[1]\n\nXtrain_np = Xtrain.detach().numpy()\nXtrain_grad_np = Xtrain_grad.numpy()\nytrain_np = ytrain.numpy().astype(np.bool)\n\nplt.figure()\nplt.scatter(Xtrain_np[ytrain_np, 0], Xtrain_np[ytrain_np, 1], s=25, marker='+')\nplt.scatter(Xtrain_np[~ytrain_np, 0], Xtrain_np[~ytrain_np, 1], s=25, marker='*')\n\nfor i in range(m):\n plt.arrow(Xtrain_np[i, 0], Xtrain_np[i, 1],\n Xtrain_grad_np[i, 0], Xtrain_grad_np[i, 1])\n\nplt.xlim(-8, 8)\nplt.ylim(-8, 8)\n\nplt.plot(np.linspace(-8, 8, 100),\n [hyperplane(x, beta_train, b_train)\n for x in np.linspace(-8, 8, 100)], '--', color='red', label='train')\nplt.plot(np.linspace(-8, 8, 100),\n [hyperplane(x, beta_test, b_test)\n for x in np.linspace(-8, 8, 100)], '-', color='blue', label='test')\nplt.legend()\nplt.savefig(\"data_poisoning.pdf\")\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e721d59ea59adfdf998cbed800efe9797a20ac36 | 53,438 | ipynb | Jupyter Notebook | Keras+-+Tutorial+-+Happy+House+v2.ipynb | gajera-divya/fuzzy | 09b9e48beb53a937e96c280fa6565e528b775b85 | [
"MIT"
] | null | null | null | Keras+-+Tutorial+-+Happy+House+v2.ipynb | gajera-divya/fuzzy | 09b9e48beb53a937e96c280fa6565e528b775b85 | [
"MIT"
] | null | null | null | Keras+-+Tutorial+-+Happy+House+v2.ipynb | gajera-divya/fuzzy | 09b9e48beb53a937e96c280fa6565e528b775b85 | [
"MIT"
] | null | null | null | 82.593509 | 24,174 | 0.74666 | [
[
[
"# Keras tutorial - the Happy House\n\nWelcome to the first assignment of week 2. In this assignment, you will:\n1. Learn to use Keras, a high-level neural networks API (programming framework), written in Python and capable of running on top of several lower-level frameworks including TensorFlow and CNTK. \n2. See how you can in a couple of hours build a deep learning algorithm.\n\nWhy are we using Keras? Keras was developed to enable deep learning engineers to build and experiment with different models very quickly. Just as TensorFlow is a higher-level framework than Python, Keras is an even higher-level framework and provides additional abstractions. Being able to go from idea to result with the least possible delay is key to finding good models. However, Keras is more restrictive than the lower-level frameworks, so there are some very complex models that you can implement in TensorFlow but not (without more difficulty) in Keras. That being said, Keras will work fine for many common models. \n\nIn this exercise, you'll work on the \"Happy House\" problem, which we'll explain below. Let's load the required packages and solve the problem of the Happy House!",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom keras import layers\nfrom keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D\nfrom keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D\nfrom keras.models import Model\nfrom keras.preprocessing import image\nfrom keras.utils import layer_utils\nfrom keras.utils.data_utils import get_file\nfrom keras.applications.imagenet_utils import preprocess_input\nimport pydot\nfrom IPython.display import SVG\nfrom keras.utils.vis_utils import model_to_dot\nfrom keras.utils import plot_model\nfrom kt_utils import *\n\nimport keras.backend as K\nK.set_image_data_format('channels_last')\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import imshow\n\n%matplotlib inline",
"Using TensorFlow backend.\n"
]
],
[
[
"**Note**: As you can see, we've imported a lot of functions from Keras. You can use them easily just by calling them directly in the notebook. Ex: `X = Input(...)` or `X = ZeroPadding2D(...)`.",
"_____no_output_____"
],
[
"## 1 - The Happy House \n\nFor your next vacation, you decided to spend a week with five of your friends from school. It is a very convenient house with many things to do nearby. But the most important benefit is that everybody has commited to be happy when they are in the house. So anyone wanting to enter the house must prove their current state of happiness.\n\n<img src=\"images/happy-house.jpg\" style=\"width:350px;height:270px;\">\n<caption><center> <u> <font color='purple'> **Figure 1** </u><font color='purple'> : **the Happy House**</center></caption>\n\n\nAs a deep learning expert, to make sure the \"Happy\" rule is strictly applied, you are going to build an algorithm which that uses pictures from the front door camera to check if the person is happy or not. The door should open only if the person is happy. \n\nYou have gathered pictures of your friends and yourself, taken by the front-door camera. The dataset is labbeled. \n\n<img src=\"images/house-members.png\" style=\"width:550px;height:250px;\">\n\nRun the following code to normalize the dataset and learn about its shapes.",
"_____no_output_____"
]
],
[
[
"X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()\n\n# Normalize image vectors\nX_train = X_train_orig/255.\nX_test = X_test_orig/255.\n\n# Reshape\nY_train = Y_train_orig.T\nY_test = Y_test_orig.T\n\nprint (\"number of training examples = \" + str(X_train.shape[0]))\nprint (\"number of test examples = \" + str(X_test.shape[0]))\nprint (\"X_train shape: \" + str(X_train.shape))\nprint (\"Y_train shape: \" + str(Y_train.shape))\nprint (\"X_test shape: \" + str(X_test.shape))\nprint (\"Y_test shape: \" + str(Y_test.shape))",
"number of training examples = 600\nnumber of test examples = 150\nX_train shape: (600, 64, 64, 3)\nY_train shape: (600, 1)\nX_test shape: (150, 64, 64, 3)\nY_test shape: (150, 1)\n"
]
],
[
[
"**Details of the \"Happy\" dataset**:\n- Images are of shape (64,64,3)\n- Training: 600 pictures\n- Test: 150 pictures\n\nIt is now time to solve the \"Happy\" Challenge.",
"_____no_output_____"
],
[
"## 2 - Building a model in Keras\n\nKeras is very good for rapid prototyping. In just a short time you will be able to build a model that achieves outstanding results.\n\nHere is an example of a model in Keras:\n\n```python\ndef model(input_shape):\n # Define the input placeholder as a tensor with shape input_shape. Think of this as your input image!\n X_input = Input(input_shape)\n\n # Zero-Padding: pads the border of X_input with zeroes\n X = ZeroPadding2D((3, 3))(X_input)\n\n # CONV -> BN -> RELU Block applied to X\n X = Conv2D(32, (7, 7), strides = (1, 1), name = 'conv0')(X)\n X = BatchNormalization(axis = 3, name = 'bn0')(X)\n X = Activation('relu')(X)\n\n # MAXPOOL\n X = MaxPooling2D((2, 2), name='max_pool')(X)\n\n # FLATTEN X (means convert it to a vector) + FULLYCONNECTED\n X = Flatten()(X)\n X = Dense(1, activation='sigmoid', name='fc')(X)\n\n # Create model. This creates your Keras model instance, you'll use this instance to train/test the model.\n model = Model(inputs = X_input, outputs = X, name='HappyModel')\n \n return model\n```\n\nNote that Keras uses a different convention with variable names than we've previously used with numpy and TensorFlow. In particular, rather than creating and assigning a new variable on each step of forward propagation such as `X`, `Z1`, `A1`, `Z2`, `A2`, etc. for the computations for the different layers, in Keras code each line above just reassigns `X` to a new value using `X = ...`. In other words, during each step of forward propagation, we are just writing the latest value in the commputation into the same variable `X`. The only exception was `X_input`, which we kept separate and did not overwrite, since we needed it at the end to create the Keras model instance (`model = Model(inputs = X_input, ...)` above). \n\n**Exercise**: Implement a `HappyModel()`. This assignment is more open-ended than most. We suggest that you start by implementing a model using the architecture we suggest, and run through the rest of this assignment using that as your initial model. But after that, come back and take initiative to try out other model architectures. For example, you might take inspiration from the model above, but then vary the network architecture and hyperparameters however you wish. You can also use other functions such as `AveragePooling2D()`, `GlobalMaxPooling2D()`, `Dropout()`. \n\n**Note**: You have to be careful with your data's shapes. Use what you've learned in the videos to make sure your convolutional, pooling and fully-connected layers are adapted to the volumes you're applying it to.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: HappyModel\n\ndef HappyModel(input_shape):\n \"\"\"\n Implementation of the HappyModel.\n \n Arguments:\n input_shape -- shape of the images of the dataset\n\n Returns:\n model -- a Model() instance in Keras\n \"\"\"\n \n ### START CODE HERE ###\n # Feel free to use the suggested outline in the text above to get started, and run through the whole\n # exercise (including the later portions of this notebook) once. The come back also try out other\n # network architectures as well. \n X_input = Input(input_shape)\n X = ZeroPadding2D((3, 3))(X_input)\n X = Conv2D(32, (5, 5), strides = (1, 1), name = 'conv0')(X)\n X = BatchNormalization(axis = 3, name = 'bn0')(X)\n X = Activation('relu')(X)\n X = MaxPooling2D((2, 2), name='max_pool')(X)\n X = Flatten()(X)\n X = Dense(1, activation='sigmoid', name='fc')(X)\n model = Model(inputs = X_input, outputs = X, name='HappyModel')\n\n \n ### END CODE HERE ###\n \n return model",
"_____no_output_____"
]
],
[
[
"You have now built a function to describe your model. To train and test this model, there are four steps in Keras:\n1. Create the model by calling the function above\n2. Compile the model by calling `model.compile(optimizer = \"...\", loss = \"...\", metrics = [\"accuracy\"])`\n3. Train the model on train data by calling `model.fit(x = ..., y = ..., epochs = ..., batch_size = ...)`\n4. Test the model on test data by calling `model.evaluate(x = ..., y = ...)`\n\nIf you want to know more about `model.compile()`, `model.fit()`, `model.evaluate()` and their arguments, refer to the official [Keras documentation](https://keras.io/models/model/).\n\n**Exercise**: Implement step 1, i.e. create the model.",
"_____no_output_____"
]
],
[
[
"### START CODE HERE ### (1 line)\nhappyModel = HappyModel((64,64,3))\n### END CODE HERE ###",
"_____no_output_____"
]
],
[
[
"**Exercise**: Implement step 2, i.e. compile the model to configure the learning process. Choose the 3 arguments of `compile()` wisely. Hint: the Happy Challenge is a binary classification problem.",
"_____no_output_____"
]
],
[
[
"### START CODE HERE ### (1 line)\nfrom keras import optimizers\nsgd = optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\nhappyModel.compile(loss='mean_squared_error', optimizer=sgd, metrics = ['accuracy'])\n### END CODE HERE ###",
"_____no_output_____"
]
],
[
[
"**Exercise**: Implement step 3, i.e. train the model. Choose the number of epochs and the batch size.",
"_____no_output_____"
]
],
[
[
"### START CODE HERE ### (1 line)\nhappyModel.fit(x = X_train, y = Y_train, epochs = 10, batch_size = 16, verbose = 1)\n### END CODE HERE ###",
"Epoch 1/10\n600/600 [==============================] - 11s - loss: 0.1842 - acc: 0.7200 \nEpoch 2/10\n600/600 [==============================] - 10s - loss: 0.0941 - acc: 0.8917 \nEpoch 3/10\n600/600 [==============================] - 10s - loss: 0.0610 - acc: 0.9383 \nEpoch 4/10\n600/600 [==============================] - 10s - loss: 0.0480 - acc: 0.9583 \nEpoch 5/10\n600/600 [==============================] - 10s - loss: 0.0384 - acc: 0.9667 \nEpoch 6/10\n600/600 [==============================] - 10s - loss: 0.0337 - acc: 0.9683 \nEpoch 7/10\n600/600 [==============================] - 10s - loss: 0.0274 - acc: 0.9750 \nEpoch 8/10\n600/600 [==============================] - 10s - loss: 0.0254 - acc: 0.9817 \nEpoch 9/10\n600/600 [==============================] - 10s - loss: 0.0213 - acc: 0.9833 \nEpoch 10/10\n600/600 [==============================] - 10s - loss: 0.0200 - acc: 0.9833 \n"
]
],
[
[
"Note that if you run `fit()` again, the `model` will continue to train with the parameters it has already learnt instead of reinitializing them.\n\n**Exercise**: Implement step 4, i.e. test/evaluate the model.",
"_____no_output_____"
]
],
[
[
"### START CODE HERE ### (1 line)\npreds = happyModel.evaluate(x = X_test, y = Y_test)\n### END CODE HERE ###\nprint()\nprint (\"Loss = \" + str(preds[0]))\nprint (\"Test Accuracy = \" + str(preds[1]))",
"150/150 [==============================] - 1s \n\nLoss = 0.0784193765124\nTest Accuracy = 0.940000003974\n"
]
],
[
[
"If your `happyModel()` function worked, you should have observed much better than random-guessing (50%) accuracy on the train and test sets.\n\nTo give you a point of comparison, our model gets around **95% test accuracy in 40 epochs** (and 99% train accuracy) with a mini batch size of 16 and \"adam\" optimizer. But our model gets decent accuracy after just 2-5 epochs, so if you're comparing different models you can also train a variety of models on just a few epochs and see how they compare. \n\nIf you have not yet achieved a very good accuracy (let's say more than 80%), here're some things you can play around with to try to achieve it:\n\n- Try using blocks of CONV->BATCHNORM->RELU such as:\n```python\nX = Conv2D(32, (3, 3), strides = (1, 1), name = 'conv0')(X)\nX = BatchNormalization(axis = 3, name = 'bn0')(X)\nX = Activation('relu')(X)\n```\nuntil your height and width dimensions are quite low and your number of channels quite large (≈32 for example). You are encoding useful information in a volume with a lot of channels. You can then flatten the volume and use a fully-connected layer.\n- You can use MAXPOOL after such blocks. It will help you lower the dimension in height and width.\n- Change your optimizer. We find Adam works well. \n- If the model is struggling to run and you get memory issues, lower your batch_size (12 is usually a good compromise)\n- Run on more epochs, until you see the train accuracy plateauing. \n\nEven if you have achieved a good accuracy, please feel free to keep playing with your model to try to get even better results. \n\n**Note**: If you perform hyperparameter tuning on your model, the test set actually becomes a dev set, and your model might end up overfitting to the test (dev) set. But just for the purpose of this assignment, we won't worry about that here.\n",
"_____no_output_____"
],
[
"## 3 - Conclusion\n\nCongratulations, you have solved the Happy House challenge! \n\nNow, you just need to link this model to the front-door camera of your house. We unfortunately won't go into the details of how to do that here. ",
"_____no_output_____"
],
[
"<font color='blue'>\n**What we would like you to remember from this assignment:**\n- Keras is a tool we recommend for rapid prototyping. It allows you to quickly try out different model architectures. Are there any applications of deep learning to your daily life that you'd like to implement using Keras? \n- Remember how to code a model in Keras and the four steps leading to the evaluation of your model on the test set. Create->Compile->Fit/Train->Evaluate/Test.",
"_____no_output_____"
],
[
"## 4 - Test with your own image (Optional)\n\nCongratulations on finishing this assignment. You can now take a picture of your face and see if you could enter the Happy House. To do that:\n 1. Click on \"File\" in the upper bar of this notebook, then click \"Open\" to go on your Coursera Hub.\n 2. Add your image to this Jupyter Notebook's directory, in the \"images\" folder\n 3. Write your image's name in the following code\n 4. Run the code and check if the algorithm is right (0 is unhappy, 1 is happy)!\n \nThe training/test sets were quite similar; for example, all the pictures were taken against the same background (since a front door camera is always mounted in the same position). This makes the problem easier, but a model trained on this data may or may not work on your own data. But feel free to give it a try! ",
"_____no_output_____"
]
],
[
[
"### START CODE HERE ###\nimg_path = 'images/image.jpg'\n### END CODE HERE ###\nimg = image.load_img(img_path, target_size=(64, 64))\nimshow(img)\n\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nx = preprocess_input(x)\n\nprint(happyModel.predict(x))",
"[[ 1.]]\n"
]
],
[
[
"## 5 - Other useful functions in Keras (Optional)\n\nTwo other basic features of Keras that you'll find useful are:\n- `model.summary()`: prints the details of your layers in a table with the sizes of its inputs/outputs\n- `plot_model()`: plots your graph in a nice layout. You can even save it as \".png\" using SVG() if you'd like to share it on social media ;). It is saved in \"File\" then \"Open...\" in the upper bar of the notebook.\n\nRun the following code.",
"_____no_output_____"
]
],
[
[
"happyModel.summary()",
"_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) (None, 64, 64, 3) 0 \n_________________________________________________________________\nzero_padding2d_1 (ZeroPaddin (None, 70, 70, 3) 0 \n_________________________________________________________________\nconv0 (Conv2D) (None, 66, 66, 32) 2432 \n_________________________________________________________________\nbn0 (BatchNormalization) (None, 66, 66, 32) 128 \n_________________________________________________________________\nactivation_1 (Activation) (None, 66, 66, 32) 0 \n_________________________________________________________________\nmax_pool (MaxPooling2D) (None, 33, 33, 32) 0 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 34848) 0 \n_________________________________________________________________\nfc (Dense) (None, 1) 34849 \n=================================================================\nTotal params: 37,409\nTrainable params: 37,345\nNon-trainable params: 64\n_________________________________________________________________\n"
],
[
"plot_model(happyModel, to_file='HappyModel.png')\nSVG(model_to_dot(happyModel).create(prog='dot', format='svg'))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e721d625a6d8d4fe287975021f215ab803510c39 | 211,366 | ipynb | Jupyter Notebook | TradingBot_1.ipynb | hkailee/Quant-Finance | b672e0c7f608e237674f7621c3f7230f4483e87c | [
"MIT"
] | 1 | 2018-08-22T04:41:25.000Z | 2018-08-22T04:41:25.000Z | TradingBot_1.ipynb | hkailee/Quant-Finance | b672e0c7f608e237674f7621c3f7230f4483e87c | [
"MIT"
] | null | null | null | TradingBot_1.ipynb | hkailee/Quant-Finance | b672e0c7f608e237674f7621c3f7230f4483e87c | [
"MIT"
] | 1 | 2018-08-22T22:57:48.000Z | 2018-08-22T22:57:48.000Z | 222.256572 | 141,669 | 0.876664 | [
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom datetime import datetime, date\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\nfrom sklearn.preprocessing import minmax_scale\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, LSTM, Input, concatenate, Embedding, Reshape\nimport keras\nimport keras.backend as K\nimport tensorflow as tf\n\n%matplotlib inline",
"Using TensorFlow backend.\n"
],
[
"sns.set_style('whitegrid')\nnp.random.seed(42)\nK.clear_session()",
"WARNING: Logging before flag parsing goes to stderr.\nW0627 11:45:54.790189 4553258432 deprecation_wrapper.py:119] From /Users/leehongkai/anaconda/envs/trading_py36/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead.\n\nW0627 11:45:54.791280 4553258432 deprecation_wrapper.py:119] From /Users/leehongkai/anaconda/envs/trading_py36/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:98: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead.\n\nW0627 11:45:54.829572 4553258432 deprecation_wrapper.py:119] From /Users/leehongkai/anaconda/envs/trading_py36/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:102: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.\n\n"
],
[
"df = pd.read_csv('robolee/Data/AAPL.csv', index_col='datetime')\ndata_cols = ['close', 'high', 'low', 'open', 'volume']\ndf = df[data_cols]\nnp.diff(df.index[:100])",
"_____no_output_____"
],
[
"df_scaled = df.apply(minmax_scale)\ndf_scaled[:5]",
"_____no_output_____"
],
[
"def compute_log_returns(datum):\n \"\"\"\n Compute log returns for each ticker.\n \n Parameters\n ----------\n prices : DataFrame\n Prices for each ticker and date\n \n Returns\n -------\n log_returns : DataFrame\n Log returns for each ticker and date\n \"\"\"\n # TODO: Implement Function\n \n return np.log(datum) - np.log(datum.shift(1))",
"_____no_output_____"
],
[
"transformed_df = compute_log_returns(df).dropna()\ntransformed_df[:5]",
"_____no_output_____"
],
[
"x_scaled = transformed_df[['high','low','open','volume']].apply(minmax_scale)\nx_scaled[:5]",
"_____no_output_____"
],
[
"xy_scaled = pd.concat([transformed_df[['close']], x_scaled], axis=1)\nxy_scaled[:5]\n",
"_____no_output_____"
],
[
"def create_multivariate_rnn_data(data, window_size):\n y = data[window_size:]\n n = data.shape[0]\n X = np.stack([data[i: j] for i, j in enumerate(range(window_size, n))], axis=0)\n return X, y",
"_____no_output_____"
],
[
"window_size = 24\n\nX, y = create_multivariate_rnn_data(xy_scaled, window_size=window_size)\n",
"_____no_output_____"
],
[
"X.shape, y.shape\n",
"_____no_output_____"
],
[
"test_size =24\ntrain_size = X.shape[0]-test_size",
"_____no_output_____"
],
[
"X_train, y_train = X[:train_size], y[:train_size]\nX_test, y_test = X[train_size:], y[train_size:]",
"_____no_output_____"
],
[
"X_train.shape, X_test.shape",
"_____no_output_____"
],
[
"n_features = output_size = 5",
"_____no_output_____"
],
[
"lstm1_units = 12\nlstm2_units = 6",
"_____no_output_____"
],
[
"rnn = Sequential([\n LSTM(units=lstm1_units,\n dropout=.2,\n recurrent_dropout=.2,\n input_shape=(window_size, n_features), name='LSTM1',\n return_sequences=True),\n LSTM(units=lstm2_units,\n dropout=.2,\n recurrent_dropout=.2,\n name='LSTM2'),\n Dense(10, name='FC1'),\n Dense(output_size, name='Output')\n])",
"W0627 13:38:05.917026 4553258432 deprecation_wrapper.py:119] From /Users/leehongkai/anaconda/envs/trading_py36/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:517: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.\n\nW0627 13:38:05.950074 4553258432 deprecation_wrapper.py:119] From /Users/leehongkai/anaconda/envs/trading_py36/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:4138: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead.\n\nW0627 13:38:06.119823 4553258432 deprecation.py:506] From /Users/leehongkai/anaconda/envs/trading_py36/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.\n"
],
[
"rnn.summary()",
"_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nLSTM1 (LSTM) (None, 24, 12) 864 \n_________________________________________________________________\nLSTM2 (LSTM) (None, 6) 456 \n_________________________________________________________________\nFC1 (Dense) (None, 10) 70 \n_________________________________________________________________\nOutput (Dense) (None, 5) 55 \n=================================================================\nTotal params: 1,445\nTrainable params: 1,445\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"rnn.compile(loss='mae', optimizer='RMSProp')",
"W0627 13:38:56.609152 4553258432 deprecation_wrapper.py:119] From /Users/leehongkai/anaconda/envs/trading_py36/lib/python3.6/site-packages/keras/optimizers.py:790: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead.\n\n"
],
[
"early_stopping = EarlyStopping(monitor='val_loss', \n patience=5,\n restore_best_weights=True)",
"_____no_output_____"
],
[
"rnn_path = 'models/fred.lstm_{}_{}.weights.best.hdf5'.format(lstm1_units, lstm2_units)\ncheckpointer = ModelCheckpoint(filepath=rnn_path,\n monitor='val_loss',\n save_best_only=True,\n save_weights_only=True,\n period=5)",
"_____no_output_____"
],
[
"result = rnn.fit(X_train,\n y_train,\n epochs=50,\n batch_size=20,\n validation_data=(X_test, y_test),\n callbacks=[checkpointer, early_stopping],\n verbose=1)",
"Train on 174565 samples, validate on 24 samples\nEpoch 1/50\n174565/174565 [==============================] - 375s 2ms/step - loss: 0.0149 - val_loss: 0.0170\nEpoch 2/50\n 20560/174565 [==>...........................] - ETA: 5:00 - loss: 0.0151"
],
[
"pd.DataFrame(result.history).plot();\n",
"_____no_output_____"
],
[
"y_pred = pd.DataFrame(rnn.predict(X_test), columns=y_test.columns, index=y_test.index)\ny_pred.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 24 entries, 1561485600000 to 1561506300000\nData columns (total 5 columns):\nclose 24 non-null float32\nhigh 24 non-null float32\nlow 24 non-null float32\nopen 24 non-null float32\nvolume 24 non-null float32\ndtypes: float32(5)\nmemory usage: 672.0 bytes\n"
],
[
"test_mae = mean_absolute_error(y_pred, y_test)\n",
"_____no_output_____"
],
[
"# pd.DataFrame(result.history).plot()\ny_train.iloc[2:, 'close']",
"_____no_output_____"
],
[
"fig, axes = plt.subplots(ncols=6, figsize=(16, 5))\npd.DataFrame(result.history).plot(ax=axes[0], title='Train & Validiation Error')\naxes[0].set_xlabel('Epoch')\naxes[0].set_ylabel('MAE')\nfor i, col in enumerate(y_test.columns, 1):\n# y_train.iloc[1561457700000:, col].plot(ax=axes[i], label='training', title=col)\n y_test[col].plot(ax=axes[i], label='out-of-sample')\n y_pred[col].plot(ax=axes[i], label='prediction')\n axes[i].set_xlabel('')\nplt.legend()\nfig.suptitle('Multivariate RNN - Results | Test MAE = {:.2f}'.format(test_mae), fontsize=16)\nfig.tight_layout()\nfig.subplots_adjust(top=.85)\n# fig.savefig('figures/multivariate_results', dpi=300);",
"_____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"
]
] |
e721de380d65cc31df46f46aa1e3ed837058aed3 | 17,872 | ipynb | Jupyter Notebook | memolon/analyses/translation_vs_prediction.ipynb | JULIELab/MEmoLon | 7f8eb102597ad5df3f6cf65c26c56f3888e885aa | [
"MIT"
] | 21 | 2020-05-14T20:19:25.000Z | 2022-03-22T09:24:56.000Z | memolon/analyses/translation_vs_prediction.ipynb | JULIELab/MEmoLon | 7f8eb102597ad5df3f6cf65c26c56f3888e885aa | [
"MIT"
] | null | null | null | memolon/analyses/translation_vs_prediction.ipynb | JULIELab/MEmoLon | 7f8eb102597ad5df3f6cf65c26c56f3888e885aa | [
"MIT"
] | 2 | 2021-04-12T10:14:40.000Z | 2021-06-09T01:41:49.000Z | 32.97417 | 221 | 0.389268 | [
[
[
"# Translation vs. Prediction",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nfrom scipy import stats as st\n\nfrom memolon.src import utils, constants",
"_____no_output_____"
]
],
[
[
"Define evaluation for single dataset:",
"_____no_output_____"
]
],
[
[
"def evaluate_translation(gold, mt, pred):\n rt = {}\n \n shared_rows = sorted(list(set(gold.index).intersection(set(mt.index)).intersection(set(pred.index))))\n shared_columns = list(set(gold.columns).intersection(set(mt.columns)).intersection(set(pred.columns)))\n \n gold = gold.loc[shared_rows, shared_columns]\n mt = mt.loc[shared_rows, shared_columns]\n pred = pred.loc[shared_rows, shared_columns]\n \n \n # TargetMT may have duplicated entries. Those will be averaged to get a single rating per type.\n # (The reason why duplicated TargetMT entries are averaged here (and not in other analyses such as the\n # silver evaluation) is that we want to determine which of the two target side lexica, TargetPred or TargetMT is\n # closer to the gold standard. As such, averaging TargetMT entries is expected to result in higher performance\n # and leads to a more challenging comparison. Additionally, if TargetMT would be used in a downstream application,\n # having competing entries may not be acceptable.)\n tmp = pd.DataFrame(columns=mt.columns)\n for i in set(mt.index):\n candidate = mt.loc[i]\n if isinstance(candidate, pd.Series):\n tmp.loc[i] = candidate\n elif isinstance(candidate, pd.DataFrame):\n tmp.loc[i] = candidate.mean(axis=0)\n else:\n raise ValueError\n mt = tmp\n \n rt['overlap'] = len(shared_rows)\n if rt['overlap'] > 50:\n rt['GoldvMT'] = {}\n rt['GoldvPred'] = {}\n rt['MTvPred'] = {}\n for c in shared_columns:\n rt['GoldvMT'][c] = st.pearsonr(gold.loc[shared_rows, c], mt.loc[shared_rows, c])[0]\n rt['GoldvPred'][c] = st.pearsonr(gold.loc[shared_rows, c], pred.loc[shared_rows, c])[0]\n rt['MTvPred'][c] = st.pearsonr(mt.loc[shared_rows, c], pred.loc[shared_rows, c])[0]\n\n return rt\n ",
"_____no_output_____"
]
],
[
[
"Run evaluation for all gold datasets:",
"_____no_output_____"
]
],
[
[
"index = pd.MultiIndex.from_product([utils.conditions.keys(), ['GoldvMT', 'GoldvPred', 'MTvPred']], names=['lexicon', 'measure'])\ndf = pd.DataFrame(index=index, columns =constants.emotions+['overlap'])\n\nfor key, data in utils.conditions.items():\n print(key, end='\\r')\n iso = data['iso']\n if not iso == 'en':\n gold = data['get']()\n # This analysis was done on the respective train sets because using TargetMT\n # rather than TargetPred is only an option for entries known at training time.\n mt = utils.get_TargetMT(iso, split='train')\n pred = utils.get_TargetPred(iso, split='train')\n\n rt = evaluate_translation(gold=gold,\n mt=mt,\n pred=pred)\n \n for measure in ['GoldvMT', 'GoldvPred', 'MTvPred']:\n df.loc[(key, measure), 'overlap'] = rt['overlap']\n if measure in rt:\n for emo in constants.emotions:\n if emo in rt[measure]:\n df.loc[(key, measure), emo] = rt[measure][emo]\n\ndf.to_csv(constants.TRANSLATION_VS_PREDICTION_RESULTS)",
"en1\ren2\ren3\res1\r"
]
],
[
[
"Loading and formatting results:",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv(constants.TRANSLATION_VS_PREDICTION_RESULTS, index_col=[0,1])\ndf",
"_____no_output_____"
],
[
"table = pd.DataFrame(index=['MT', 'Pred', 'Diff'], columns=constants.emotions, data=0.)\ntable.loc['MT'] = df.xs('GoldvMT', level='measure').mean()\ntable.loc['Pred'] = df.xs('GoldvPred', level='measure').mean()\ntable.loc['Diff'] = table.loc['Pred'] - table.loc['MT']\ntable",
"_____no_output_____"
],
[
"s = table.round(3).to_latex(float_format=lambda x: \"{:.3f}\".format(x).lstrip('0'))\nprint(s)",
"\\begin{tabular}{lrrrrrrrr}\n\\toprule\n{} & valence & arousal & dominance & joy & anger & sadness & fear & disgust \\\\\n\\midrule\nMT & .796 & .515 & .613 & .699 & .677 & .636 & .654 & .579 \\\\\nPred & .871 & .652 & .733 & .767 & .734 & .692 & .728 & .650 \\\\\nDiff & .076 & .137 & .119 & .068 & .057 & .056 & .074 & .071 \\\\\n\\bottomrule\n\\end{tabular}\n\n"
]
],
[
[
"---",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
e721ec6895562d9ec7cbebfc143c31529dcbda53 | 10,242 | ipynb | Jupyter Notebook | d2l/chapter_linear-networks/linear-regression-concise.ipynb | atlasbioinfo/myDLNotes_Pytorch | fada6ab56af340cd5ec6cc4dfd5e749af16a6ed4 | [
"MIT"
] | null | null | null | d2l/chapter_linear-networks/linear-regression-concise.ipynb | atlasbioinfo/myDLNotes_Pytorch | fada6ab56af340cd5ec6cc4dfd5e749af16a6ed4 | [
"MIT"
] | null | null | null | d2l/chapter_linear-networks/linear-regression-concise.ipynb | atlasbioinfo/myDLNotes_Pytorch | fada6ab56af340cd5ec6cc4dfd5e749af16a6ed4 | [
"MIT"
] | null | null | null | 21.516807 | 289 | 0.511814 | [
[
[
"# 线性回归的简洁实现\n:label:`sec_linear_concise`\n\n在过去的几年里,出于对深度学习强烈的兴趣,许多公司、学者和业余爱好者开发了各种成熟的开源框架。通过这些框架可以自动化实现基于梯度的学习算法中重复性的工作。\n在 :numref:`sec_linear_scratch` 中,我们只依赖了:(1)通过张量来进行数据存储和线性代数;(2)通过自动微分来计算梯度。实际上,由于数据迭代器、损失函数、优化器和神经网络层很常用,现代深度学习库也为我们实现了这些组件。\n\n在本节中,我们将介绍如何(**通过使用深度学习框架来简洁地实现**) :numref:`sec_linear_scratch` 中的(**线性回归模型**)。\n\n## 生成数据集\n\n与 :numref:`sec_linear_scratch` 中类似,我们首先[**生成数据集**]。\n",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport torch\nfrom torch.utils import data\nfrom d2l import torch as d2l\n",
"_____no_output_____"
],
[
"true_w = torch.tensor([2, -3.4])\ntrue_b = 4.2\nfeatures, labels = d2l.synthetic_data(true_w, true_b, 1000)",
"_____no_output_____"
]
],
[
[
"## 读取数据集\n\n我们可以[**调用框架中现有的API来读取数据**]。我们将 `features` 和 `labels` 作为API的参数传递,并在实例化数据迭代器对象时指定 `batch_size`。此外,布尔值 `is_train` 表示是否希望数据迭代器对象在每个迭代周期内打乱数据。\n",
"_____no_output_____"
]
],
[
[
"def load_array(data_arrays, batch_size, is_train=True): #@save\n \"\"\"构造一个PyTorch数据迭代器。\"\"\"\n dataset = data.TensorDataset(*data_arrays)\n return data.DataLoader(dataset, batch_size, shuffle=is_train)",
"_____no_output_____"
],
[
"batch_size = 10\ndata_iter = load_array((features, labels), batch_size)",
"_____no_output_____"
]
],
[
[
"使用 `data_iter` 的方式与我们在 :numref:`sec_linear_scratch` 中使用 `data_iter` 函数的方式相同。为了验证是否正常工作,让我们读取并打印第一个小批量样本。\n与 :numref:`sec_linear_scratch` 不同,这里我们使用 `iter` 构造Python迭代器,并使用 `next` 从迭代器中获取第一项。\n",
"_____no_output_____"
]
],
[
[
"next(iter(data_iter))",
"_____no_output_____"
]
],
[
[
"## 定义模型\n\n当我们在 :numref:`sec_linear_scratch` 中实现线性回归时,我们明确定义了模型参数变量,并编写了计算的代码,这样通过基本的线性代数运算得到输出。但是,如果模型变得更加复杂,而且当你几乎每天都需要实现模型时,你会想简化这个过程。这种情况类似于从头开始编写自己的博客。做一两次是有益的、有启发性的,但如果每次你每需要一个博客就花一个月的时间重新发明轮子,那你将是一个糟糕的网页开发者。\n\n对于标准操作,我们可以[**使用框架的预定义好的层**]。这使我们只需关注使用哪些层来构造模型,而不必关注层的实现细节。我们首先定义一个模型变量`net`,它是一个 `Sequential` 类的实例。 `Sequential` 类为串联在一起的多个层定义了一个容器。当给定输入数据, `Sequential` 实例将数据传入到第一层,然后将第一层的输出作为第二层的输入,依此类推。在下面的例子中,我们的模型只包含一个层,因此实际上不需要`Sequential`。但是由于以后几乎所有的模型都是多层的,在这里使用`Sequential`会让你熟悉标准的流水线。\n\n回顾 :numref:`fig_single_neuron` 中的单层网络架构,这一单层被称为 *全连接层*(fully-connected layer),因为它的每一个输入都通过矩阵-向量乘法连接到它的每个输出。\n",
"_____no_output_____"
],
[
"在 PyTorch 中,全连接层在 `Linear` 类中定义。值得注意的是,我们将两个参数传递到 `nn.Linear` 中。第一个指定输入特征形状,即 2,第二个指定输出特征形状,输出特征形状为单个标量,因此为 1。\n",
"_____no_output_____"
]
],
[
[
"# `nn` 是神经网络的缩写\nfrom torch import nn\n\nnet = nn.Sequential(nn.Linear(2, 1))\n",
"_____no_output_____"
]
],
[
[
"## (**初始化模型参数**)\n\n在使用`net`之前,我们需要初始化模型参数。如在线性回归模型中的权重和偏置。\n深度学习框架通常有预定义的方法来初始化参数。\n在这里,我们指定每个权重参数应该从均值为0、标准差为0.01的正态分布中随机采样,偏置参数将初始化为零。\n",
"_____no_output_____"
],
[
"正如我们在构造 `nn.Linear` 时指定输入和输出尺寸一样。现在我们直接访问参数以设定初始值。我们通过 `net[0]` 选择网络中的第一个图层,然后使用 `weight.data` 和 `bias.data` 方法访问参数。然后使用替换方法 `normal_` 和 `fill_` 来重写参数值。\n",
"_____no_output_____"
]
],
[
[
"net[0].weight.data.normal_(0, 0.01)\nnet[0].bias.data.fill_(0)",
"_____no_output_____"
]
],
[
[
"\n",
"_____no_output_____"
],
[
"## 定义损失函数\n",
"_____no_output_____"
],
[
"[**计算均方误差使用的是`MSELoss`类,也称为平方 $L_2$ 范数**]。默认情况下,它返回所有样本损失的平均值。\n",
"_____no_output_____"
]
],
[
[
"loss = nn.MSELoss()",
"_____no_output_____"
]
],
[
[
"## 定义优化算法\n",
"_____no_output_____"
],
[
"小批量随机梯度下降算法是一种优化神经网络的标准工具,PyTorch 在 `optim` 模块中实现了该算法的许多变种。当我们(**实例化 `SGD` 实例**)时,我们要指定优化的参数(可通过 `net.parameters()` 从我们的模型中获得)以及优化算法所需的超参数字典。小批量随机梯度下降只需要设置 `lr`值,这里设置为 0.03。\n",
"_____no_output_____"
]
],
[
[
"trainer = torch.optim.SGD(net.parameters(), lr=0.03)",
"_____no_output_____"
]
],
[
[
"## 训练\n\n通过深度学习框架的高级API来实现我们的模型只需要相对较少的代码。\n我们不必单独分配参数、不必定义我们的损失函数,也不必手动实现小批量随机梯度下降。\n当我们需要更复杂的模型时,高级API的优势将大大增加。\n当我们有了所有的基本组件,[**训练过程代码与我们从零开始实现时所做的非常相似**]。\n\n回顾一下:在每个迭代周期里,我们将完整遍历一次数据集(`train_data`),不停地从中获取一个小批量的输入和相应的标签。对于每一个小批量,我们会进行以下步骤:\n\n* 通过调用 `net(X)` 生成预测并计算损失 `l`(正向传播)。\n* 通过进行反向传播来计算梯度。\n* 通过调用优化器来更新模型参数。\n\n为了更好的衡量训练效果,我们计算每个迭代周期后的损失,并打印它来监控训练过程。\n",
"_____no_output_____"
]
],
[
[
"num_epochs = 3\nfor epoch in range(num_epochs):\n for X, y in data_iter:\n l = loss(net(X) ,y)\n trainer.zero_grad()\n l.backward()\n trainer.step()\n l = loss(net(features), labels)\n print(f'epoch {epoch + 1}, loss {l:f}')",
"epoch 1, loss 0.000213\nepoch 2, loss 0.000107\nepoch 3, loss 0.000108\n"
]
],
[
[
"下面我们[**比较生成数据集的真实参数和通过有限数据训练获得的模型参数**]。\n要访问参数,我们首先从 `net` 访问所需的层,然后读取该层的权重和偏置。\n正如在从零开始实现中一样,我们估计得到的参数与生成数据的真实参数非常接近。\n",
"_____no_output_____"
]
],
[
[
"w = net[0].weight.data\nprint('w的估计误差:', true_w - w.reshape(true_w.shape))\nb = net[0].bias.data\nprint('b的估计误差:', true_b - b)",
"w的估计误差: tensor([-0.0003, 0.0008])\nb的估计误差: tensor([-0.0002])\n"
]
],
[
[
"## 小结\n",
"_____no_output_____"
],
[
"* 我们可以使用 PyTorch 的高级 API更简洁地实现模型。\n* 在 PyTorch 中,`data` 模块提供了数据处理工具,`nn` 模块定义了大量的神经网络层和常见损失函数。\n* 我们可以通过`_` 结尾的方法将参数替换,从而初始化参数。\n",
"_____no_output_____"
],
[
"## 练习\n",
"_____no_output_____"
],
[
"1. 如果我们用 `nn.MSELoss()` 替换 `nn.MSELoss(reduction='sum')`,为了使代码的行为相同,需要怎么更改学习速率?为什么?\n1. 查看 PyTorch 文档,了解提供了哪些损失函数和初始化方法。用Huber损失来代替。\n1. 你如何访问 `net[0].weight` 的梯度?\n\n[Discussions](https://discuss.d2l.ai/t/1781)\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e721f8b359b2be923cc5fe8b7250bb00434081b8 | 572,405 | ipynb | Jupyter Notebook | DataCamp Projects/The Android App Market on Google Play/notebook.ipynb | mayank1101/DataCamp | d02f03ddd4ebc1f2271fd409a803d8196279cccd | [
"MIT"
] | 3 | 2020-12-15T19:36:03.000Z | 2021-05-05T07:36:15.000Z | DataCamp Projects/The Android App Market on Google Play/notebook.ipynb | mayank1101/DataCamp | d02f03ddd4ebc1f2271fd409a803d8196279cccd | [
"MIT"
] | null | null | null | DataCamp Projects/The Android App Market on Google Play/notebook.ipynb | mayank1101/DataCamp | d02f03ddd4ebc1f2271fd409a803d8196279cccd | [
"MIT"
] | null | null | null | 572,405 | 572,405 | 0.757072 | [
[
[
"## 1. Google Play Store apps and reviews\n<p>Mobile apps are everywhere. They are easy to create and can be lucrative. Because of these two factors, more and more apps are being developed. In this notebook, we will do a comprehensive analysis of the Android app market by comparing over ten thousand apps in Google Play across different categories. We'll look for insights in the data to devise strategies to drive growth and retention.</p>\n<p><img src=\"https://assets.datacamp.com/production/project_619/img/google_play_store.png\" alt=\"Google Play logo\"></p>\n<p>Let's take a look at the data, which consists of two files:</p>\n<ul>\n<li><code>apps.csv</code>: contains all the details of the applications on Google Play. There are 13 features that describe a given app.</li>\n<li><code>user_reviews.csv</code>: contains 100 reviews for each app, <a href=\"https://www.androidpolice.com/2019/01/21/google-play-stores-redesigned-ratings-and-reviews-section-lets-you-easily-filter-by-star-rating/\">most helpful first</a>. The text in each review has been pre-processed and attributed with three new features: Sentiment (Positive, Negative or Neutral), Sentiment Polarity and Sentiment Subjectivity.</li>\n</ul>",
"_____no_output_____"
]
],
[
[
"# Read in dataset\nimport pandas as pd\napps_with_duplicates = pd.read_csv('datasets/apps.csv')\n\n# Drop duplicates\napps = apps_with_duplicates.drop_duplicates()\n\n# Print the total number of apps\nprint('Total number of apps in the dataset = ', apps.count())\n\n# Print a concise summary of apps dataframe\nprint(apps.info())\n\n# Have a look at a random sample of n rows\nn = 5\napps.sample(n)",
"Total number of apps in the dataset = Unnamed: 0 9659\nApp 9659\nCategory 9659\nRating 8196\nReviews 9659\nSize 8432\nInstalls 9659\nType 9659\nPrice 9659\nContent Rating 9659\nGenres 9659\nLast Updated 9659\nCurrent Ver 9651\nAndroid Ver 9657\ndtype: int64\n<class 'pandas.core.frame.DataFrame'>\nInt64Index: 9659 entries, 0 to 9658\nData columns (total 14 columns):\nUnnamed: 0 9659 non-null int64\nApp 9659 non-null object\nCategory 9659 non-null object\nRating 8196 non-null float64\nReviews 9659 non-null int64\nSize 8432 non-null float64\nInstalls 9659 non-null object\nType 9659 non-null object\nPrice 9659 non-null object\nContent Rating 9659 non-null object\nGenres 9659 non-null object\nLast Updated 9659 non-null object\nCurrent Ver 9651 non-null object\nAndroid Ver 9657 non-null object\ndtypes: float64(2), int64(2), object(10)\nmemory usage: 1.1+ MB\nNone\n"
]
],
[
[
"## 2. Data cleaning\n<p>The four features that we will be working with most frequently henceforth are <code>Installs</code>, <code>Size</code>, <code>Rating</code> and <code>Price</code>. The <code>info()</code> function (from the previous task) told us that <code>Installs</code> and <code>Price</code> columns are of type <code>object</code> and not <code>int64</code> or <code>float64</code> as we would expect. This is because the column contains some characters more than just [0,9] digits. Ideally, we would want these columns to be numeric as their name suggests. <br>\nHence, we now proceed to data cleaning and prepare our data to be consumed in our analyis later. Specifically, the presence of special characters (<code>, $ +</code>) in the <code>Installs</code> and <code>Price</code> columns make their conversion to a numerical data type difficult.</p>",
"_____no_output_____"
]
],
[
[
"# List of characters to remove\nchars_to_remove = ['+', ',', '$']\n# List of column names to clean\ncols_to_clean = ['Installs', 'Price']\n\n# Loop for each column\nfor col in cols_to_clean:\n # Replace each character with an empty string\n for char in chars_to_remove:\n apps[col] = apps[col].astype(str).str.replace(char, '')\n # Convert col to numeric\n apps[col] = pd.to_numeric(apps[col]) ",
"_____no_output_____"
]
],
[
[
"## 3. Exploring app categories\n<p>With more than 1 billion active users in 190 countries around the world, Google Play continues to be an important distribution platform to build a global audience. For businesses to get their apps in front of users, it's important to make them more quickly and easily discoverable on Google Play. To improve the overall search experience, Google has introduced the concept of grouping apps into categories.</p>\n<p>This brings us to the following questions:</p>\n<ul>\n<li>Which category has the highest share of (active) apps in the market? </li>\n<li>Is any specific category dominating the market?</li>\n<li>Which categories have the fewest number of apps?</li>\n</ul>\n<p>We will see that there are <code>33</code> unique app categories present in our dataset. <em>Family</em> and <em>Game</em> apps have the highest market prevalence. Interestingly, <em>Tools</em>, <em>Business</em> and <em>Medical</em> apps are also at the top.</p>",
"_____no_output_____"
]
],
[
[
"import plotly\nplotly.offline.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\n\n# Print the total number of unique categories\nnum_categories = len(apps['Category'].unique())\nprint('Number of categories = ', num_categories)\n\n# Count the number of apps in each 'Category' and sort them in descending order\nnum_apps_in_category = apps['Category'].value_counts().sort_values(ascending = False)\n\ndata = [go.Bar(\n x = num_apps_in_category.index, # index = category name\n y = num_apps_in_category.values, # value = count\n)]\n\nplotly.offline.iplot(data)",
"_____no_output_____"
]
],
[
[
"## 4. Distribution of app ratings\n<p>After having witnessed the market share for each category of apps, let's see how all these apps perform on an average. App ratings (on a scale of 1 to 5) impact the discoverability, conversion of apps as well as the company's overall brand image. Ratings are a key performance indicator of an app.</p>\n<p>From our research, we found that the average volume of ratings across all app categories is <code>4.17</code>. The histogram plot is skewed to the left indicating that the majority of the apps are highly rated with only a few exceptions in the low-rated apps.</p>",
"_____no_output_____"
]
],
[
[
"# Average rating of apps\navg_app_rating = apps['Rating'].mean()\nprint('Average app rating = ', avg_app_rating)\n\n# Distribution of apps according to their ratings\ndata = [go.Histogram(\n x = apps['Rating']\n)]\n\n# Vertical dashed line to indicate the average app rating\nlayout = {'shapes': [{\n 'type' :'line',\n 'x0': avg_app_rating,\n 'y0': 0,\n 'x1': avg_app_rating,\n 'y1': 1000,\n 'line': { 'dash': 'dashdot'}\n }]\n }\n\nplotly.offline.iplot({'data': data, 'layout': layout})",
"Average app rating = 4.173243045387994\n"
]
],
[
[
"## 5. Size and price of an app\n<p>Let's now examine app size and app price. For size, if the mobile app is too large, it may be difficult and/or expensive for users to download. Lengthy download times could turn users off before they even experience your mobile app. Plus, each user's device has a finite amount of disk space. For price, some users expect their apps to be free or inexpensive. These problems compound if the developing world is part of your target market; especially due to internet speeds, earning power and exchange rates.</p>\n<p>How can we effectively come up with strategies to size and price our app?</p>\n<ul>\n<li>Does the size of an app affect its rating? </li>\n<li>Do users really care about system-heavy apps or do they prefer light-weighted apps? </li>\n<li>Does the price of an app affect its rating? </li>\n<li>Do users always prefer free apps over paid apps?</li>\n</ul>\n<p>We find that the majority of top rated apps (rating over 4) range from 2 MB to 20 MB. We also find that the vast majority of apps price themselves under \\$10.</p>",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport seaborn as sns\nsns.set_style(\"darkgrid\")\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# Filter rows where both Rating and Size values are not null\napps_with_size_and_rating_present = apps[(~apps['Rating'].isnull()) & (~apps['Size'].isnull())]\n\n# Subset for categories with at least 250 apps\nlarge_categories = apps_with_size_and_rating_present.groupby('Category').filter(lambda x: len(x) >= 250).reset_index()\n\n# Plot size vs. rating\nplt1 = sns.jointplot(x = large_categories['Size'], y = large_categories['Rating'], kind = 'hex')\n\n# Subset apps whose 'Type' is 'Paid'\npaid_apps = apps_with_size_and_rating_present[apps_with_size_and_rating_present['Type'] == 'Paid']\n\n# Plot price vs. rating\nplt2 = sns.jointplot(x = paid_apps['Price'], y = paid_apps['Rating'])",
"_____no_output_____"
]
],
[
[
"## 6. Relation between app category and app price\n<p>So now comes the hard part. How are companies and developers supposed to make ends meet? What monetization strategies can companies use to maximize profit? The costs of apps are largely based on features, complexity, and platform.</p>\n<p>There are many factors to consider when selecting the right pricing strategy for your mobile app. It is important to consider the willingness of your customer to pay for your app. A wrong price could break the deal before the download even happens. Potential customers could be turned off by what they perceive to be a shocking cost, or they might delete an app they’ve downloaded after receiving too many ads or simply not getting their money's worth.</p>\n<p>Different categories demand different price ranges. Some apps that are simple and used daily, like the calculator app, should probably be kept free. However, it would make sense to charge for a highly-specialized medical app that diagnoses diabetic patients. Below, we see that <em>Medical and Family</em> apps are the most expensive. Some medical apps extend even up to \\$80! All game apps are reasonably priced below \\$20.</p>",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nfig, ax = plt.subplots()\nfig.set_size_inches(15, 8)\n\n# Select a few popular app categories\npopular_app_cats = apps[apps.Category.isin(['GAME', 'FAMILY', 'PHOTOGRAPHY',\n 'MEDICAL', 'TOOLS', 'FINANCE',\n 'LIFESTYLE','BUSINESS'])]\n\n# Examine the price trend by plotting Price vs Category\nax = sns.stripplot(x = popular_app_cats['Price'], y = popular_app_cats['Category'], jitter=True, linewidth=1)\nax.set_title('App pricing trend across categories')\n\n# Apps whose Price is greater than 200\napps_above_200 = popular_app_cats[['Category', 'App', 'Price']][popular_app_cats['Price'] > 200]\napps_above_200",
"_____no_output_____"
]
],
[
[
"## 7. Filter out \"junk\" apps\n<p>It looks like a bunch of the really expensive apps are \"junk\" apps. That is, apps that don't really have a purpose. Some app developer may create an app called <em>I Am Rich Premium</em> or <em>most expensive app (H)</em> just for a joke or to test their app development skills. Some developers even do this with malicious intent and try to make money by hoping people accidentally click purchase on their app in the store.</p>\n<p>Let's filter out these junk apps and re-do our visualization.</p>",
"_____no_output_____"
]
],
[
[
"# Select apps priced below $100\napps_under_100 = popular_app_cats[popular_app_cats.Price < 100]\n\nfig, ax = plt.subplots()\nfig.set_size_inches(15, 8)\n\n# Examine price vs category with the authentic apps (apps_under_100)\nax = sns.stripplot(x=apps_under_100['Price'], y=apps_under_100['Category'], \n data=apps_under_100 ,jitter=True, linewidth=1)\nax.set_title('App pricing trend across categories after filtering for junk apps')",
"_____no_output_____"
]
],
[
[
"## 8. Popularity of paid apps vs free apps\n<p>For apps in the Play Store today, there are five types of pricing strategies: free, freemium, paid, paymium, and subscription. Let's focus on free and paid apps only. Some characteristics of free apps are:</p>\n<ul>\n<li>Free to download.</li>\n<li>Main source of income often comes from advertisements.</li>\n<li>Often created by companies that have other products and the app serves as an extension of those products.</li>\n<li>Can serve as a tool for customer retention, communication, and customer service.</li>\n</ul>\n<p>Some characteristics of paid apps are:</p>\n<ul>\n<li>Users are asked to pay once for the app to download and use it.</li>\n<li>The user can't really get a feel for the app before buying it.</li>\n</ul>\n<p>Are paid apps installed as much as free apps? It turns out that paid apps have a relatively lower number of installs than free apps, though the difference is not as stark as I would have expected!</p>",
"_____no_output_____"
]
],
[
[
"trace0 = go.Box(\n # Data for paid apps\n y=apps[apps['Type'] == 'Paid']['Installs'],\n name = 'Paid'\n)\n\ntrace1 = go.Box(\n # Data for free apps\n y=apps[apps['Type'] == 'Free']['Installs'],\n name = 'Free'\n)\n\nlayout = go.Layout(\n title = \"Number of downloads of paid apps vs. free apps\",\n yaxis = dict(\n type = 'log',\n autorange = True\n )\n)\n\n# Add trace0 and trace1 to a list for plotting\ndata = [trace0, trace1]\nplotly.offline.iplot({'data': data, 'layout': layout})",
"_____no_output_____"
]
],
[
[
"## 9. Sentiment analysis of user reviews\n<p>Mining user review data to determine how people feel about your product, brand, or service can be done using a technique called sentiment analysis. User reviews for apps can be analyzed to identify if the mood is positive, negative or neutral about that app. For example, positive words in an app review might include words such as 'amazing', 'friendly', 'good', 'great', and 'love'. Negative words might be words like 'malware', 'hate', 'problem', 'refund', and 'incompetent'.</p>\n<p>By plotting sentiment polarity scores of user reviews for paid and free apps, we observe that free apps receive a lot of harsh comments, as indicated by the outliers on the negative y-axis. Reviews for paid apps appear never to be extremely negative. This may indicate something about app quality, i.e., paid apps being of higher quality than free apps on average. The median polarity score for paid apps is a little higher than free apps, thereby syncing with our previous observation.</p>\n<p>In this notebook, we analyzed over ten thousand apps from the Google Play Store. We can use our findings to inform our decisions should we ever wish to create an app ourselves.</p>",
"_____no_output_____"
]
],
[
[
"# Load user_reviews.csv\nreviews_df = ...\n\n# Join and merge the two dataframe\nmerged_df = pd.merge(..., ..., on = ..., how = \"inner\")\n\n# Drop NA values from Sentiment and Translated_Review columns\nmerged_df = merged_df.dropna(subset=['Sentiment', 'Translated_Review'])\n\nsns.set_style('ticks')\nfig, ax = plt.subplots()\nfig.set_size_inches(11, 8)\n\n# User review sentiment polarity for paid vs. free apps\nax = sns.boxplot(x = ..., y = ..., data = ...)\nax.set_title('Sentiment Polarity Distribution')",
"_____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"
]
] |
e7220444f4122731500bde090997d7644fb4975d | 11,546 | ipynb | Jupyter Notebook | Bloque 3 - Machine Learning/05_Deep_Learning/1-Intro Deep Learning/ejercicios/01_DL_Clasificación.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 | e81cbdcb9254fa46a3925f41c583748e25b459c0 | [
"MIT"
] | null | null | null | Bloque 3 - Machine Learning/05_Deep_Learning/1-Intro Deep Learning/ejercicios/01_DL_Clasificación.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 | e81cbdcb9254fa46a3925f41c583748e25b459c0 | [
"MIT"
] | null | null | null | Bloque 3 - Machine Learning/05_Deep_Learning/1-Intro Deep Learning/ejercicios/01_DL_Clasificación.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 | e81cbdcb9254fa46a3925f41c583748e25b459c0 | [
"MIT"
] | 1 | 2021-01-23T10:37:15.000Z | 2021-01-23T10:37:15.000Z | 24.991342 | 303 | 0.549974 | [
[
[
"# Clasificación Básica: Predecir una imagen de moda",
"_____no_output_____"
],
[
"En el siguiente notebook entrenaremos un modelo de redes neuronales para clasificar imágenes de ropa, como zapatos y camisetas.\n\nPara ello, utilizaremos las librerías tanto keras como Tensorflow, en concreto, centrándonos en la primera [tf.keras](https://www.tensorflow.org/guide/keras).",
"_____no_output_____"
]
],
[
[
"# TensorFlow y tf.keras\nimport tensorflow as tf\nfrom tensorflow import keras\n\n# Librerias de ayuda\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nprint(tf.__version__)",
"2.4.1\n"
]
],
[
[
"## Importar el set de datos de moda de MNIST",
"_____no_output_____"
],
[
"Utilizaremos el datest de [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist), que contiene mas de 70,000 imágenes de 10 categorías. Las imágenes muestran artículos individuales de ropa a una resolución baja (28 por 28 pixeles), tal como se ve en la siguiente imagen:\n\n<table>\n <tr><td>\n <img src=\"https://tensorflow.org/images/fashion-mnist-sprite.png\"\n alt=\"Fashion MNIST sprite\" width=\"600\">\n </td></tr>\n <tr><td align=\"center\">\n <b>Figure 1.</b> <a href=\"https://github.com/zalandoresearch/fashion-mnist\">Fashion-MNIST samples</a> (by Zalando, MIT License).<br/> \n </td></tr>\n</table>\n\nPara importar y cargar el set de datos de MNIST directamente de TensorFlow:",
"_____no_output_____"
]
],
[
[
"fashion_mnist = keras.datasets.fashion_mnist\n\n(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()",
"_____no_output_____"
]
],
[
[
"La *class* de ropa que la imagen representa.\n\n<table>\n <tr>\n <th>Label</th>\n <th>Class</th>\n </tr>\n <tr>\n <td>0</td>\n <td>T-shirt/top</td>\n </tr>\n <tr>\n <td>1</td>\n <td>Trouser</td>\n </tr>\n <tr>\n <td>2</td>\n <td>Pullover</td>\n </tr>\n <tr>\n <td>3</td>\n <td>Dress</td>\n </tr>\n <tr>\n <td>4</td>\n <td>Coat</td>\n </tr>\n <tr>\n <td>5</td>\n <td>Sandal</td>\n </tr>\n <tr>\n <td>6</td>\n <td>Shirt</td>\n </tr>\n <tr>\n <td>7</td>\n <td>Sneaker</td>\n </tr>\n <tr>\n <td>8</td>\n <td>Bag</td>\n </tr>\n <tr>\n <td>9</td>\n <td>Ankle boot</td>\n </tr>\n</table>\n\nCada imagen es mapeada a una única etiqueta. Ya que los *Class names* no están incluidos en el dataset, los guardamos en la siguiente lista:",
"_____no_output_____"
]
],
[
[
"class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',\n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']",
"_____no_output_____"
]
],
[
[
"## Explora el set de datos:\n\n* ¿Cuántas imaágenes hay en train?\n* ¿Y en test?\n* ¿De cuántos pixels se compone cada imagen?\n* ¿Cuáles son los valores de los labels?",
"_____no_output_____"
],
[
"## Pre-procesamiento del set de datos\n\n### Representando imágenes\n\nInspecciona y representa la primera imagen del dataset de train. Para ello, utiliza la función `imshow` de matplotlib.",
"_____no_output_____"
],
[
"### Escalado\n\nEscala los conjuntos de train y test para que vayan del 0 al 1. No hace falta usar ninguna librería, con realizar una división en cada conjunto será suficiente.",
"_____no_output_____"
],
[
"### Mostrando imágenes\n\nPara verificar que el set de datos esta en el formato adecuado y que están listos para construir y entrenar la red, muestra las primeras 25 imágenes del *training set* y el nombre de cada clase debajo de cada imagen.\n\nPara ello, utiliza la función ``plt.imshow()`` y los labels de los ejes. Además, puedes utilizar un subplot de 5x5 para que se muestren los datos de una forma más legible:",
"_____no_output_____"
],
[
"# Construir el Modelo\n\nPasemos a construir la red neuronal requiere configurar las capas del modelo y luego compilar el modelo.",
"_____no_output_____"
],
[
"### Configurar las Capas\n\nConstruye un modelo con keras, donde especifiques las siguientes capas:\n * **Entrada**: hemos visto que tienen que ser de un tipo concreto y de un tamaño definido por los datos de entrada del modelo\n * **Hidden layers**: 1 capa densa de 128 neuronas\n * **Salida**: una capa con tantas neuronas como clases tengamos que predecir",
"_____no_output_____"
],
[
"### Compila el modelo\n\nAntes de que el modelo este listo para entrenar , se necesitan algunas configuraciones más. Estas son agregadas durante el paso de compilación del modelo:\n\n* **Loss function**: mide la exactitud del modelo durante el entrenamiento. Busca minimizar esta función para dirigir el modelo en la dirección adecuada.\n* **Optimizer**: indica cómo el modelo se actualiza basado en el set de datos que ve y la función de pérdida.\n* **Metrics**: utilizado para monitorear los pasos de train y test.\n\nComo es un problema de clasificación multiclase, tendrás que usar `sparse_categorical_crossentropy` como función de coste. En cuanto a las métricas, usa simplemente `accuracy`. Como optimizador, empezaremos utilizando ``adam``.",
"_____no_output_____"
],
[
"### Entrenar el Modelo\n\nEmpieza entrenándolo con 10 epochs:",
"_____no_output_____"
],
[
"## Evaluar Accuracy\n\nUna vez lo hemos entrenado, prueba el rendimiento del modelo con los datos de test:",
"_____no_output_____"
],
[
"## Predecir\n\nCon el modelo entrenado podemos realizar predicciones sobre imágenes. Utiliza el modelo para ver qué obtenemos con las imágenes de test. Comprueba las 5 primeras imágenes.\n\nUna prediccion es un array de 10 números. Estos representan el nivel de \"confianza\" del modelo sobre las imágenes de cada uno de los 10 artículos de moda/ropa. Puedes revisar cuál tiene el nivel más alto de confianza para identificar a qué clase se corresponde.",
"_____no_output_____"
],
[
"### Comprobaciones globales\n\nUtiliza lo que acabas de ver para evaluar cómo de bien predecimos cada clase de ropa:",
"_____no_output_____"
],
[
"### EXTRA\n\nComo has podido ver, hemos utilizado una configuración en concreto. Sin embargo, hemos comentado que estos parámetros pueden ser cambiados y obtener diferentes resultados. Por ello, proeba a cambiar diferentes parámetros buscando el mejor modelo posible basado en el score de los datos de test.\n\nPrueba cambiando:\n * Número de neuronas\n * Optimizador\n * Nº epochs (¿early stopping?)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7220b1e252c4aa178aefba4d42285957e253a2b | 5,312 | ipynb | Jupyter Notebook | examples/notebook/contrib/broken_weights.ipynb | jspricke/or-tools | 45770b833997f827d322e929b1ed4781c4e60d44 | [
"Apache-2.0"
] | 1 | 2020-07-18T16:24:09.000Z | 2020-07-18T16:24:09.000Z | examples/notebook/contrib/broken_weights.ipynb | jspricke/or-tools | 45770b833997f827d322e929b1ed4781c4e60d44 | [
"Apache-2.0"
] | 1 | 2021-02-23T10:22:55.000Z | 2021-02-23T13:57:14.000Z | examples/notebook/contrib/broken_weights.ipynb | jspricke/or-tools | 45770b833997f827d322e929b1ed4781c4e60d44 | [
"Apache-2.0"
] | 1 | 2021-03-16T14:30:59.000Z | 2021-03-16T14:30:59.000Z | 35.891892 | 86 | 0.556099 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e7221162ee0cfad90e0fb404c8fd6d970cc60f3d | 5,481 | ipynb | Jupyter Notebook | Public/Src/Cache/MultiTool/scripts/Parse SST Recompression.ipynb | BearerPipelineTest/BuildXL | 121d6342963ef66f7e4365476ee80a20a4234db6 | [
"MIT"
] | 448 | 2018-11-07T21:00:58.000Z | 2019-05-06T17:29:34.000Z | Public/Src/Cache/MultiTool/scripts/Parse SST Recompression.ipynb | BearerPipelineTest/BuildXL | 121d6342963ef66f7e4365476ee80a20a4234db6 | [
"MIT"
] | 496 | 2019-05-06T21:38:22.000Z | 2022-03-14T18:17:14.000Z | Public/Src/Cache/MultiTool/scripts/Parse SST Recompression.ipynb | BearerPipelineTest/BuildXL | 121d6342963ef66f7e4365476ee80a20a4234db6 | [
"MIT"
] | 88 | 2019-05-08T08:28:45.000Z | 2022-03-24T23:43:21.000Z | 33.420732 | 576 | 0.543514 | [
[
[
"import pandas as pd\nimport re\nimport os\nimport pathlib",
"_____no_output_____"
],
[
"INPUT_PATH = pathlib.Path('D:\\checkpoints')\n\ndef attempt_convert(v):\n try:\n try:\n return int(v)\n except:\n return float(v)\n except:\n return v\n\ndf = []\nextract_block_size_regex = re.compile(r'Block Size: (?P<BlockSize>[0-9]+)')\nextract_compression_regex = re.compile(r'Compression: (?P<CompressionType>[^\\s]+)\\s*Compression level: (?P<CompressionLevel>[0-9]+)\\s*Size:\\s*(?P<CompressedSize>[0-9]+)\\s*Blocks:\\s*(?P<NumBlocks>[0-9]+)\\s*Time Taken:\\s*(?P<TimeTakenMicros>[0-9]+)\\s*microsecs\\s*Compressed:\\s*(?P<Compressed>[0-9]+)\\s*\\(\\s*(?P<CompressedPct>.*?)%\\)\\s*Not compressed \\(ratio\\):\\s*(?P<NotCompressedRatio>[0-9]+)\\s*\\(\\s*(?P<NotCompressedRatioPct>.*?)%\\)\\s*Not compressed \\(abort\\):\\s*(?P<NotCompressedAbort>[0-9]+)\\s*\\(\\s*(?P<NotCompressedAbortPct>.*?)%\\)')\nfor checkpoint in os.listdir(INPUT_PATH):\n checkpoint_path = INPUT_PATH / checkpoint\n for sst in os.listdir(checkpoint_path):\n sst_path = checkpoint_path / sst\n if not sst_path.match('*.compression*.txt'):\n continue\n \n contents = sst_path.read_text()\n if 'Not able to read table properties' in contents:\n continue\n \n try:\n block_size = int(extract_block_size_regex.search(contents).group('BlockSize'))\n checkpoint = checkpoint_path.stem\n for algorithm in extract_compression_regex.finditer(contents):\n entry = {k: attempt_convert(v) for k, v in algorithm.groupdict().items()}\n entry['BlockSize'] = block_size\n entry['Path'] = str(sst_path)\n entry['Checkpoint'] = checkpoint\n df.append(entry)\n except Exception as e:\n print(e)\n print(contents)\n \n\ndf = pd.DataFrame(df)\n\n# Sanitize compression algorithm names\ndef rename_compression_types(compression_type):\n renamer = {\n 'kNoCompression': 'uncompressed',\n 'kSnappyCompression': 'snappy',\n 'kZlibCompression': 'zlib',\n 'kLZ4Compression': 'lz4',\n 'kLZ4HCCompression': 'lz4hc',\n 'kZSTD': 'zstd'\n }\n return renamer[compression_type]\n\ndf['CompressionType'] = df['CompressionType'].apply(rename_compression_types)\n\n# Compute compression rate\nuncompressed = df[df['CompressionType'] == 'uncompressed'][['Path', 'CompressedSize']].drop_duplicates()\nuncompressed.rename(columns={'CompressedSize': 'UncompressedSize'}, inplace=True)\ndf = df.merge(uncompressed)\ndel uncompressed\n\ndf['CompressionRate'] = (1.0 - df['CompressedSize']/df['UncompressedSize'])\n\n# Filter out uncompressed, they are useless\ndf = df[df['CompressionType'] != 'uncompressed']",
"_____no_output_____"
],
[
"df.to_csv('dataset.csv')",
"_____no_output_____"
],
[
"cf = df.groupby(['Checkpoint', 'CompressionType', 'BlockSize']).sum()[['CompressedSize', 'UncompressedSize']]\ncf['CompressionRate'] = cf['CompressedSize']/cf['UncompressedSize']\nsnappySizes = []\nfor idx, data in cf.iterrows():\n snappySizes.append(cf.loc[(idx[0], 'snappy', idx[2])]['CompressedSize'])\ncf['BaselineCompressedSize'] = snappySizes\ncf['BaselineCompressionRate'] = cf['BaselineCompressedSize'] / cf['UncompressedSize']\n# A smaller compression rate means a lower size\ncf['BaselineCompressionImprovement'] = cf['BaselineCompressionRate'] - cf['CompressionRate']\ndel snappySizes\ndel cf['BaselineCompressedSize']",
"_____no_output_____"
],
[
"cf.sort_values(by=['BaselineCompressionImprovement'], ascending=False)",
"_____no_output_____"
],
[
"cf",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7221945db984e56216048d0a00f72baf7fb5f3f | 532,591 | ipynb | Jupyter Notebook | docs/source/examples/dynamical_magnetic_xray.ipynb | theodoho/udkm1Dsim | 1d2c10bc052f0b6ebb8f65c45cf8ce3f32dddddb | [
"MIT"
] | null | null | null | docs/source/examples/dynamical_magnetic_xray.ipynb | theodoho/udkm1Dsim | 1d2c10bc052f0b6ebb8f65c45cf8ce3f32dddddb | [
"MIT"
] | null | null | null | docs/source/examples/dynamical_magnetic_xray.ipynb | theodoho/udkm1Dsim | 1d2c10bc052f0b6ebb8f65c45cf8ce3f32dddddb | [
"MIT"
] | null | null | null | 496.819963 | 120,336 | 0.944697 | [
[
[
"# Dynamical Magnetic X-ray Scattering\r\n\r\nIn this example static and transient magnetic X-ray simulations are carried out employing a dynamical magnetic X-ray scattering formalism which was adapted from [Project Dyna](http://dyna.neel.cnrs.fr).",
"_____no_output_____"
],
[
"## Setup\n\nDo all necessary imports and settings.",
"_____no_output_____"
]
],
[
[
"import udkm1Dsim as ud\nu = ud.u # import the pint unit registry from udkm1Dsim\nimport scipy.constants as constants\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nu.setup_matplotlib() # use matplotlib with pint units",
"_____no_output_____"
]
],
[
[
"## Structure\n\nRefer to the [structure-example](structure.ipynb) for more details.\n\nIn this example the sample `Structure` consists of `AmorphousLayer`s.\n\nIn order to build an antiferromagnetic sample two different types of _Fe_ `Atom`s and `AmorphousLayer`s are created with opposite in-plane magnetization.\n\nHere a local file for the atomic scattering factor is read only for Fe atoms.",
"_____no_output_____"
]
],
[
[
"Fe_right = ud.Atom('Fe', mag_amplitude=1, mag_phi=90*u.deg, mag_gamma=90*u.deg,\n atomic_form_factor_path='./Fe.cf')\nFe_left = ud.Atom('Fe', mag_amplitude=1, mag_phi=90*u.deg, mag_gamma=270*u.deg,\n atomic_form_factor_path='./Fe.cf')\nCr = ud.Atom('Cr')\nSi = ud.Atom('Si')",
"_____no_output_____"
],
[
"density_Fe = 7874*u.kg/u.m**3\n\nprop_Fe = {}\nprop_Fe['heat_capacity'] = 449*u.J/u.kg/u.K\nprop_Fe['therm_cond'] = 80*u.W/(u.m *u.K)\nprop_Fe['lin_therm_exp'] = 11.8e-6\nprop_Fe['sound_vel'] = 4.910*u.nm/u.ps\nprop_Fe['opt_ref_index'] = 2.9174+3.3545j\n\nlayer_Fe_left = ud.AmorphousLayer('Fe_left', 'Fe left amorphous', 1*u.nm, density_Fe, atom=Fe_left, **prop_Fe)\nlayer_Fe_right = ud.AmorphousLayer('Fe_right', 'Fe right amorphous', 1*u.nm, density_Fe, atom=Fe_right, **prop_Fe)",
"_____no_output_____"
],
[
"density_Cr = 7140*u.kg/u.m**3\n\nprop_Cr = {}\nprop_Cr['heat_capacity'] = 449*u.J/u.kg/u.K\nprop_Cr['therm_cond'] = 94*u.W/(u.m *u.K)\nprop_Cr['lin_therm_exp'] = 6.2e-6\nprop_Cr['sound_vel'] = 5.940*u.nm/u.ps\nprop_Cr['opt_ref_index'] = 3.1612+3.4606j\n\nlayer_Cr = ud.AmorphousLayer('Cr', \"Cr amorphous\", 1*u.nm, density_Cr, atom=Cr, **prop_Cr)",
"_____no_output_____"
],
[
"density_Si = 2336*u.kg/u.m**3\n\nprop_Si = {}\nprop_Si['heat_capacity'] = 703*u.J/u.kg/u.K\nprop_Si['therm_cond'] = 150*u.W/(u.m *u.K)\nprop_Si['lin_therm_exp'] = 2.6e-6\nprop_Si['sound_vel'] = 8.433*u.nm/u.ps\nprop_Si['opt_ref_index'] = 3.6941+0.0065435j\n\nlayer_Si = ud.AmorphousLayer('Si', \"Si amorphous\", 1*u.nm, density_Si, atom=Si, **prop_Si)",
"_____no_output_____"
],
[
"S = ud.Structure('Fe/Cr AFM Super Lattice')\n\n# create a sub-structure\nDL = ud.Structure('Two Fe/Cr Double Layers')\nDL.add_sub_structure(layer_Fe_left, 1)\nDL.add_sub_structure(layer_Cr, 1)\nDL.add_sub_structure(layer_Fe_right, 1)\nDL.add_sub_structure(layer_Cr, 1)\n\nS.add_sub_structure(DL, 10)\nS.add_sub_structure(layer_Fe_left, 10)\nS.add_sub_structure(layer_Si, 200)",
"_____no_output_____"
],
[
"S.visualize()",
"_____no_output_____"
]
],
[
[
"## Heat\n\nRefer to the [heat-example](heat.ipynb) for more details.",
"_____no_output_____"
]
],
[
[
"h = ud.Heat(S, True)\n\nh.save_data = False\nh.disp_messages = True\n\nh.excitation = {'fluence': [40]*u.mJ/u.cm**2,\n 'delay_pump': [0]*u.ps,\n 'pulse_width': [1]*u.ps,\n 'multilayer_absorption': True,\n 'wavelength': 800*u.nm,\n 'theta': 45*u.deg}\n\n# enable heat diffusion\nh.heat_diffusion = True\n\n# temporal and spatial grid\ndelays = np.r_[-2:40:0.1]*u.ps\n_, _, distances = S.get_distances_of_layers()",
"_____no_output_____"
],
[
"temp_map, delta_temp_map = h.get_temp_map(delays, 0*u.K)",
"Surface incidence fluence scaled by factor 0.7071 due to incidence angle theta=45.00 deg\nCalculating _heat_diffusion_ for excitation 1:1 ...\nAbsorption profile is calculated by multilayer formalism.\nTotal reflectivity of 47.7 % and transmission of 6.4 %.\n"
],
[
"plt.figure(figsize=[6, 8])\nplt.subplot(2, 1, 1)\nplt.plot(distances.to('nm').magnitude, temp_map[20, :], label='{:0.2f} ps'.format(delays[20].to('ps').magnitude))\nplt.plot(distances.to('nm').magnitude, temp_map[-1, :], label='{:0.2f} ps'.format(delays[-1].to('ps').magnitude))\nplt.xlim([0, distances.to('nm').magnitude[-1]])\nplt.xlabel('Distance [nm]')\nplt.ylabel('Temperature [K]')\nplt.legend()\nplt.title('Temperature Profile')\n\nplt.subplot(2, 1, 2)\nplt.pcolormesh(distances.to('nm').magnitude, delays.to('ps').magnitude, temp_map)\nplt.colorbar()\nplt.xlabel('Distance [nm]')\nplt.ylabel('Delay [ps]')\nplt.title('Temperature Map')\n\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Numerical Phonons\n\nRefer to the [phonons-example](phonons.ipynb) for more details.",
"_____no_output_____"
]
],
[
[
"p = ud.PhononNum(S, True)\np.save_data = False\np.disp_messages = True",
"_____no_output_____"
],
[
"strain_map = p.get_strain_map(delays, temp_map, delta_temp_map)",
"Calculating linear thermal expansion ...\nCalculating coherent dynamics with ODE solver ...\n"
],
[
"plt.figure(figsize=[6, 8])\nplt.subplot(2, 1, 1)\nplt.plot(distances.to('nm').magnitude, strain_map[130, :], label=np.round(delays[130]))\nplt.plot(distances.to('nm').magnitude, strain_map[-1, :], label=np.round(delays[-1]))\nplt.xlim([0, distances.to('nm').magnitude[-1]])\nplt.xlabel('Distance [nm]')\nplt.ylabel('Strain')\nplt.legend()\nplt.title('Strain Profile')\n\nplt.subplot(2, 1, 2)\nplt.pcolormesh(distances.to('nm').magnitude, delays.to('ps').magnitude,\n strain_map, cmap='RdBu',\n vmin=-np.max(strain_map), vmax=np.max(strain_map))\nplt.colorbar()\nplt.xlabel('Distance [nm]')\nplt.ylabel('Delay [ps]')\nplt.title('Strain Map')\n\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Magnetization\r\n\r\nThe `Magnetization` class is currently only an interface to allow the user for defining specific magnetization dynamics depending on the `strain_map` and `temp_map`.\r\n\r\nHere the magnetization as function of temperature is used as a simplified model to alter the transient magnetization amplitude.",
"_____no_output_____"
]
],
[
[
"def magnetization_bloch(x,Tc, M0, beta):\r\n m = M0*((1-(x/Tc)**(3/2))**beta)*np.heaviside(Tc-x, 0.5)\r\n m[np.isnan(m)] = 0\r\n return m\r\n\r\nplt.figure()\r\ntemperatures = np.r_[10:1000:0.1]\r\nplt.plot(temperatures, magnetization_bloch(temperatures, 770, 1, 0.75))\r\nplt.xlabel('Temperature [K]')\r\nplt.ylabel('Magneitzation')\r\nplt.show()",
"c:\\users\\schick\\general\\python\\wpy64-3770\\python-3.7.7.amd64\\lib\\site-packages\\ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in power\n \n"
]
],
[
[
"The `calc_magnetization_map` method must be overwritten to allow for calculating magnetization dynamics.",
"_____no_output_____"
]
],
[
[
"class SimpleMagnetization(ud.Magnetization):\r\n\r\n def calc_magnetization_map(self, delays, **kwargs):\r\n strain_map = kwargs['strain_map']\r\n temp_map = kwargs['temp_map']\r\n T_c = kwargs['T_c']\r\n magnetization_map = np.zeros([len(delays), self.S.get_number_of_layers(), 3])\r\n \r\n handles = self.S.get_layer_vectors()[2]\r\n \r\n for i, handle in enumerate(handles):\r\n if handle.id in ['Fe_left', 'Fe_right']:\r\n magnetization_map[:, i, 0] = magnetization_bloch(temp_map[:, i], T_c, 1, .75)\r\n handle.magnetization['phi']\r\n magnetization_map[:, i, 1] = handle.magnetization['phi'].to_base_units().magnitude\r\n magnetization_map[:, i, 2] = handle.magnetization['gamma'].to_base_units().magnitude\r\n \r\n return magnetization_map",
"_____no_output_____"
],
[
"mag = SimpleMagnetization(S, True)\nmag.save_data = False\n\nmagnetization_map = mag.get_magnetization_map(delays,\n strain_map=strain_map,\n temp_map=temp_map,\n T_c = 770)",
"Calculating _magnetization_map_ ...\nElapsed time for _magnetization_map_: 0.097714 s\n"
],
[
"plt.figure()\nplt.pcolormesh(distances.to('nm').magnitude, delays.to('ps').magnitude, magnetization_map[:, :, 0])\nplt.title('Magnetization Amplitude Map')\nplt.ylabel('Delay [ps]')\nplt.xlabel('Distance [nm]')\nplt.colorbar()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Initialize dynamical magnetic X-ray simulations\n\nThe `XrayDynMag` class requires a `Structure` object and a boolean `force_recalc` in order overwrite previous simulation results.\n\nThese results are saved in the `cache_dir` when `save_data` is enabled.\nPrinting simulation messages can be en-/disabled using `disp_messages` and progress bars can using the boolean switch `progress_bar`.",
"_____no_output_____"
]
],
[
[
"dyn_mag = ud.XrayDynMag(S, True)\ndyn_mag.disp_messages = True\ndyn_mag.save_data = False",
"incoming polarizations set to: sigma\nanalyzer polarizations set to: unpolarized\n"
]
],
[
[
"## Homogeneous magnetic X-ray scattering\n\nFor the case of homogeneously strained/magnetized samples, the dynamical magnetic X-ray scattering simulations can be greatly simplified, which saves a lot of computational time.",
"_____no_output_____"
],
[
"### $q_z$-scan\n\nThe `XrayDynMag` object requires an `energy` and scattering vector `qz` to run the simulations. \nBoth parameters can be arrays and the resulting reflectivity has a first dimension for the photon energy and the a second for the scattering vector.\n\nThe resulting reflectivity is always calculated for the actual magnetization (`R_hom`) of the sample, as well as for opposite magnetization (`R_hom_phi`).",
"_____no_output_____"
]
],
[
[
"dyn_mag.energy = np.r_[600, 708]*u.eV # set two photon energies\ndyn_mag.qz = np.r_[0.01:5:0.01]/u.nm # qz range\n\nR_hom, R_hom_phi, _, _ = dyn_mag.homogeneous_reflectivity() # this is the actual calculation",
"Calculating _homogeneous_reflectivity_ ...\nElapsed time for _homogeneous_reflectivity_: 0.953312 s\n"
]
],
[
[
"In this example half-order antiferromagnetic Bragg peaks appear only at the resonance.",
"_____no_output_____"
]
],
[
[
"plt.figure()\nplt.semilogy(dyn_mag.qz[0, :], R_hom[0, :], label='{}'.format(dyn_mag.energy[0]))\nplt.semilogy(dyn_mag.qz[1, :], R_hom[1, :], label='{}'.format(dyn_mag.energy[1]))\nplt.ylabel('Reflectivity')\nplt.xlabel(r'$q_z$ [1/nm]')\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Post-Processing\n\nSimple convolution of the results with an arbitrary function handle.",
"_____no_output_____"
]
],
[
[
"FWHM = 0.01/1e-10 # Angstrom\nsigma = FWHM /2.3548\n \nhandle = lambda x: np.exp(-((x)/sigma)**2/2)\ny_conv = dyn_mag.conv_with_function(R_hom[1,:], dyn_mag._qz[1,:], handle)\n\nplt.figure()\nplt.semilogy(dyn_mag.qz[0,:], R_hom[1,:], label='{}'.format(dyn_mag.energy[1]))\nplt.semilogy(dyn_mag.qz[0,:], y_conv, label='{} convoluted'.format(dyn_mag.energy[1]))\nplt.ylabel('Reflectivity')\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Energy- and $q_z$-scan",
"_____no_output_____"
]
],
[
[
"dyn_mag.energy = np.r_[690:730:0.1]*u.eV # set the energy range\ndyn_mag.qz = np.r_[0.01:5:0.01]/u.nm # qz range\n\nR_hom, R_hom_phi, _, _ = dyn_mag.homogeneous_reflectivity() # this is the actual calculation",
"Calculating _homogeneous_reflectivity_ ...\nElapsed time for _homogeneous_reflectivity_: 193.556878 s\n"
],
[
"plt.figure(figsize=[6, 8])\nplt.subplot(2, 1, 1)\nplt.semilogy(dyn_mag.qz[0, :].to('1/nm'), R_hom[0, :], label=np.round(dyn_mag.energy[0]))\nplt.semilogy(dyn_mag.qz[0, :].to('1/nm'), R_hom[180, :], label=np.round(dyn_mag.energy[180]))\nplt.semilogy(dyn_mag.qz[0, :].to('1/nm'), R_hom[-1, :], label=np.round(dyn_mag.energy[-1]))\n\nplt.xlabel('$q_z$ [nm$^{-1}$]')\nplt.ylabel('Reflectivity')\nplt.legend()\nplt.title('Dynamical Magnetic X-ray')\n\nplt.subplot(2, 1, 2)\nplt.pcolormesh(dyn_mag.qz[0, :].to('1/nm').magnitude, dyn_mag.energy.magnitude, np.log10(R_hom[:, :]))\nplt.title('Dynamical Magnetic X-ray')\nplt.ylabel('Energy [eV]')\nplt.xlabel('$q_z$ [nm$^{-1}$]')\n\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Polarization dependence\n\nThe `XrayDynMag` allows to set the incoming and outgoing polarization of the X-rays.",
"_____no_output_____"
]
],
[
[
"dyn_mag.energy = np.r_[710]*u.eV # set two photon energies\ndyn_mag.qz = np.r_[0.01:5:0.01]/u.nm # qz range\n\nplt.figure()\ndyn_mag.set_polarization(3, 0)\nR_hom, R_hom_phi, _, _ = dyn_mag.homogeneous_reflectivity() # this is the actual calculation\nplt.semilogy(dyn_mag.qz[0, :], R_hom[0, :], label='{}: sigma -> unpolarized'.format(dyn_mag.energy[0]), alpha=0.5)\n\ndyn_mag.set_polarization(3, 3)\nR_hom, R_hom_phi, _, _ = dyn_mag.homogeneous_reflectivity() # this is the actual calculation\nplt.semilogy(dyn_mag.qz[0, :], R_hom[0, :], label='{}: sigma -> sigma'.format(dyn_mag.energy[0]), alpha=0.5)\n\ndyn_mag.set_polarization(3, 4)\nR_hom, R_hom_phi, _, _ = dyn_mag.homogeneous_reflectivity() # this is the actual calculation\nplt.semilogy(dyn_mag.qz[0, :], R_hom[0, :], label='{}: sigma -> pi'.format(dyn_mag.energy[0]), alpha=0.5)\n\nplt.xlabel('$q_z$ [nm$^{-1}$]')\nplt.ylabel('Reflectivity')\nplt.title('Dynamical X-ray Polarization Dependence')\nplt.legend()\nplt.show()",
"incoming polarizations set to: sigma\nanalyzer polarizations set to: unpolarized\nCalculating _homogeneous_reflectivity_ ...\nElapsed time for _homogeneous_reflectivity_: 0.620994 s\nincoming polarizations set to: sigma\nanalyzer polarizations set to: sigma\nCalculating _homogeneous_reflectivity_ ...\nElapsed time for _homogeneous_reflectivity_: 0.402254 s\nincoming polarizations set to: sigma\nanalyzer polarizations set to: pi\nCalculating _homogeneous_reflectivity_ ...\nElapsed time for _homogeneous_reflectivity_: 0.388865 s\n"
]
],
[
[
"## Inhomogeneous dynamical magnetic X-ray scattering\n\nThe `inhomogeneous_reflectivity()` method allows to calculate the transient magnetic X-ray reflectivity according to a `strain_map` and/or `magnetization_map`.",
"_____no_output_____"
]
],
[
[
"dyn_mag.energy = np.r_[708]*u.eV # set the energy range\ndyn_mag.qz = np.r_[1:3.5:0.01]/u.nm # qz range\ndyn_mag.set_polarization(3, 0)",
"incoming polarizations set to: sigma\nanalyzer polarizations set to: unpolarized\n"
],
[
"R_seq, R_seq_phi, _, _ = dyn_mag.inhomogeneous_reflectivity(strain_map=strain_map,\n magnetization_map=magnetization_map)",
"Calculating _inhomogeneous_reflectivity_ ...\n"
],
[
"plt.figure(figsize=[6, 8])\nplt.subplot(2, 1, 1)\nplt.semilogy(dyn_mag.qz[0, :].to('1/nm'), R_seq[0, 0, :], label=np.round(delays[0]))\nplt.semilogy(dyn_mag.qz[0, :].to('1/nm'), R_seq[40, 0, :], label=np.round(delays[40]))\nplt.semilogy(dyn_mag.qz[0, :].to('1/nm'), R_seq[-1, 0, :], label=np.round(delays[-1]))\n\nplt.xlabel('$q_z$ [nm$^{-1}$]')\nplt.ylabel('Reflectivity')\nplt.legend()\nplt.title('Dynamical Magnetic X-ray')\n\nplt.subplot(2, 1, 2)\nplt.pcolormesh(dyn_mag.qz[0, :].to('1/nm').magnitude,\n delays.to('ps').magnitude, np.log10(R_seq[:, 0, :]))\n\nplt.ylabel('Delay [ps]')\nplt.xlabel('$q_z$ [nm$^{-1}$]')\nplt.colorbar()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Parallel dynamical X-ray scattering\n\nParallelization is fundamentally implemented but needs further improvements.\nIt works similar as with `XrayDyn`.\n\nYou need to install the `udkm1Dsim` with the `parallel` option which essentially add the `Dask` package to the requirements:\n\n```\n> pip install udkm1Dsim[parallel]\n```\n\nYou can also install/add `Dask` manually, e.g. via pip:\n\n```\n> pip install dask\n```\n\nPlease refer to the [Dask documentation](https://docs.dask.org/en/latest/) for more details on parallel computing in Python.\n",
"_____no_output_____"
]
],
[
[
"try:\n from dask.distributed import Client\n client = Client()\n R_seq_par, R_seq_phi_par, _, _ = dyn_mag.inhomogeneous_reflectivity(strain_map=strain_map,\n magnetization_map=magnetization_map,\n calc_type='parallel', dask_client=client)\n client.close()\nexcept:\n pass",
"Calculating _inhomogeneous_reflectivity_ ...\nElapsed time for _inhomogeneous_reflectivity_: 1293.669474 s\n"
],
[
"plt.figure(figsize=[6, 8])\nplt.subplot(2, 1, 1)\nplt.semilogy(dyn_mag.qz[0, :].to('1/nm'), R_seq_par[0, 0, :], label=np.round(delays[0]))\nplt.semilogy(dyn_mag.qz[0, :].to('1/nm'), R_seq_par[40, 0, :], label=np.round(delays[40]))\nplt.semilogy(dyn_mag.qz[0, :].to('1/nm'), R_seq_par[-1, 0, :], label=np.round(delays[-1]))\n\nplt.xlabel('$q_z$ [nm$^{-1}$]')\nplt.ylabel('Reflectivity')\nplt.legend()\nplt.title('Parallel Dynamical Magnetic X-ray')\n\nplt.subplot(2, 1, 2)\nplt.pcolormesh(dyn_mag.qz[0, :].to('1/nm').magnitude,\n delays.to('ps').magnitude, np.log10(R_seq_par[:, 0, :]))\n\nplt.ylabel('Delay [ps]')\nplt.xlabel('$q_z$ [nm$^{-1}$]')\nplt.colorbar()\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e722449dcb9346440fdc4dbbfc5ca5e52383fc07 | 12,553 | ipynb | Jupyter Notebook | wirescraper/scraping_demo_phx_2018-07.ipynb | mileserickson/wirescraper | 264418f99b83f37598a4e1e3a91c64a5acc7b7a5 | [
"MIT"
] | null | null | null | wirescraper/scraping_demo_phx_2018-07.ipynb | mileserickson/wirescraper | 264418f99b83f37598a4e1e3a91c64a5acc7b7a5 | [
"MIT"
] | null | null | null | wirescraper/scraping_demo_phx_2018-07.ipynb | mileserickson/wirescraper | 264418f99b83f37598a4e1e3a91c64a5acc7b7a5 | [
"MIT"
] | 2 | 2018-07-07T03:44:19.000Z | 2018-07-09T05:02:01.000Z | 41.022876 | 76 | 0.453039 | [
[
[
"import pandas as pd\nfrom selenium.webdriver import Firefox\nimport wirescraper",
"_____no_output_____"
],
[
"url = \"https://thewirecutter.com/electronics/accessories/\"\ndata = wirescraper.scrape_section(url)",
"_____no_output_____"
],
[
"pd.DataFrame(data)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code"
]
] |
e7224588ef8a49fa6a76d85a8a5192c4fdd28507 | 5,527 | ipynb | Jupyter Notebook | jsonld-widgets.ipynb | sfsheath/heath-lod-cookbook | 7645fd0d986938186402205b315d3ccafddc9ddf | [
"MIT"
] | null | null | null | jsonld-widgets.ipynb | sfsheath/heath-lod-cookbook | 7645fd0d986938186402205b315d3ccafddc9ddf | [
"MIT"
] | null | null | null | jsonld-widgets.ipynb | sfsheath/heath-lod-cookbook | 7645fd0d986938186402205b315d3ccafddc9ddf | [
"MIT"
] | null | null | null | 38.381944 | 327 | 0.559255 | [
[
[
"# Interactive Table and Histogram of Roman Amphitheater Capacities\n\nManually execute the three cells in order or \"Run All\". That will load data and then create an interactive interface to setting which amphitheaters capacities appear in a table and histogram at the bottom of the page. Slide the sliders and click the checkbox to make changes. Display refresh is clunky, but it works.\n\nNote: If you're running this in Binder, you might get warnings about module compatibility. Should be OK to ignore those, or at least was in Summer of 2018.\n\nTo view this data as a map see:\n\nhttps://github.com/sfsheath/roman-amphitheaters/blob/master/roman-amphitheaters.geojson",
"_____no_output_____"
]
],
[
[
"from ipywidgets import widgets,interact\nfrom IPython.display import display, HTML, clear_output\nfrom urllib.request import urlopen\nfrom rdflib import Graph, plugin\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\npd.set_option('display.max_colwidth', -1) # so that full Pleiades URIs are displayed",
"_____no_output_____"
],
[
"# jsonld+geojson amphitheater data\njson_data = urlopen(\"http://sfsheath.github.io/roman-amphitheaters/roman-amphitheaters.geojson\")\ng = Graph().parse(data=json_data.read(), format='json-ld')",
"_____no_output_____"
],
[
"# function that handles changes to sliders and creates histogram\ndef on_value_change(change=1): # change isn't used but will be passewd so there has to be a placeholder\n global low_widget, high_widget, lower_range, upper_range, sort_widget\n \n # provide defaults if values not defined\n try:\n lower_range = low_widget.value\n upper_range = high_widget.value\n sort_order = sort_widget.value\n except NameError:\n lower_range = 2000\n upper_range = 55000\n sort_order = True\n \n# The SPARQL Query\n results = g.query(\"\"\"\nPREFIX ramphs: <http://purl.org/roman-amphitheaters/resource/>\nPREFIX gj: <https://purl.org/geojson/vocab#>\nPREFIX ramphs-p: <http://purl.org/roman-amphitheaters/properties#>\nPREFIX dcterms: <http://purl.org/dc/terms/>\nSELECT ?title ?capacity ?pleiades WHERE {\n\n?s gj:properties/dcterms:title ?title ;\n gj:properties/ramphs-p:capacity/ramphs-p:quantity ?capacity ;\n gj:properties/ramphs-p:pleiades ?pleiades\n .\n\nFILTER ((?capacity > %s) )\nFILTER (?capacity < %s)\n}\"\"\" % (lower_range, upper_range ) )\n\n # build pandas dataframe\n titles, caps, pleiades = [],[],[]\n for row in results:\n titles.append(row.title)\n caps.append(int(row.capacity))\n pleiades.append('<a href=\"{0}\" target=\"_new\">{0}hihi</a>'.format(row.pleiades))\n \n ramphs_pd = pd.DataFrame({'title':titles,'capacity':caps,'pleiades':pleiades})\n \n # build/display interface, table, and histogram\n clear_output()\n low_widget = widgets.IntSlider(value=lower_range,\n min=2000, max=55000,\n step = 1000,\n description=\"Lower limit:\",\n continuous_update=False)\n high_widget = widgets.IntSlider(value=upper_range,\n min=2000, max=55000,\n step = 1000,\n description=\"Upper limit:\",\n continuous_update=False)\n sort_widget = widgets.Checkbox(description=\"Sort high to low\", value=sort_order)\n low_widget.observe(on_value_change, names='value')\n high_widget.observe(on_value_change, names='value')\n sort_widget.observe(on_value_change, names='value')\n \n display(high_widget,\n low_widget,\n sort_widget,\n HTML(ramphs_pd.sort_values(by='capacity',\n ascending = not sort_order).\\\n head(10).to_html(escape=False)))\n ramphs_pd.hist() # for now, works better outside of call to display()\n\n# call function that gets the ball rolling,\non_value_change()",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e72245f7221c58da0657dfbd54dc2492d2d4aadd | 32,247 | ipynb | Jupyter Notebook | Chapter3_MLIntroduction/KnnAlgorithm/KnnImplementation_preparation_end.ipynb | tomex74/UdemyML | d9600d95783bae553e4142231aeb284a38a69f4e | [
"MIT"
] | 8 | 2020-11-01T13:22:02.000Z | 2022-03-18T09:28:12.000Z | Chapter3_MLIntroduction/KnnAlgorithm/KnnImplementation_preparation_end.ipynb | tomex74/UdemyML | d9600d95783bae553e4142231aeb284a38a69f4e | [
"MIT"
] | null | null | null | Chapter3_MLIntroduction/KnnAlgorithm/KnnImplementation_preparation_end.ipynb | tomex74/UdemyML | d9600d95783bae553e4142231aeb284a38a69f4e | [
"MIT"
] | 9 | 2020-09-09T08:20:30.000Z | 2022-01-08T09:59:59.000Z | 206.711538 | 21,591 | 0.655472 | [
[
[
"### K-Nearest Neighbor Algorithmus:\n\n#### Parameter: \n\ndataset = (X, Y) \nmit X := Features \nund Y := Classes \n\nK := Hyperparameter für die nächsten k Nachbarn \nsample := Neuer Datenpunkt zum Klassifizieren \n\n#### Pseudo-Code:\n\nkNN (dataset, K, sample): \n - Bestimme von jedem Punkt $p \\in dataset$ die Distanz, mit der geg. Distanzfunktion.\n - Bestimme die $K$ nächst gelegenen Nachbarn und bestimme die zugehörige Klasse von $sample$. ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nnp.random.seed(42)",
"_____no_output_____"
],
[
"def generate_dataset():\n num_samples_class1 = 10\n num_samples_class2 = 6\n num_samples_class3 = 13\n cov = np.array([[1, 0], [0, 1]])\n data1 = np.random.multivariate_normal(\n np.array([0, 0]), cov, num_samples_class1\n )\n data2 = np.random.multivariate_normal(\n np.array([-10, 4]), cov, num_samples_class2\n )\n data3 = np.random.multivariate_normal(\n np.array([10, 10]), cov, num_samples_class3\n )\n data = np.concatenate((data1, data2, data3), axis=0)\n classes = np.array(\n [0 for i in range(num_samples_class1)] +\n [1 for i in range(num_samples_class2)] +\n [2 for i in range(num_samples_class3)]\n )\n return data, classes",
"_____no_output_____"
],
[
"x, y = generate_dataset()",
"_____no_output_____"
],
[
"print(f\"x shape: {x.shape}\")\nprint(f\"y shape: {y.shape}\")\n\nprint(f\"x:\\n{x}\")\nprint(f\"y:\\n{y}\")",
"x shape: (29, 2)\ny shape: (29,)\nx:\n[[ 0.49671415 -0.1382643 ]\n [ 0.64768854 1.52302986]\n [ -0.23415337 -0.23413696]\n [ 1.57921282 0.76743473]\n [ -0.46947439 0.54256004]\n [ -0.46341769 -0.46572975]\n [ 0.24196227 -1.91328024]\n [ -1.72491783 -0.56228753]\n [ -1.01283112 0.31424733]\n [ -0.90802408 -1.4123037 ]\n [ -8.53435123 3.7742237 ]\n [ -9.9324718 2.57525181]\n [-10.54438272 4.11092259]\n [-11.15099358 4.37569802]\n [-10.60063869 3.70830625]\n [-10.60170661 5.85227818]\n [ 9.98650278 8.94228907]\n [ 10.82254491 8.77915635]\n [ 10.2088636 8.04032988]\n [ 8.67181395 10.19686124]\n [ 10.73846658 10.17136828]\n [ 9.88435172 9.6988963 ]\n [ 8.52147801 9.28015579]\n [ 9.53936123 11.05712223]\n [ 10.34361829 8.23695984]\n [ 10.32408397 9.61491772]\n [ 9.323078 10.61167629]\n [ 11.03099952 10.93128012]\n [ 9.16078248 9.69078762]]\ny:\n[0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2]\n"
],
[
"import matplotlib.pyplot as plt\n\ndef plot_dataset(x, y):\n colors = [\"red\", \"blue\", \"green\"]\n for index, point in enumerate(x):\n plt.scatter(point[0], point[1], color=colors[y[index]])\n plt.show()",
"_____no_output_____"
],
[
"plot_dataset(x, y)",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e722499f76c5572ef910d31fae78615773b72420 | 58,377 | ipynb | Jupyter Notebook | src/datasets/investigate_dataset/investigate_df.ipynb | AllaVinner/Augmentation-in-3D-microscopy | e0e0ce242b71f8a03ef931fee6e8909b2b62841a | [
"MIT"
] | 1 | 2022-02-28T19:37:36.000Z | 2022-02-28T19:37:36.000Z | src/datasets/investigate_dataset/investigate_df.ipynb | AllaVinner/Augmentation-in-3D-microscopy | e0e0ce242b71f8a03ef931fee6e8909b2b62841a | [
"MIT"
] | null | null | null | src/datasets/investigate_dataset/investigate_df.ipynb | AllaVinner/Augmentation-in-3D-microscopy | e0e0ce242b71f8a03ef931fee6e8909b2b62841a | [
"MIT"
] | 1 | 2022-02-28T19:37:39.000Z | 2022-02-28T19:37:39.000Z | 98.944068 | 40,054 | 0.785532 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os\nfrom collections import defaultdict\nimport seaborn as sns",
"_____no_output_____"
],
[
"DATASET = 'Ovules'\nDATASET_PATH = os.path.join('/scratch/ottosson/datasets', DATASET)\nRAW_PATH = os.path.join(DATASET_PATH, 'raw')\nLABEL_PATH = os.path.join(DATASET_PATH, 'label')\nBACKGROUND_LABEL = 1\nDATA_FRAME_PATH = os.path.join(DATASET_PATH, 'dataframes')",
"_____no_output_____"
],
[
"cell_df = pd.read_csv(os.path.join(DATA_FRAME_PATH, 'cell_df.csv'))\nlabel_df = pd.read_csv(os.path.join(DATA_FRAME_PATH, 'label_df.csv'))\nsample_df = pd.read_csv(os.path.join(DATA_FRAME_PATH, 'sample_df.csv'))",
"_____no_output_____"
],
[
"sample_df['p'] = sample_df['background_volume']/(sample_df['X']*sample_df['Y']*sample_df['Z'])",
"_____no_output_____"
],
[
"sample_df.describe()",
"_____no_output_____"
],
[
"sample_df['im_volume'] = sample_df['Z']*sample_df['Y']*sample_df['X']",
"_____no_output_____"
],
[
"sample_df['part_background'] = sample_df['background_volume']/sample_df['im_volume']",
"_____no_output_____"
],
[
"cell_df.groupby('sample_name').median()",
"_____no_output_____"
],
[
"sns.displot(data = cell_df, x = 'cell_volume', col = 'sample_name', col_wrap=5, log_scale=True)",
"_____no_output_____"
],
[
"cell_df[cell_df['sample_name'] == '0h'].describe()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7226d37008c824fcdaf8a26c5160c583b5b2062 | 1,457 | ipynb | Jupyter Notebook | example-notebooks/webgl/.ipynb_checkpoints/single_dataset-checkpoint.ipynb | VisionandCognition/pycortex | 88f477eb7e3b37123ed4e79244c18a322d5336e3 | [
"BSD-2-Clause"
] | null | null | null | example-notebooks/webgl/.ipynb_checkpoints/single_dataset-checkpoint.ipynb | VisionandCognition/pycortex | 88f477eb7e3b37123ed4e79244c18a322d5336e3 | [
"BSD-2-Clause"
] | 1 | 2020-05-12T13:44:41.000Z | 2022-02-02T17:29:12.000Z | example-notebooks/webgl/.ipynb_checkpoints/single_dataset-checkpoint.ipynb | VisionandCognition/pycortex | 88f477eb7e3b37123ed4e79244c18a322d5336e3 | [
"BSD-2-Clause"
] | null | null | null | 26.981481 | 381 | 0.533974 | [
[
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"\n# Create a 3D WebGL Viewer\n\n\nA webgl viewer displays a 3D view of brain data in a web browser\n",
"_____no_output_____"
]
],
[
[
"import cortex\n\nimport numpy as np\nnp.random.seed(1234)\n\n# gather data Volume\nvolume = cortex.Volume.random(subject='S1', xfmname='fullhead')\n\n# create viewer\ncortex.webgl.show(data=volume)\n\n# a port number will then be output, for example \"Started server on port 39140\"\n# the viewer can then be accessed in a web browser, in this case at \"localhost:39140\"",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e72271c03bf035c00f3d384425b6f8e9c75282bf | 100,728 | ipynb | Jupyter Notebook | docs/source/tutorials/5_SanUnit_advanced.ipynb | cmlav14/QSDsan | 419d188515296238672f9a3b877235809f979da9 | [
"Unlicense"
] | 23 | 2021-01-23T16:45:07.000Z | 2022-01-30T18:14:32.000Z | docs/source/tutorials/5_SanUnit_advanced.ipynb | cmlav14/QSDsan | 419d188515296238672f9a3b877235809f979da9 | [
"Unlicense"
] | 39 | 2021-01-07T05:57:06.000Z | 2022-03-21T20:44:11.000Z | docs/source/tutorials/5_SanUnit_advanced.ipynb | cmlav14/QSDsan | 419d188515296238672f9a3b877235809f979da9 | [
"Unlicense"
] | 12 | 2021-03-09T09:06:15.000Z | 2022-03-12T15:10:13.000Z | 55.804986 | 20,396 | 0.696212 | [
[
[
"# `SanUnit` (advanced) <a class=\"anchor\" id=\"top\"></a>\n\n- **Prepared by:**\n \n - [Yalin Li](https://qsdsan.readthedocs.io/en/latest/authors/Yalin_Li.html)\n\n- **Covered topics:**\n\n - [1. Python class creation 101](#s1)\n - [2. Basic structure of SanUnit subclasses](#s2)\n - [3. Making a simple AerobicReactor](#s3)\n - [4. Other convenient features](#s4)\n \n- **Video demo:**\n\n - [Hannah Lohman](https://qsdsan.readthedocs.io/en/latest/authors/Hannah_Lohman.html)\n \nTo run tutorials in your browser, go to this [Binder page](https://mybinder.org/v2/gh/QSD-Group/QSDsan/main?filepath=%2Fdocs%2Fsource%2Ftutorials).\n\nYou can also watch a video demo on [YouTube](https://youtu.be/G20J2U8g7Dg) (subscriptions & likes appreciated!).",
"_____no_output_____"
]
],
[
[
"import qsdsan as qs\nprint(f'This tutorial was made with qsdsan v{qs.__version__}.')",
"This tutorial was made with qsdsan v0.3.7.\n"
]
],
[
[
"## 1. Python class creation 101 <a class=\"anchor\" id=\"s1\"></a>",
"_____no_output_____"
],
[
"### 1.1. Syntax and methods",
"_____no_output_____"
]
],
[
[
"# To make a new class, at the bare minimum, you just need to have\nclass i_am_a_new_class:\n pass",
"_____no_output_____"
],
[
"# Then you can make instances of the class\ninstance1 = i_am_a_new_class()\ntype(instance1)",
"_____no_output_____"
],
[
"# To make this class more useful, we can add data and functions to the class\nclass i_am_a_useful_class:\n def do_something(self):\n print(\"Thinking of what to do...\")",
"_____no_output_____"
],
[
"instance2 = i_am_a_useful_class()\ntype(instance2)",
"_____no_output_____"
],
[
"# Since we included a function to go with this class, we can at least do\ninstance2.do_something()",
"Thinking of what to do...\n"
]
],
[
[
"OK, it can do something!\n\nThe `do_something` function, when it's associated with the `i_am_a_useful_class`, it is called a `method`. More specifically, when it's just written as:\n\n```python\ndef FUNCTION_NAME(self):\n SOME CODES\n```\n\nIt is a `instance method`. This means it works on instances of the class (like `instance2`). The most salient feature is that it requires `self` as a method argument (you will know from later part of the tutorial how usefuel `self` is).",
"_____no_output_____"
]
],
[
[
"# Of course, there can be other types of methods\nclass i_am_a_more_useful_class:\n @staticmethod\n def i_dont_need_self_cls():\n print('I am a static method, I can be called without `self` nor `cls`!')\n \n @classmethod\n def i_need_cls(cls):\n print(f'I am a class method, I need `cls` and the name of the class is {cls.__name__}.')\n \n def i_need_self(self):\n print('I am an instance method, I need `self`, '\n f'the name of my class is {type(self).__name__}.')\n \n @staticmethod\n def print_cls(object):\n print(f'The class of this object is {type(object).__name__}')\n \n \ninstance3 = i_am_a_more_useful_class() # oh boy the name is so long...",
"_____no_output_____"
],
[
"# You will find that the `static method`, being indicated by the `decorator` (that `@`) `staticmethod`,\n# does not require `self` as the input!\n# `static method` can be useful if there is a function that you want to use with the class,\n# but it does not need the `self` as an argument\ninstance3.i_dont_need_self_cls()",
"I am a static method, I can be called without `self` nor `cls`!\n"
]
],
[
[
"**Minor tip:**\n\n`decorator` is an elegant and convinent way to add functionalities, for more details, just search for it, I personally like this [tutorial](https://www.programiz.com/python-programming/decorator)",
"_____no_output_____"
]
],
[
[
"instance3.i_need_self()",
"I am an instance method, I need `self`, the name of my class is i_am_a_more_useful_class.\n"
],
[
"# For the `class method`, you will notice that it requires `cls` instead of `self` as an argument\n# it can work on both the class and the instance\n# This method is indeed helpful, since sometimes you'll want to figure out the name of a class\ninstance3.i_need_cls()\ni_am_a_more_useful_class.i_need_cls()",
"I am a class method, I need `cls` and the name of the class is i_am_a_more_useful_class.\nI am a class method, I need `cls` and the name of the class is i_am_a_more_useful_class.\n"
],
[
"# One interesting to note, is that instance and class methods are `bound methods`\n# (i.e., they are bound to this instance/class)\nprint(instance3.i_need_cls) # see the printout, this belongs to the class\nprint(instance3.i_need_self) # see the printout, this belongs to the object",
"<bound method i_am_a_more_useful_class.i_need_cls of <class '__main__.i_am_a_more_useful_class'>>\n<bound method i_am_a_more_useful_class.i_need_self of <__main__.i_am_a_more_useful_class object at 0x7fd676d53d30>>\n"
],
[
"# If you recall how we load the default components\ncmps = qs.Components.load_default()\nqs.Components.load_default # aha!",
"_____no_output_____"
],
[
"# But static method is not, it's static regardless of the instance/class,\n# it can be used regardless of whether an object belongs to this class or not\nprint(instance3.print_cls)\ni_am_five = 5\nprint(f'The class of this object is {type(i_am_five).__name__}')\ninstance3.print_cls(i_am_five)\ni_am_a_more_useful_class.print_cls(i_am_five)",
"<function i_am_a_more_useful_class.print_cls at 0x7fd676d49a60>\nThe class of this object is int\nThe class of this object is int\nThe class of this object is int\n"
]
],
[
[
"Fancinating, isn't it?",
"_____no_output_____"
],
[
"### 1.2. Attributes and properties\nSo we talked about how we can add methods to a class, then what if we want the class to remember some data?",
"_____no_output_____"
]
],
[
[
"# Let's see this example (yeah I just love apple...)\nclass apple:\n def __init__(self, argument_name, argument_color):\n self.attribute_name = argument_name\n self.attribute_color = argument_color\n \n def introduce(self):\n print(f'My name is {self.attribute_name}, my color is {self.attribute_color}.')\n \ngala = apple(argument_name='Gala', argument_color='red')\ngranny_smith = apple(argument_name='Granny Smith', argument_color='green')\npink_lady = apple(argument_name='Pink Lady', argument_color='pink')\n\nfor i in (gala, granny_smith, pink_lady):\n i.introduce()",
"My name is Gala, my color is red.\nMy name is Granny Smith, my color is green.\nMy name is Pink Lady, my color is pink.\n"
]
],
[
[
"Here we use an `__init__` method, which is a builtin method and is called when you initialize (e.g., when you do `instance = class()`) an instance.\n\nIn `__init__`, with `self.attribute_name = argument_name`, we actually did two things:\n- We added an attribute called `attribute_name` to `self` (i.e., the instance)\n- We pass the value of the argument `argument_name` to `attribute_name`",
"_____no_output_____"
],
[
"You can think of it as anything that after the `.` of a class/instance. Attributes can be data, method, even modules.\n\nSimilar to instance vs. class method, there are instance attribute and class attribute. For example",
"_____no_output_____"
]
],
[
[
"class apple2(apple):\n cls_attr = 'fruit'\n \n def __init__(self, argument_name, argument_color):\n self.attribute_name = argument_name\n self.attribute_color = argument_color",
"_____no_output_____"
],
[
"# See that `(apple)` after `apple2`? This means we are making `apple2` a subclass of `apple`.\n# Even without defining the `introduce` method, we can use it\nred_delicious = apple2('Red Delicious', 'red')\nred_delicious.introduce()",
"My name is Red Delicious, my color is red.\n"
],
[
"# Indeed the method is coming from `apple`\nprint(red_delicious.introduce)",
"<bound method apple.introduce of <__main__.apple2 object at 0x7fd668906a60>>\n"
],
[
"# The `cls_attr` there is a class attribute and can be accesible to the class and all its instances\nprint(red_delicious.cls_attr)\nprint(apple2.cls_attr)",
"fruit\nfruit\n"
]
],
[
[
"Another concept that you might have heard of property and get confused about the differences between it and attribute.\n\nYou can think property as a special kind of attribute. Its specialty lies in the need for `getter`, `setter`, and `deleter` (functions to get values, set values, and delete values). For example",
"_____no_output_____"
]
],
[
[
"class apple3:\n def __init__(self, argument_name, argument_color):\n self.attribute_name = argument_name\n self._attribute_color = argument_color\n \n def introduce(self):\n print(f'My name is {self.attribute_name}, my color is {self.attribute_color}.')\n \n @property # decorator!\n def attribute_color(self):\n return self._attribute_color\n @attribute_color.setter\n def attribute_color(self, color):\n self._attribute_color = color\n\nscarlet_gala = apple3('Scarlet Gala', 'scalet')\nscarlet_gala.introduce()",
"My name is Scarlet Gala, my color is scalet.\n"
],
[
"apple3.attribute_color",
"_____no_output_____"
]
],
[
[
"You can see that `attribute_color` is a property. Since it's value depends on the attribute `_attribute_color`, and Python doesn't know the value of it before you create the instance, so you cannot get the acutal value.",
"_____no_output_____"
]
],
[
[
"# Note that you'll get an error if you attempt to do the following,\n# because `_attribute_color` is an instance attribute\n# apple3._attribute_color",
"_____no_output_____"
]
],
[
[
"However, why do we want to use property and add all those extra lines?\n\nFirst, because now `getter` is a function, we can add in other thing while we try to get the value, like",
"_____no_output_____"
]
],
[
[
"class apple4:\n def __init__(self, argument_name, argument_color):\n self.attribute_name = argument_name\n self._attribute_color = argument_color\n \n def introduce(self):\n print(f'My name is {self.attribute_name}, my color is {self.attribute_color}.')\n \n @property # decorator!\n def attribute_color(self):\n print('Trying to retrieving the value...')\n return self._attribute_color\n @attribute_color.setter\n def attribute_color(self, color):\n self._attribute_color = color\n\nempire = apple4('Empire', 'red')\nempire.introduce()",
"Trying to retrieving the value...\nMy name is Empire, my color is red.\n"
]
],
[
[
"Second, we can prevent the users from (accidentally) changing values",
"_____no_output_____"
]
],
[
[
"# Say that some user try to do\nempire.attribute_color = 'green'\nempire.introduce()",
"Trying to retrieving the value...\nMy name is Empire, my color is green.\n"
]
],
[
[
"But this is not right! [Empire](https://en.wikipedia.org/wiki/Empire_(apple)) is NOT green!\n\nTo prevent the value of an attribute to be changed by the user, we can just take away (or more accurately, not implement) the `setter`.",
"_____no_output_____"
]
],
[
[
"class apple5:\n def __init__(self, argument_name, argument_color):\n self.attribute_name = argument_name\n self._attribute_color = argument_color\n \n def introduce(self):\n print(f'My name is {self.attribute_name}, my color is {self.attribute_color}.')\n \n @property\n def attribute_color(self):\n return self._attribute_color\n # Take out the `setter` function will prevent the property `attribute_color`\n # from being updated\n # @attribute_color.setter\n # def attribute_color(self, color):\n # self._attribute_color = color\n\ngolden_delicious = apple5('Golden Delicious', 'golden')\ngolden_delicious.introduce()",
"My name is Golden Delicious, my color is golden.\n"
],
[
"# Now you will get an error if you try to change the color\n# golden_delicious.attribute_color = 'green'",
"_____no_output_____"
],
[
"# However, if you really want to update the value, you can still do it by\ngolden_delicious._attribute_color = 'green'\nprint(f'The property `attribute_color` is {golden_delicious.attribute_color}.')\nprint(f'The attribute `_attribute_color` is {golden_delicious._attribute_color}.')",
"The property `attribute_color` is green.\nThe attribute `_attribute_color` is green.\n"
],
[
"# You can make it more helpful (or hurtful) by adding questions\nclass apple6:\n def __init__(self, argument_name, argument_color):\n self.attribute_name = argument_name\n self._attribute_color = argument_color\n \n def introduce(self):\n print(f'My name is {self.attribute_name}, my color is {self.attribute_color}.')\n \n @property\n def attribute_color(self):\n return self._attribute_color\n @attribute_color.setter\n def attribute_color(self, color):\n raise AttributeError(\"Nope I'm not letting you change the color!\")\n\ncosmic_crisp = apple6('Cosmic Crisp', 'dark red')\ncosmic_crisp.introduce()",
"My name is Cosmic Crisp, my color is dark red.\n"
],
[
"# Ah, it hurts, doesn't it?\n# cosmic_crisp.attribute_color = 'red'",
"_____no_output_____"
]
],
[
[
"[Back to top](#top)",
"_____no_output_____"
],
[
"## 2. Basic structure of `SanUnit` subclasses <a class=\"anchor\" id=\"s2\"></a>\nAlright, equipped with the basics on `SanUnit` (assuming you are familiar with the topics covered in the [previous tutorial](https://qsdsan.readthedocs.io/en/latest/tutorials/4_SanUnit_basic.html) on `SanUnit`) and the syntax of creating Pythong classes, we can now learn more specifics about creating subclasses of `SanUnit`.",
"_____no_output_____"
],
[
"### 2.1. Fundamental methods\nIn addition to the `__init__` method for initialization, all `SanUnit` objects have three most fundamental methods (they all start with `_`, as users typically don't interact with them):\n\n- `_run`, which is used for mass and energy calculation within a unit operation (e.g., if you have an anaerobic reactor that will convert 80% of the organics in the influent, you'll want to put it in `_run`\n\n - There is also a `run` method that will call the `_run` method and any `specification` functions you define, but we will skip it for now\n \n- `_design`, this method will be called after `_run` (when you have a `System` with multiple units, then `_design` will only be called *after* all units within the system have converged). The `_design` method contains algorithms that are used in designing the unit (e.g., volume, dimensions, materials)\n \n - Material inventories calculated in `_design` are usually stored in the `design_results` dict of the unit with keys being names (`str`) of the item and values being quantities of the item\n - All entires in the `design_results` dict should have corresponding entries in the `_units` dict to provide units of measure to the values in the `design_results` dict\n\n- `_cost`, which will be called after `_design` to get the cost of the unit, it may leverage the inventories calculated in `_run` or `_design`\n\n - Purchase cost of the inventory items are usually stored in the `baseline_purhcase_costs` dict, and installed cost of this item will be calcualted using different factors (`F_BM`, `F_D`, `F_P`, and `F_M` for bare module, design, pressure, and material factors, they are all dict).\n - Only the bare module factor `F_BM` is mandatory (others will be defaulted to 1 if not given). If you want to assume all material inventory items' purchase costs equal installed costs, you can set `F_BM_default` to 1 when you initialize the subclass",
"_____no_output_____"
],
[
"These methods will be aggregated into a `simulate` function that will call these methods (and do some other minor stuff).",
"_____no_output_____"
],
[
"**Note:**\n\nYou do NOT need to use all of these methods, and you do not need to strictly follow the functionalities above. For \nexample, you can put cost algorithms in `_design` or even `_run`, but the latter will be strongly discouraged unless you have a good reason, as the cost algorithms will be run a lot of times when the `System` is trying to converge, which adds unnecessary overheads.",
"_____no_output_____"
],
[
"### 2.2. Useful attributes\nSome of the class attributes that you will find useful in making your subclasses:\n\n- `_N_ins` and `_N_outs` set the number of influents and effluents of the `SanUnit`\n\n - If you are unsure of how many influents and/or effluents there will be (e.g., they can be dynamic for a mixer), you can instead set `_ins_size_is_fixed` and/or `_outs_size_is_fixed` to `False`\n \n- `construction` and `transportation` are tuple of `Construction` and `Transportation` objects for life cycle assessment (will be covered in later tutorials)\n- `purchase_cost` (float) and `purchase_costs` (dict) contain the total (without the `s`) and itemized purchase costs of this unit (i.e., `purchase_cost` is the sum of all the values in the `purchase_costs` dict). Purchase cost of an item is calculated by multiplying the value in the `baseline_purchase_cost` dict with the corresponding values in the `F_<D/P/M>` dict\n\n - Similarly, `installed_cost` (float) and `installed_costs` (dict) are the total and itemized *installed* costs (i.e., purchase cost multiplied by the the different corresponding factor in the `F_BM` dict)\n\n- `F_mass_in` (float), `mass_in` (np.array containing the *mass* of each component), `z_mass_in` (np.array containing the *mass fraction* of each component)\n \n - Additionally, there are `F_mass_out`, `mass_out`, and `z_mass_out`, and the corresponding sets for molar and volume flows (e.g., `F_mol_in`/`F_vol_in`, etc.)\n\n- `H_in`/`H_out` (changes with T) and `Hf_in`/`Hf_out` (doesn't change with T), enthalpy and enthalpy of formation of influents and effluents, respectively\n \n - There is also another attribute `Hnet` calculated as `(H_out-H_in)+(Hf_out-Hf_in)`\n\n- `_graphics`, how the unit will be represented when you call the `diagram` function. If not given, it will be defaulted to a box\n\n - Note that if you make the subclasses of `Mixer`/`Splitter`/`HXutility`/`HXprocess`, the default graphics will be different because these units have their corresponding graphics\n \n- `results`, a method (i.e., you need to call it by `<SanUnit>.results()` instead of just `<SanUnit>.result`) to give you a quick summary of the unit design and cost results",
"_____no_output_____"
],
[
"[Back to top](#top)",
"_____no_output_____"
],
[
"## 3. Making a simple AerobicReactor <a class=\"anchor\" id=\"s3\"></a>\nAlright, all those descriptions are abstract enough, and there are many details that will be best covered in an example. So let's assume we want to design a *very* simple aerobic reactor that will convert 90% of the influent organics into CO2 and H2O.",
"_____no_output_____"
]
],
[
[
"# By convention, name of the class will be concatenated capitalized words\n# (I don't need know if this is a grammerly correction expression, but I trust you can get what I meant)\n# Now it is the simplest form of the AerobicReactor\nclass AerobicReactor1(qs.SanUnit):\n def __init__(self, ID='', ins=None, outs=(), thermo=None, init_with='WasteStream'):\n qs.SanUnit.__init__(self, ID, ins, outs, thermo, init_with)\n \n def _run(self):\n pass\n \n def _design(self):\n pass\n \n def _cost(self):\n pass",
"_____no_output_____"
],
[
"# The default components are indeed useful!\ncmps_default = qs.Components.load_default()\nkwargs = {'particle_size': 'Dissolved gas',\n 'degradability': 'Undegradable',\n 'organic': False}\nO2 = qs.Component('O2', search_ID='O2', **kwargs)\nCO2 = qs.Component('CO2', search_ID='CO2', **kwargs)\ncmps = qs.Components([*cmps_default, O2, CO2])\nqs.set_thermo(cmps)\ncmps.show()",
"CompiledComponents([S_H2, S_CH4, S_CH3OH, S_Ac, S_Prop, S_F, S_U_Inf, S_U_E, C_B_Subst, C_B_BAP, C_B_UAP, C_U_Inf, X_B_Subst, X_OHO_PHA, X_GAO_PHA, X_PAO_PHA, X_GAO_Gly, X_PAO_Gly, X_OHO, X_AOO, X_NOO, X_AMO, X_PAO, X_MEOLO, X_FO, X_ACO, X_HMO, X_PRO, X_U_Inf, X_U_OHO_E, X_U_PAO_E, X_Ig_ISS, X_MgCO3, X_CaCO3, X_MAP, X_HAP, X_HDP, X_FePO4, X_AlPO4, X_AlOH, X_FeOH, X_PAO_PP_Lo, X_PAO_PP_Hi, S_NH4, S_NO2, S_NO3, S_PO4, S_K, S_Ca, S_Mg, S_CO3, S_N2, S_O2, S_CAT, S_AN, H2O, O2, CO2])\n"
],
[
"# Now make a fake waste stream with these components\nws = qs.WasteStream(H2O=1000, S_CH3OH=0.5, units='kg/hr')\nws.show()",
"WasteStream: ws1\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow (g/hr): S_CH3OH 500\n H2O 1e+06\n WasteStream-specific properties:\n pH : 7.0\n Alkalinity : 2.5 mg/L\n COD : 498.2 mg/L\n BOD : 357.2 mg/L\n TC : 124.4 mg/L\n TOC : 124.4 mg/L\n Component concentrations (mg/L):\n S_CH3OH 498.2\n H2O 996395.7\n"
],
[
"U1 = AerobicReactor1(ins=ws)\nU1.simulate()\nU1.show()",
"AerobicReactor1: R1\nins...\n[0] ws1\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow (g/hr): S_CH3OH 500\n H2O 1e+06\n WasteStream-specific properties:\n pH : 7.0\n COD : 498.2 mg/L\n BOD : 357.2 mg/L\n TC : 124.4 mg/L\n TOC : 124.4 mg/L\nouts...\n[0] ws2\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow: 0\n WasteStream-specific properties: None for empty waste streams\n"
]
],
[
[
"OK, with these simple setups, we can \"sort of\" see something, but without the methods above we aren't really doing anything useful, so let's try to implement those methods",
"_____no_output_____"
]
],
[
[
"class AerobicReactor2(qs.SanUnit):\n def __init__(self, ID='', ins=None, outs=(), thermo=None, init_with='WasteStream',\n conversion=0.9, # default conversion to be 0.9,\n aeration_rate=5, # assume we need 5 g/L of O2 pumped into the system\n HRT=5, # hydraulic residence time being 5 hours\n ):\n # Some standard codes you need to include for all subclasses of `SanUnit`\n qs.SanUnit.__init__(self, ID, ins, outs, thermo, init_with)\n # These are the unique attribures of `AerobicReactor`\n self.conversion = conversion\n self.aeration_rate = aeration_rate\n self.HRT = HRT\n \n # Assume a bare module factor of 2\n self.F_BM = {'Tank': 2}\n\n \n # Assume we'll have two influents - the waste stream and O2,\n # as well as two effluents - treated waste stream and the generated CO2\n _N_ins = 2\n _N_outs = 2\n \n def _run(self):\n # This is equivalent to\n # inf=self.ins[0]\n # o2=self.ins[1]\n inf, o2 = self.ins\n \n eff, co2 = self.outs\n o2.phase = co2.phase = 'g'\n \n # Firstly let's calculate how much O2 we need,\n # g/L (kg/m3) * m3/hr = kg/hr\n o2_needed = self.aeration_rate * self.F_vol_in\n o2.imass['O2'] = o2_needed # `imass` in kg/hr\n \n # Mix the influent streams\n eff.mix_from(self.ins)\n \n # O2 gas turned into dissolved O2\n eff.imass['S_O2'] = eff.imass['O2']\n eff.imass['O2'] = 0\n \n # Then we will want convert the organics,\n # for demo purpose let's make it very simple,\n # assume that we know ahead of time that\n # we will only have `S_CH3OH`\n # so reaction will be\n # CH3OH + 1.5 O2 -> CO2 + 2H2O\n # with the conversion defined by the user\n x = self.conversion\n converted_meoh = x * inf.imol['S_CH3OH']\n consumed_o2 = 1.5 * converted_meoh\n generated_co2 = converted_meoh\n generated_h2o = 2 * converted_meoh\n eff.imol['S_CH3OH'] -= converted_meoh\n eff.imol['S_O2'] -= consumed_o2\n eff.imol['H2O'] += generated_h2o\n co2.imol['CO2'] = generated_co2\n # Assume 5 wt% of MeOH is turned into biomass\n eff.imass['X_OHO'] = 0.05 * inf.imass['S_CH3OH']\n \n \n # We can (or seems more straightfoward to) move this into\n # the `_design` method, but since these units won't change\n # putting it here will save some simulation time\n _units = {\n 'Volume': 'm3',\n 'Diameter': 'm',\n 'Height': 'm',\n 'Stainless steel': 'kg'\n }\n \n # As for the design, let's assume we will have a \n # cylinder with a height-to-diameter ratio of 2:1\n def _design(self):\n D = self.design_results\n tot_vol = self.outs[0].F_vol*self.HRT\n rx_vol = tot_vol / 0.8 # assume 80% working volume\n # You can certainly do `import math; math.pi`\n dia = (2*rx_vol/3.14)**(1/3)\n D['Volume'] = rx_vol\n D['Diameter'] = dia\n D['Height'] = H = 2 * dia\n \n # Assume the tank has a thickness of 3 cm,\n # we'll need the cover, but not the bottom\n ss = 3.14*(dia**2)*H + 3.14/4*(dia**2)\n # Assume the density is 7,500 kg/m3\n D['Stainless steel'] = ss * 7500\n \n # Let's assume that the reactor is\n # made of stainless steel with a price of $3/kg\n def _cost(self):\n self.baseline_purchase_costs['Tank'] = \\\n 3 * self.design_results['Stainless steel']\n # Assume the electricity usage is proportional to the\n # volumetric flow rate\n self.power_utility.consumption = 0.1 * self.outs[0].F_vol\n \n \n # Now it's a proper use of property,\n # see the text enclosed in the pair of triple quotes?\n # That's the documentation (e.g., the helpful prompt\n # that will show up when users do\n # `?AerobicReactor.conversion`)\n @property\n def conversion(self):\n '''[float] Conversion of the organic matters in this reactor.'''\n return self._conversion\n @conversion.setter\n def conversion(self, i):\n if not 0 <= i <= 1:\n # Include the specific values in the error messgae\n # will often help the users (and many times you) in debugging\n raise AttributeError('`conversion` must be within [0, 1], '\n f'the provided value {i} is outside this range.')\n self._conversion = i",
"_____no_output_____"
],
[
"# Let's set up this unit again\nU2 = AerobicReactor2(ins=(ws.copy(), 'o2'), outs=('eff', 'co2'))",
"_____no_output_____"
],
[
"# Voila!\nU2.simulate()\nU2.results()",
"_____no_output_____"
],
[
"U2",
"_____no_output_____"
],
[
"# Trying to put an unrealistic value will show our helpful message\n# U2.conversion = 1.1",
"_____no_output_____"
]
],
[
[
"## 4. Other convenient features <a class=\"anchor\" id=\"s4\"></a>\nWe've done a good job in making the `AerobicReactor` class, but there are many helpful features that will make our lives much easier",
"_____no_output_____"
],
[
"### 4.1. Reactions\nHere's what we did for the reaction of MeOH and O2 to CO2 and H2O:\n```python\nconverted_meoh = x * inf.imol['S_CH3OH']\nconsumed_o2 = 1.5 * converted_meoh\ngenerated_co2 = converted_meoh\ngenerated_h2o = 2 * converted_meoh\neff.imol['S_CH3OH'] -= converted_meoh\neff.imol['S_O2'] -= consumed_o2\neff.imol['H2O'] += generated_h2o\nco2.imol['CO2'] = generated_co2\n```",
"_____no_output_____"
],
[
"For reactions like this, we can acutally use `Reaction` in Thermosteam to do it in a much more convenient way:\n```python\nfrom thermosteam.reaction import Reaction as Rxn\n# reaction definition reactant conversion\naerobic_rxn = Rxn('S_CH3OH + 1.5 O2 -> CO2 + 2 H2O', 'S_CH3OH', self.conversion)\n```\n\nIf we have multiple reactions, we can use `ParallelRxn` (if all reactions happen at once) or `SeriesReaction` (if these reactions happen in sequence), and we can use `ReactionSystem` to compile multiple `Reaction`, `ParallelRxn`, and `SeriesReaction` together.\n\nFor more detailed instructions, refer to [Thermosteam's documentation](https://thermosteam.readthedocs.io/en/latest/reaction/Reaction.html).",
"_____no_output_____"
],
[
"### 4.2. `cost` decorator\nIf we want to scale the cost of some equipment base on certain variables (e.g., scale the capital cost and electricity of a pump based on the flow rate, we can use the `cost` decorator (usage of decorator starts with the `@` symbol, again recall the `property` decorator).\n\nFor the demo purpose, let's assume that we need a pump for the aeration that will be scaled based on the mass flow rate of needed O2\n```python\nfrom biosteam.units.decorators import cost\n\n@cost('O2 flow rate', # the variable that the equipment is scaled on\n 'O2 pump', # name of the equipment\n CE=522, # chemical engineering plant cost index (CEPCI)\n S=40000, # value of the scaling basis\n cost=22500, # cost of the equipment when the variable is at the basis value\n n=0.8, # exponential scaling factor\n kW=75, # electricity usage\n N=1, # number of this equipment (will be defaulted to 1 if not given)\n BM=2.3) # bare module\nclass AerobicReactor(qs.SanUnit):\n ...\n\n # Note that in the unit, you'll need to define what 'O2 flow rate' is\n # in the `design_results` dict and its unit in the `_units` dict\n _units = {\n ...,\n 'O2 flow rate': 'kg/hr',\n }\n \n def _design(self):\n ...\n self.design_results['O2 flow rate'] = self.outs[1].F_mass\n```\n\nThe scaling equations are (`ub` is the upper bound):\n\n$$New\\ cost = N \\cdot cost \\bigg(\\frac{CE_{new}}{CE}\\bigg) \\bigg(\\frac{S_{new}}{N \\cdot S}\\bigg)^{n}$$\n \n$$Electricity\\ rate = kW \\bigg(\\frac{S_{new}}{S}\\bigg)$$\n\n$$N = ceil \\bigg( \\frac{S_{new}}{ub} \\bigg)$$",
"_____no_output_____"
],
[
"**Note:**\n\nYou can actually add the unit in the `@` expression, e.g., \n```python\n@cost('O2 flow rate', ..., units='kg/hr')\n```\nBut if later you define `_units` in the class definition by using \n```python\n_units = {\n 'Reactor volume': 'm3',\n 'Diameter': 'm',\n 'Height': 'm',\n 'Stainless steel': 'kg'\n}\n```\nYou'll throw away the previous definition.",
"_____no_output_____"
]
],
[
[
"# If you want to know the current CEPCI\nqs.CEPCI",
"_____no_output_____"
],
[
"# If you want to look up CEPCI by year\nqs.CEPCI_by_year",
"_____no_output_____"
]
],
[
[
"For more details, check out [BioSTEAM's documentation](https://biosteam.readthedocs.io/en/latest/tutorial/Unit_decorators.html).",
"_____no_output_____"
]
],
[
[
"# Let's use `Reaction` and `cost` decorator here,\n# I removed all the comments to make it shorter\nfrom thermosteam.reaction import Reaction as Rxn\nfrom biosteam.units.decorators import cost\n@cost('O2 flow rate', 'O2 pump', CE=522,\n S=40000, cost=22500, n=0.8, kW=75, BM=2.3)\nclass AerobicReactor3(qs.SanUnit):\n def __init__(self, ID='', ins=None, outs=(), thermo=None, init_with='WasteStream',\n conversion=0.9, aeration_rate=3, HRT=5):\n qs.SanUnit.__init__(self, ID, ins, outs, thermo, init_with)\n self.conversion = conversion\n self.aeration_rate = aeration_rate\n self.HRT = HRT\n self.F_BM = {'Tank': 2}\n self.aerobic_rxn = Rxn('S_CH3OH + 1.5 S_O2 -> CO2 + 2 H2O', 'S_CH3OH', conversion)\n\n _N_ins = 2\n _N_outs = 2\n \n def _run(self):\n inf, o2 = self.ins\n eff, co2 = self.outs\n o2.phase = co2.phase = 'g'\n \n o2_needed = self.aeration_rate * self.F_vol_in\n o2.imass['O2'] = o2_needed\n \n eff.mix_from(self.ins)\n eff.imass['S_O2'] = eff.imass['O2']\n eff.imass['O2'] = 0\n \n self.aerobic_rxn(eff.mol)\n\n eff.imass['X_OHO'] = 0.05 * inf.imass['S_CH3OH']\n eff.imass['S_CH3OH'] -= eff.imass['X_OHO']\n \n _units = {\n 'Volume': 'm3',\n 'Diameter': 'm',\n 'Height': 'm',\n 'Stainless steel': 'kg',\n 'O2 flow rate': 'kg/hr'\n }\n \n def _design(self):\n D = self.design_results\n tot_vol = self.outs[0].F_vol*self.HRT\n rx_vol = tot_vol / 0.8\n dia = (2*rx_vol/3.14)**(1/3)\n D['Volume'] = rx_vol\n D['Diameter'] = dia\n D['Height'] = H = 2 * dia\n\n ss = 3.14*(dia**2)*H + 3.14/4*(dia**2)\n D['Stainless steel'] = ss * 7500\n\n D['O2 flow rate'] = self.outs[1].F_mass\n \n \n def _cost(self):\n self.baseline_purchase_costs['Tank'] = \\\n 3 * self.design_results['Stainless steel']\n self.power_utility.consumption = 0.1 * self.outs[0].F_vol\n\n \n @property\n def conversion(self):\n '''[float] Conversion of the organic matters in this reactor.'''\n return self._conversion\n @conversion.setter\n def conversion(self, i):\n if not 0 <= i <= 1:\n raise AttributeError('`conversion` must be within [0, 1], '\n f'the provided value {i} is outside this range.')\n self._conversion = i",
"_____no_output_____"
],
[
"# Check out the results again\nU3 = AerobicReactor3(ins=(ws.copy(), 'o2'), outs=('eff', 'co2'))\nU3.simulate()\nU3.results()",
"/Users/yalinli_cabbi/opt/anaconda3/envs/demo/lib/python3.8/site-packages/biosteam/utils/piping.py:216: RuntimeWarning: <WasteStream: o2> has been replaced in registry\n else dock(Stream(i, thermo=thermo)) for i in streams]\n/Users/yalinli_cabbi/opt/anaconda3/envs/demo/lib/python3.8/site-packages/biosteam/utils/piping.py:216: RuntimeWarning: <WasteStream: eff> has been replaced in registry\n else dock(Stream(i, thermo=thermo)) for i in streams]\n/Users/yalinli_cabbi/opt/anaconda3/envs/demo/lib/python3.8/site-packages/biosteam/utils/piping.py:216: RuntimeWarning: <WasteStream: co2> has been replaced in registry\n else dock(Stream(i, thermo=thermo)) for i in streams]\n"
],
[
"U3",
"_____no_output_____"
]
],
[
[
"### 4.3. `Equipment`\nIf you have multiple equipment that will be used in many of your units, then you might consider using the `Equipment` class. For exemplary usage, check out the [documentation](https://qsdsan.readthedocs.io/en/latest/sanunits/ElectrochemicalCell.html) of `ElecchemicalCell` and the [source codes](https://github.com/QSD-Group/QSDsan/tree/main/qsdsan/equipments) of the corresponding equipment.",
"_____no_output_____"
],
[
"[Back to top](#top)",
"_____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",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
e72283b686c8dba127979f257a7671444038c539 | 188,655 | ipynb | Jupyter Notebook | happiness_index.ipynb | Thooost/python_samples | 7722fbac8ea512beca5c9527c4f80d66741a0fc9 | [
"MIT"
] | null | null | null | happiness_index.ipynb | Thooost/python_samples | 7722fbac8ea512beca5c9527c4f80d66741a0fc9 | [
"MIT"
] | null | null | null | happiness_index.ipynb | Thooost/python_samples | 7722fbac8ea512beca5c9527c4f80d66741a0fc9 | [
"MIT"
] | 1 | 2021-06-28T08:21:45.000Z | 2021-06-28T08:21:45.000Z | 113.374399 | 42,532 | 0.730174 | [
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"df = pd.read_csv(\"./data/world-happiness-report-2021.csv\")",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"ls = df.iloc[:,[0, 2]]",
"_____no_output_____"
],
[
"plt.bar(ls.iloc[:,1], ls.iloc[:,0])",
"_____no_output_____"
],
[
"ls.iloc[:,1]",
"_____no_output_____"
],
[
"df.iloc[:, [0,2]]",
"_____no_output_____"
],
[
"df = df.rename(columns={'Regional indicator': 'Region'})",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"df = df.reindex(sorted(df.columns), axis=1)",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"plt.plot(ls.iloc[:,1], ls.iloc[:,0])",
"_____no_output_____"
],
[
"plt.scatter(ls.iloc[:,1], ls.iloc[:,0])",
"_____no_output_____"
],
[
"plt.cluster(ls.iloc[:,1], ls.iloc[:,0])",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e72289d5fb0aa0b45acb287f4825e14c4c42ba49 | 267,892 | ipynb | Jupyter Notebook | input/eg01-eg30/eg01-30-overall-plots.ipynb | abachma2/transition-scenarios | 7084cf472593ff9552ff205e2cf84ac4d21ec3b0 | [
"BSD-3-Clause"
] | 2 | 2019-03-11T12:27:40.000Z | 2019-12-05T08:09:02.000Z | input/eg01-eg30/eg01-30-overall-plots.ipynb | abachma2/transition-scenarios | 7084cf472593ff9552ff205e2cf84ac4d21ec3b0 | [
"BSD-3-Clause"
] | 119 | 2016-09-14T16:15:54.000Z | 2022-03-16T20:28:18.000Z | input/eg01-eg30/eg01-30-overall-plots.ipynb | gwenchee/transition-scenarios | 17edc74bd7f6b7391930907447465c7dc2212ef7 | [
"BSD-3-Clause"
] | 11 | 2017-02-21T19:56:44.000Z | 2021-06-09T19:57:07.000Z | 1,585.159763 | 110,820 | 0.955243 | [
[
[
"# EG01-30\n** Deployment & Comparison of Prediction Method Plots **\n\nThese plots were used in the DDCA Journal Article (https://github.com/arfc/2019-ddca-journal-article), Demonstration of Demand Driven Deployment Capabilities in Cyclus Global Presentation (https://github.com/arfc/2019-chee-global), and the DDCA final quarterly report (https://github.com/arfc/ddca_numerical_exp). \n\nTo generate the plots in this Jupyter Notebook, you must go to the ARFC Fuel-Cycle Box (fuel-cycle/cyclus_output/d3ploy-transition-scenarios/eg01-eg30) and download the following sqlite files: \n* eg01-eg30-linpower-d3ploy-buffer0-fft.sqlite\n* eg01-eg30-linpower-d3ploy-buffer2000-fft.sqlite\n* eg01-eg30-linpower-d3ploy-buffer4000-fft.sqlite\n* eg01-eg30-linpower-d3ploy-buffer6000-fft.sqlite\n* eg01-eg30-linpower-d3ploy-buffer8000-fft.sqlite\n",
"_____no_output_____"
]
],
[
[
"import sys \nsys.path.insert(0, '../../scripts/')\nimport transition_plots as tp",
"_____no_output_____"
],
[
"sqlite30 = 'eg01-eg30-linpower-d3ploy-buffer8000-fft.sqlite'\nall_agents30 = tp.format_agent_dict(sqlite30,simple=False)\ntp.plot_agents(all_agents30,name='eg30-stack',simple=False)",
"_____no_output_____"
],
[
"commods = ['power']\ncommodnames = ['power']\nmethods = ['0-fft','2000-fft','4000-fft','6000-fft','8000-fft']\ngeneral_sqlite = 'eg01-eg30-linpower-d3ploy-buffer'\ntp.plot_all_undersupply(commods,commodnames,methods,general_sqlite,demand_eq='60000 + 250*t/12',\n title='EG1-30: Time steps with an undersupply of power for varying power buffer sizes',\n name='eg30-sa')",
"_____no_output_____"
],
[
"commods1 = ['sourceout',\n 'enrichmentout',\n 'moxmixerout',\n 'frmixerout',\n 'power']\ncommodnames1 = ['Natural Uranium',\n 'LWR Fuel',\n 'MOX Fuel',\n 'FR Fuel',\n 'Power']\ncommods2 = ['lwrout',\n 'lwrstorageout',\n 'moxout',\n 'moxstorageout',\n 'frout',\n 'frstorageout']\ncommodnames2 = ['LWR Used Fuel',\n 'Cool LWR Used Fuel',\n 'MOX Used Fuel',\n 'Cool MOX Used Fuel',\n 'FR Used Fuel',\n 'Cool FR Used Fuel']\nmethods = ['ma','arma','arch','poly','exp_smoothing','holt_winters','fft','sw_seasonal']\nmethodnames = ['MA','ARMA','ARCH','POLY','EXP SMOOTHING','HOLT WINTERS','FFT', 'STEPWISE SEASONAL']\ngeneral_sqlite = 'eg01-eg30-linpower-d3ploy-buffer0-'\ndemand_driven = True\ndemand_eq='60000+250*t/12'\ntitle = 'EG1-30: Time steps with an undersupply or under capacity of each commodity for different prediction methods'\nname = 'eg01-30-histogram'\nyticks=[0,5,10,15]\ntp.plot_histogram(commods1,commodnames1,commods2,commodnames2,methods,methodnames,general_sqlite,demand_eq,title,name,yticks)",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e72290d2268504d190e10763bdfc392fa85dd1e4 | 98,426 | ipynb | Jupyter Notebook | Assignment-4.ipynb | shobes572/DSI_Module-25 | 686bcd48f5ef2919a7df71a9c7e033e6f36006f5 | [
"MIT"
] | null | null | null | Assignment-4.ipynb | shobes572/DSI_Module-25 | 686bcd48f5ef2919a7df71a9c7e033e6f36006f5 | [
"MIT"
] | null | null | null | Assignment-4.ipynb | shobes572/DSI_Module-25 | 686bcd48f5ef2919a7df71a9c7e033e6f36006f5 | [
"MIT"
] | null | null | null | 427.93913 | 32,780 | 0.934438 | [
[
[
"from scipy.cluster.hierarchy import dendrogram, linkage\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import adjusted_rand_score, silhouette_score\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns",
"_____no_output_____"
],
[
"confile = list(pd.read_csv('../../dbcon.csv'))\npostgres_db = 'heartdisease'\ndb_connection = 'postgresql://{}:{}@{}:{}/{}'.format(confile[0], confile[1], confile[2], confile[3], postgres_db)\n\nquery = '''\nSELECT *\nFROM heartdisease\n;'''\n\nheartdisease_df = pd.read_sql(query, db_connection)\n\nX = heartdisease_df.iloc[:, :13]\ny = heartdisease_df.iloc[:, 13]\n\nX = X.replace(to_replace='?', value=0)\ny = np.where(y > 0, 0, 1)\n\nscaler = StandardScaler()\nscaled_X = scaler.fit_transform(X)",
"_____no_output_____"
],
[
"linkages = ['complete', 'average', 'ward']\nfor link in linkages:\n print(f\"With Linkage method \\\"{link}\\\": \")\n plt.figure(figsize=(20,10))\n dendrogram(linkage(scaled_X, method=link))\n plt.show()\n ",
"With Linkage method \"complete\": \n"
]
],
[
[
"The \"ward\" linkage method seems to have a breakdown that would allow the best segregation and clustering of data",
"_____no_output_____"
]
],
[
[
"link_comp_df = pd.DataFrame(index=linkages,columns=['ARI_Score', 'SIL_Score'])\nfor link in linkages:\n agg_model = AgglomerativeClustering(linkage=link, n_clusters=2)\n y_pred = agg_model.fit_predict(scaled_X)\n link_comp_df.loc[link, 'ARI_Score'] = adjusted_rand_score(y, y_pred)\n link_comp_df.loc[link, 'SIL_Score'] = silhouette_score(X, y_pred)\nlink_comp_df",
"_____no_output_____"
]
],
[
[
"This confirms \"ward\" is the better method for this model",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown"
] | [
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7229e4962523ee5b2680bc2a14cfe5eb69c35e2 | 30,066 | ipynb | Jupyter Notebook | Week2_Linear_Regression.ipynb | fadelramli/Tugas-MachineLearning | 35316e0113925953984ec65c68cd6621232c647c | [
"Apache-2.0"
] | null | null | null | Week2_Linear_Regression.ipynb | fadelramli/Tugas-MachineLearning | 35316e0113925953984ec65c68cd6621232c647c | [
"Apache-2.0"
] | null | null | null | Week2_Linear_Regression.ipynb | fadelramli/Tugas-MachineLearning | 35316e0113925953984ec65c68cd6621232c647c | [
"Apache-2.0"
] | null | null | null | 74.791045 | 13,986 | 0.683895 | [
[
[
"<a href=\"https://colab.research.google.com/github/fadelramli/Tugas-MachineLearning/blob/main/Week2_Linear_Regression.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import datasets",
"_____no_output_____"
],
[
"diabetes = datasets.load_diabetes()",
"_____no_output_____"
],
[
"diabetes",
"_____no_output_____"
],
[
"diabetes.data.shape #feature matrix shape",
"_____no_output_____"
],
[
"diabetes.target.shape",
"_____no_output_____"
],
[
"diabetes.feature_names",
"_____no_output_____"
],
[
"#separate train and test data\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(diabetes.data, diabetes.target, test_size=0.2, random_state = 0)\n#steps to model something with sklearn\n#1. Set up model\nmodel = LinearRegression()\n#2. Use fit\nmodel.fit(x_train, y_train)\n#3. Check the score\nmodel.score(x_test, y_test)",
"_____no_output_____"
],
[
"#After fitting the model\nmodel.coef_ #get the coefficient",
"_____no_output_____"
],
[
"model.intercept_ #get the intercept",
"_____no_output_____"
],
[
"model.predict(x_test)",
"_____no_output_____"
],
[
"#To better understand why the prediction and actual different, you can plot the following way:\n#plot prediction and actual data\ny_pred = model.predict(x_test)\nplt.plot(y_test, y_pred, '.')\n\n#plot a line, a perfit predict would all fall on this line\nX = np.linspace (0, 330, 100)\ny = X\nplt.plot(X, y)\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e722a4d899d08166e17d3cd21320f75688427742 | 3,629 | ipynb | Jupyter Notebook | examples/notebooks/18_point_layer.ipynb | aplitest/leafmap | 17dde7dc8aca6553633608e5c6135799baf27176 | [
"MIT"
] | 1,187 | 2021-03-10T02:50:29.000Z | 2022-03-29T19:53:40.000Z | examples/notebooks/18_point_layer.ipynb | aplitest/leafmap | 17dde7dc8aca6553633608e5c6135799baf27176 | [
"MIT"
] | 118 | 2021-05-25T18:17:20.000Z | 2022-03-20T20:58:32.000Z | examples/notebooks/18_point_layer.ipynb | aplitest/leafmap | 17dde7dc8aca6553633608e5c6135799baf27176 | [
"MIT"
] | 137 | 2021-03-23T09:49:13.000Z | 2022-03-27T21:39:22.000Z | 22.263804 | 171 | 0.559383 | [
[
[
"[](https://githubtocolab.com/giswqs/leafmap/blob/master/examples/notebooks/18_point_layer.ipynb)\n[](https://gishub.org/leafmap-binder)\n\n**Adding a point layer with popup attributes to the map**\n\nThe notebook requires the ipyleaflet plotting backend. Folium is not supported. The point dataset can be any geopandas-supported file stored locally or online. \n\n\nUncomment the following line to install [leafmap](https://leafmap.org) if needed.",
"_____no_output_____"
]
],
[
[
"# !pip install leafmap",
"_____no_output_____"
],
[
"from leafmap import leafmap",
"_____no_output_____"
]
],
[
[
"Use the toolbar GUI to open a point-type vector dataset.",
"_____no_output_____"
]
],
[
[
"m = leafmap.Map()\nm",
"_____no_output_____"
]
],
[
[
"Display a single popup attribute.",
"_____no_output_____"
]
],
[
[
"m = leafmap.Map()\nm.add_point_layer(\"../data/us_cities.geojson\", popup=\"name\", layer_name=\"US Cities\")\nm",
"_____no_output_____"
]
],
[
[
"Display multiple popup attributes.",
"_____no_output_____"
]
],
[
[
"m = leafmap.Map()\nurl= \"https://raw.githubusercontent.com/giswqs/leafmap/master/examples/data/us_cities.geojson\"\nm.add_point_layer(url, popup=[\"name\", \"pop_max\"], layer_name=\"US Cities\")\nm",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e722abfae3c777a722d09e16ffc69f73c4a1a70e | 75,970 | ipynb | Jupyter Notebook | merge/.ipynb_checkpoints/merge-checkpoint.ipynb | dSHARP-CMU/megaText | 3b321bd7bf95591b41b10e0819ff98b9d8466dfb | [
"CC-BY-4.0"
] | null | null | null | merge/.ipynb_checkpoints/merge-checkpoint.ipynb | dSHARP-CMU/megaText | 3b321bd7bf95591b41b10e0819ff98b9d8466dfb | [
"CC-BY-4.0"
] | null | null | null | merge/.ipynb_checkpoints/merge-checkpoint.ipynb | dSHARP-CMU/megaText | 3b321bd7bf95591b41b10e0819ff98b9d8466dfb | [
"CC-BY-4.0"
] | null | null | null | 64.655319 | 1,820 | 0.563815 | [
[
[
"import numpy as np\nimport pandas as pd\nimport fuzzymatcher\nfrom fuzzywuzzy import fuzz\nfrom fuzzywuzzy import process",
"_____no_output_____"
],
[
"df = pd.read_csv('title3.csv', encoding = \"ISO-8859-1\")\ndf.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 64398 entries, 0 to 64397\nData columns (total 24 columns):\nid 64398 non-null int64\ntitle 64398 non-null object\nimdb_index 29 non-null object\nkind_id 64398 non-null int64\nproduction_year 64398 non-null int64\nimdb_id 0 non-null float64\nphonetic_code 55232 non-null object\nepisode_of_id 59636 non-null float64\nseason_nr 54786 non-null float64\nepisode_nr 54757 non-null float64\nseries_years 3896 non-null object\nmd5sum 64398 non-null object\nid.1 64398 non-null int64\nmovie_id 64398 non-null int64\ncompany_id 64398 non-null int64\ncompany_type_id 64398 non-null int64\nnote 32211 non-null object\nid.2 64398 non-null int64\nname 64398 non-null object\ncountry_code 64398 non-null object\nimdb_id.1 0 non-null float64\nname_pcode_nf 64398 non-null object\nname_pcode_sf 64398 non-null object\nmd5sum.1 64398 non-null object\ndtypes: float64(5), int64(8), object(11)\nmemory usage: 11.8+ MB\n"
],
[
"df_right = df[df.kind_id != 7.0]\n\ndf_right.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 4762 entries, 0 to 64397\nData columns (total 24 columns):\nid 4762 non-null int64\ntitle 4762 non-null object\nimdb_index 29 non-null object\nkind_id 4762 non-null int64\nproduction_year 4762 non-null int64\nimdb_id 0 non-null float64\nphonetic_code 4762 non-null object\nepisode_of_id 0 non-null float64\nseason_nr 0 non-null float64\nepisode_nr 0 non-null float64\nseries_years 3896 non-null object\nmd5sum 4762 non-null object\nid.1 4762 non-null int64\nmovie_id 4762 non-null int64\ncompany_id 4762 non-null int64\ncompany_type_id 4762 non-null int64\nnote 3046 non-null object\nid.2 4762 non-null int64\nname 4762 non-null object\ncountry_code 4762 non-null object\nimdb_id.1 0 non-null float64\nname_pcode_nf 4762 non-null object\nname_pcode_sf 4762 non-null object\nmd5sum.1 4762 non-null object\ndtypes: float64(5), int64(8), object(11)\nmemory usage: 930.1+ KB\n"
],
[
"df_right.describe()",
"_____no_output_____"
],
[
"df_left = pd.read_csv('enc.csv', encoding = \"ISO-8859-1\")\ndf_left.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1732 entries, 0 to 1731\nData columns (total 12 columns):\nNumber 1732 non-null int64\nProgram Title 1732 non-null object\nProgram Type 1731 non-null object\nProgram Genre 1731 non-null object\nNetwork 1704 non-null object\nFirst Air Month 131 non-null float64\nFirst Air Day 123 non-null float64\nFirst Air Year 1732 non-null int64\nLast Air Month 2 non-null float64\nLast Air Day 2 non-null float64\nLast Air Year 895 non-null object\nProgram Description 1732 non-null object\ndtypes: float64(4), int64(2), object(6)\nmemory usage: 162.5+ KB\n"
],
[
"df_left[\"Program Type\"].value_counts()",
"_____no_output_____"
],
[
"df_right = df_right.astype(str).apply(lambda x: x.str.lower())\ndf_left = df_left.astype(str).apply(lambda x: x.str.lower())",
"_____no_output_____"
],
[
"df_right.drop(df_right.columns[[2,5,7,8,9, 20]], axis=1, inplace=True)",
"_____no_output_____"
],
[
"df_right.head()",
"_____no_output_____"
],
[
"df_right.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 4762 entries, 0 to 64397\nData columns (total 18 columns):\nid 4762 non-null object\ntitle 4762 non-null object\nkind_id 4762 non-null object\nproduction_year 4762 non-null object\nphonetic_code 4762 non-null object\nseries_years 4762 non-null object\nmd5sum 4762 non-null object\nid.1 4762 non-null object\nmovie_id 4762 non-null object\ncompany_id 4762 non-null object\ncompany_type_id 4762 non-null object\nnote 4762 non-null object\nid.2 4762 non-null object\nname 4762 non-null object\ncountry_code 4762 non-null object\nname_pcode_nf 4762 non-null object\nname_pcode_sf 4762 non-null object\nmd5sum.1 4762 non-null object\ndtypes: object(18)\nmemory usage: 706.9+ KB\n"
],
[
"df_left.drop(df_left.head().columns[[5,6,8,9]], axis=1, inplace=True)",
"_____no_output_____"
],
[
"df_left.head()",
"_____no_output_____"
],
[
"df_right[\"title\"].head()",
"_____no_output_____"
],
[
"df_left[\"Program Title\"] = df_left[\"Program Title\"].str.replace('[^\\w\\s]','')",
"_____no_output_____"
],
[
"df_left[\"Program Title\"].head()",
"_____no_output_____"
],
[
"(process.extract(x, df_left, scorer= fuzz.ratio) for x in df_right)",
"_____no_output_____"
],
[
"#This works but needs tweaking\n\nnames_array=[]\nratio_array=[]\n\ndef match_names(wrong_names,correct_names):\n for row in wrong_names:\n x=process.extractOne(row, correct_names)\n names_array.append(x[0])\n ratio_array.append(x[1])\n return names_array,ratio_array\n \n \n#imdb names dataset\n\nwrong_names=df_left[\"Program Title\"].dropna().values\n \n#enc names dataset\ncorrect_names=df_right[\"title\"].dropna().values\n \nname_match,ratio_match=match_names(wrong_names,correct_names)\n \ndf_left['correct_name']=pd.Series(name_match)\ndf_left['name_ratio']=pd.Series(ratio_match)\n \n \nprint(df_left[['Program Title','correct_name','name_ratio']].head(10))",
" Program Title correct_name \\\n0 mary kay and johnny arthur godfrey and his ukulele \n1 the small fry club claudia: the story of a marriage \n2 crawford mystery theater crawford mystery theatre \n3 public prosecutor the public life of cliff norton \n4 juvenile jury fury \n5 the kraft television theater kraft television theatre \n6 kukla fran and ollie arthur godfrey and his ukulele \n7 howdy doody hollywood today \n8 midwestern hayride midwestern hayride \n9 actors studio studio 57 \n\n name_ratio \n0 86 \n1 86 \n2 96 \n3 86 \n4 68 \n5 88 \n6 86 \n7 62 \n8 100 \n9 76 \n"
],
[
"#df_left.to_csv(\"testing.csv\")",
"_____no_output_____"
],
[
"df_merge = pd.merge(df_left, df_right, left_on= \"correct_name\", right_on = \"title\")",
"_____no_output_____"
],
[
"print(df_merge.head(10))",
" Number Program Title Program Type Program Genre \\\n0 5137 mary kay and johnny series comedy \n1 4498 kukla fran and ollie series children \n2 340 and everything nice series women \n3 5397 mr and mrs carroll series variety \n4 1129 burns and allen series comedy \n5 464 arthur godfrey and his ukulele series variety \n6 5673 mystery and mrs test program crime drama \n7 8684 ukulele ike series variety \n8 8731 unk and andy series children \n9 4919 lum and abner pilot comedy \n\n Network First Air Year Last Air Year \\\n0 dumont, nbc, cbs 1947 1950 \n1 nbc, abc 1947 1957 \n2 dumont 1949 1950 \n3 dumont 1950 1951 \n4 cbs 1950 1958 \n5 cbs 1950 nan \n6 abc 1950 nan \n7 cbs 1950 nan \n8 syn. 1950 nan \n9 cbs 1951 nan \n\n Program Description \\\n0 the marital misadventures of mary kay and joh... \n1 the series, set against the background of the... \n2 beauty tips, fashion advice and health tips g... \n3 musician-singer jimmy carroll and his wife, s... \n4 the shortened tv guide title for the george b... \n5 an informal program of music and chatter (hum... \n6 sally and george fame are a young married cou... \n7 music and songs with musician cliff edwards, ... \n8 a program, aimed at preschoolers, that relate... \n9 a second pilot (see prior title) based on the... \n\n correct_name name_ratio \\\n0 arthur godfrey and his ukulele 86 \n1 arthur godfrey and his ukulele 86 \n2 arthur godfrey and his ukulele 86 \n3 arthur godfrey and his ukulele 86 \n4 arthur godfrey and his ukulele 86 \n5 arthur godfrey and his ukulele 100 \n6 arthur godfrey and his ukulele 86 \n7 arthur godfrey and his ukulele 86 \n8 arthur godfrey and his ukulele 86 \n9 arthur godfrey and his ukulele 86 \n\n ... movie_id company_id company_type_id note \\\n0 ... 194351 66 1 (tv) \n1 ... 194351 66 1 (tv) \n2 ... 194351 66 1 (tv) \n3 ... 194351 66 1 (tv) \n4 ... 194351 66 1 (tv) \n5 ... 194351 66 1 (tv) \n6 ... 194351 66 1 (tv) \n7 ... 194351 66 1 (tv) \n8 ... 194351 66 1 (tv) \n9 ... 194351 66 1 (tv) \n\n id.2 name country_code name_pcode_nf \\\n0 66 columbia broadcasting system (cbs) [us] c4516 \n1 66 columbia broadcasting system (cbs) [us] c4516 \n2 66 columbia broadcasting system (cbs) [us] c4516 \n3 66 columbia broadcasting system (cbs) [us] c4516 \n4 66 columbia broadcasting system (cbs) [us] c4516 \n5 66 columbia broadcasting system (cbs) [us] c4516 \n6 66 columbia broadcasting system (cbs) [us] c4516 \n7 66 columbia broadcasting system (cbs) [us] c4516 \n8 66 columbia broadcasting system (cbs) [us] c4516 \n9 66 columbia broadcasting system (cbs) [us] c4516 \n\n name_pcode_sf md5sum.1 \n0 c4516 7ae3ee174d2d4b06fc3d2ba6d7dc2fab \n1 c4516 7ae3ee174d2d4b06fc3d2ba6d7dc2fab \n2 c4516 7ae3ee174d2d4b06fc3d2ba6d7dc2fab \n3 c4516 7ae3ee174d2d4b06fc3d2ba6d7dc2fab \n4 c4516 7ae3ee174d2d4b06fc3d2ba6d7dc2fab \n5 c4516 7ae3ee174d2d4b06fc3d2ba6d7dc2fab \n6 c4516 7ae3ee174d2d4b06fc3d2ba6d7dc2fab \n7 c4516 7ae3ee174d2d4b06fc3d2ba6d7dc2fab \n8 c4516 7ae3ee174d2d4b06fc3d2ba6d7dc2fab \n9 c4516 7ae3ee174d2d4b06fc3d2ba6d7dc2fab \n\n[10 rows x 28 columns]\n"
],
[
"#df_merge.to_csv(\"merged.csv\")",
"_____no_output_____"
],
[
"#DOES NOT WORK\n#Columns to match on from df_left\n\ndf_left.dropna().values\ndf_right.dropna().values\n\nleft_on = [\"Program Title\", \"First Air Year\"]\n\n# Columns to match on from df_right\nright_on = [\"title\", \"production_year\"]\n\nfuzzymatcher.link_table(df_left, df_right, left_on, right_on)",
"_____no_output_____"
],
[
"#DOES NOT WORK\nfuzzymatcher.fuzzy_left_join(df_left, df_right, left_on = \"Program Title\", right_on = \"title\")",
"_____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"
]
] |
e722ad19b8cf8faf116ba5e75e74fbedbe0b328f | 54,018 | ipynb | Jupyter Notebook | Class Work/AppliedDescriptiveStatistics.ipynb | Pondorasti/DS-1.1 | bce3866b2c70e4769ca8dab8e2933ae9ab23505e | [
"MIT"
] | null | null | null | Class Work/AppliedDescriptiveStatistics.ipynb | Pondorasti/DS-1.1 | bce3866b2c70e4769ca8dab8e2933ae9ab23505e | [
"MIT"
] | null | null | null | Class Work/AppliedDescriptiveStatistics.ipynb | Pondorasti/DS-1.1 | bce3866b2c70e4769ca8dab8e2933ae9ab23505e | [
"MIT"
] | null | null | null | 80.145401 | 18,689 | 0.648173 | [
[
[
"# Learning Objectives\n\nAt the end of this class, you will be able to...\n\n- Write down functions to compute mean, median and mode \n\n- Describe variance and what it reflects \n\n- Express the meaning of percentile",
"_____no_output_____"
],
[
"# An Introduction to Descriptive Statistics\n\n- At this point in our course, we've had plenty of time, experience, and practice in manipulating our data. \n\n- However, to really _understand_ our data and underlying patterns across it, we need to dive a layer deeper into the mathematics behind data mechanics and dynamics.\n\n- In order to be able to draw conclusions from our data, we need to be able to **describe and interpret our data**.\n\n- This will become essential for more advanced data science concepts in data visualization, machine learning, and deep learning.",
"_____no_output_____"
],
[
"## Measures of Central Tendency\n\nA [**Central Tendency**](https://en.wikipedia.org/wiki/Central_tendency) is a central (typical) value for a probability distribution\n\n- In statistics, we often find that describing data by _averages_ allows us to more often make more powerful assertions regarding the data as a whole. \n\n- We often use **three key measures of central tendency** to help describe the **centroid** (arithmetic mean trend across a distribution) of our data:\n - **Mean**\n - **Median**\n - **Mode**",
"_____no_output_____"
],
[
"### The mean is the raw average value across our data. \n\nCalculating the mean is simple: _compute the sum of all values across our data and divide by the total number of values in our dataset_.\n\nWe've been using the mean for years and years, but such a surprisingly simple arithmetic calculation turns out to have massive implications across being able to critically understand and break down complex datasets! \n",
"_____no_output_____"
],
[
"### Activity: _Write a function to compute the mean from an arbitrary dataset._",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\ndata = np.array([1, 3, 5, 2, 3, 7, 8, 4, 10, 0, 6, 7, 3, 0, 3, 0, 5, 7, 10, 1, 4, 9, 3])\n\n\ndef compute_mean(dataset):\n \"\"\" Main function that calculates the average value across our data. \"\"\"\n sum = 0\n for number in data:\n sum += number\n\n return sum / data.size\n \n\n\ncompute_mean(data)\n# data.mean()",
"_____no_output_____"
]
],
[
[
"## Activity (Titanic):\n\n- What is the average age of male passengers that survived?\n\nOnce you've found the average, talk with a neighbor who has also found the average, and compare how you each came about to your solution",
"_____no_output_____"
]
],
[
[
"import pandas as pd\ntitanicdf = pd.read_csv(\"datasets/titanic.csv\")\ntitanicdf.dropna(inplace=True)\n\ntitanicdf[titanicdf[\"Sex\"] == \"male\"][\"Age\"].mean()",
"_____no_output_____"
],
[
"titanicdf[(titanicdf[\"Survived\"] == 1) & (titanicdf[\"Age\"] > 20)][\"Fare\"].mean()",
"_____no_output_____"
]
],
[
[
"### The median is the \"middle value\" or midpoint across our data.\n\nDetermining the median is as simple as it sounds: _find the data value lying in the exact middle of our dataset_.\n\nOne critical exception occurs when our data has an even number of values and thus has **two values** at its center: _in these cases, find the **mean** value of the two medians to obtain the true median across our data_. \n\n**Remember:** the median can only be calculated across _sorted data_!\n\nIf data is distributed in a non-normal manner, then we can learn a great deal from interpreting what the exact median value of our dataset is. ",
"_____no_output_____"
],
[
"### Activity: _Write a function to compute the median from an arbitrary dataset._\n\nOnce you write the function, compare with a neighbor's implementation",
"_____no_output_____"
]
],
[
[
"data = np.array([1, 3, 5, 2, 3, 7, 8, 4, 10, 0, 6, 7, 3, 0, 3, 0, 5, 7, 10, 1, 4, 9, 3])\n\n# TODO: Complete this function by having the function return the exact true median value of our dataset.\n# HINT: Consider using DataFrame slicing to help with identifying the correct median value(s).\ndef compute_median(dataset):\n \"\"\" Main function that determines the median value across our data. \"\"\"\n count = len(dataset)\n middle = count // 2\n dataset = np.sort(dataset)\n\n if count < 1:\n return 0\n if count % 2 == 1:\n return dataset[middle]\n else:\n return (dataset[middle - 1] + dataset[middle]) / 2\n \ncompute_median(data)\nnp.median(data)",
"_____no_output_____"
]
],
[
[
"### The mode is the most commonly occurring value or feature across our data.\n\nDetermining the mode is relatively simple: _find the value that occurs most frequently across our data_.\n\nRemember that if all values across our data are unique and only occur once, then our data **has no mode**!\n\nThe mode is also an interesting measure of _central tendency_ in that it can be applied towards categorical (non-numerical) data; one can find frequently occurring categories without running any calculations. ",
"_____no_output_____"
],
[
"### Activity: _Write a function to compute the mode from an arbitrary dataset._\n\nOnce you write the function, compare with a neighbor's implementation",
"_____no_output_____"
]
],
[
[
"# NOTE: Tricker than it looks!\ndata = np.array([1, 3, 5, 2, 3, 7, 8, 4, 10, 0, 6, 7, 3, 0, 3, 0, 5, 7, 10, 1, 4, 9, 3])\n\n# TODO: Complete this function by having the function return the relative mode across our dataset.\n# HINT: Remember histograms and tokenization from CS 1.2? How many they help you here? \ndef compute_mode(dataset):\n \"\"\" Main function that determines the mode value across our data. \"\"\"\n return\n\ncompute_mode(data)",
"_____no_output_____"
]
],
[
[
"There we have it!\n\nThree measures of central tendency that are critically important to understanding the distribution of our data. \n\nIn future classes on distributions and introductory inferential statistics, we'll talk more about exactly **why** these measures are so important. ",
"_____no_output_____"
],
[
"## Measures of Spread and Variance\n\nLike our friends in the central tendency community, measures of spread and variance do their best to describe patterns across our data as a whole.\n\nHowever, unlike measures of central tendency, which focus on the distribution of our data towards an arithmetic centroid, measures of spread and variance talk about the shape and layout of our data all across the board!\n\nIn this course, there are **two key measures of spread and variance** to help describe the shape of our data:\n- **Range**\n- **Variance**, **Standard Deviation**\n",
"_____no_output_____"
],
[
"## What is Range?\n\n**Range** is the difference between the highest and lowest values in a data set. It is one of the simplest measures of **spread** (the extent to which a distribution is stretched or squeezed). We'll use variance/standard deviation to help give more information around all of this!",
"_____no_output_____"
],
[
"## What is standard deviation or variance?\n\nLet's learn it by example:\n \n- We measured the number of rainy days during Fall in three different cities in the last 5 years:",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndf = pd.DataFrame({'Rainy':[29,28,32,35,36,12,18,30,45,55, 32,32,32,32,32], 'City':['City_A']*5 + ['City_B']*5 + ['City_C']*5})\ndf",
"_____no_output_____"
]
],
[
[
"## What is the mean of rainy days for City A, B and C?",
"_____no_output_____"
]
],
[
[
"print(np.mean(df[df['City'] == 'City_A']['Rainy']))\n\nprint(np.mean(df[df['City'] == 'City_B']['Rainy']))\n\nprint(np.mean(df[df['City'] == 'City_C']['Rainy']))",
"32.0\n32.0\n32.0\n"
]
],
[
[
"## Which city has more variation?\n\n**Standard deviation (std), which is the square root of variance,** can capture the variations in different arrays\n\n[Docs on the std function](https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html) from Numpy",
"_____no_output_____"
]
],
[
[
"print(np.std(df[df['City'] == 'City_A']['Rainy']))\n\nprint(np.std(df[df['City'] == 'City_B']['Rainy']))\n\nprint(np.std(df[df['City'] == 'City_C']['Rainy']))",
"3.1622776601683795\n16.112107248898266\n0.0\n"
]
],
[
[
"## Let's plot the variations in the data",
"_____no_output_____"
]
],
[
[
"sns.lineplot(y='Rainy', x='City', data=df)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Most (or majority) of the values (rainy days) in Cities A, B and C are between mean - std and mean + std",
"_____no_output_____"
]
],
[
[
"\nprint([32 - np.std(df[df['City'] == 'City_A']['Rainy']), 32 + np.std(df[df['City'] == 'City_A']['Rainy'])])\n\nprint([32 - np.std(df[df['City'] == 'City_B']['Rainy']), 32 + np.std(df[df['City'] == 'City_B']['Rainy'])])\n\nprint([32 - np.std(df[df['City'] == 'City_C']['Rainy']), 32 + np.std(df[df['City'] == 'City_C']['Rainy'])])\n",
"[28.837722339831622, 35.16227766016838]\n[15.887892751101734, 48.11210724889827]\n[32.0, 32.0]\n"
]
],
[
[
"# Percentile\n\nThe value below which a percentage of data falls.\n\n## Activity - Compute 75% Percentile for Fare in Titanic\nWe want to compute:\n\n- What fare value did 75% of all the fare values fall below\n\nHow would we do this?\n\n**Hint:** Use Numpy's [percentile](https://docs.scipy.org/doc/numpy/reference/generated/numpy.percentile.html) function\n\nWhen you're done, compare implementations with a neighbor",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv(\"datasets/titanic.csv\")\ndf\nnp.percentile(df['Fare'], 75)",
"_____no_output_____"
]
],
[
[
"## Verify that 75 percent of passengers paid less than 31.0 Dollar",
"_____no_output_____"
]
],
[
[
"# Slice the data based on Fare for those paid less than 31 Dollar\nnumbers_below_percentile = df[df['Fare'] <= np.percentile(df[\"Fare\"], 75)]\n\n# Compute the size of the sliced dataframe and divide over all number of passengers\npr_below_percentile = len(numbers_below_percentile)/len(df[\"Fare\"])\n\npr_below_percentile",
"_____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",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e722bd6c0ffb1c503ca1c65c464c955210c9032d | 13,116 | ipynb | Jupyter Notebook | python3/notebooks/rcv1/tensorflow-word2vec.ipynb | tobby2002/python-sandbox | 6d9056f0cf5ece62026534c33ed04e97416e5430 | [
"MIT"
] | 39 | 2017-12-28T11:25:12.000Z | 2022-02-08T19:21:34.000Z | python3/notebooks/rcv1/tensorflow-word2vec.ipynb | tobby2002/python-sandbox | 6d9056f0cf5ece62026534c33ed04e97416e5430 | [
"MIT"
] | 14 | 2020-01-28T22:02:25.000Z | 2022-02-09T23:28:37.000Z | python3/notebooks/rcv1/tensorflow-word2vec.ipynb | tobby2002/python-sandbox | 6d9056f0cf5ece62026534c33ed04e97416e5430 | [
"MIT"
] | 49 | 2018-02-01T03:12:14.000Z | 2022-03-14T15:56:13.000Z | 31.990244 | 99 | 0.531793 | [
[
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport math\nimport os\nimport random\nimport zipfile\n\nimport numpy as np\nfrom six.moves import urllib\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\nfrom tensorflow.python.client import device_lib\n\n%matplotlib inline",
"_____no_output_____"
],
[
"local_device_protos = device_lib.list_local_devices()\n[x.name for x in local_device_protos if x.device_type == 'GPU']",
"_____no_output_____"
],
[
"path_to_data=\"../../data/rcv1/string/out/reuters-rcv1-full-tokenized.txt\"\n\nwith open(path_to_data) as f:\n words = tf.compat.as_str(f.read()).split()",
"_____no_output_____"
],
[
"print('Data size', len(words))",
"_____no_output_____"
],
[
"# Step 2: Build the dictionary and replace rare words with UNK token.\nvocabulary_size = 50000\n\ndef build_dataset(words):\n count = [['UNK', -1]]\n count.extend(collections.Counter(words).most_common(vocabulary_size - 1))\n dictionary = dict()\n\n for word, _ in count:\n dictionary[word] = len(dictionary)\n \n data = list()\n unk_count = 0\n \n for word in words:\n if word in dictionary:\n index = dictionary[word]\n else:\n index = 0 # dictionary['UNK']\n unk_count += 1\n data.append(index)\n \n count[0][1] = unk_count\n reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n \n return data, count, dictionary, reverse_dictionary",
"_____no_output_____"
],
[
"data, count, dictionary, reverse_dictionary = build_dataset(words)\ndel words # Hint to reduce memory.\nprint('Most common words (+UNK)', count[:5])\nprint('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])\n\ndata_index = 0",
"_____no_output_____"
],
[
"# Step 3: Function to generate a training batch for the skip-gram model.\ndef generate_batch(batch_size, num_skips, skip_window):\n global data_index\n \n assert batch_size % num_skips == 0\n assert num_skips <= 2 * skip_window\n \n batch = np.ndarray(shape=(batch_size), dtype=np.int32)\n labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)\n \n span = 2 * skip_window + 1 # [ skip_window target skip_window ]\n buffer = collections.deque(maxlen=span)\n \n for _ in range(span):\n buffer.append(data[data_index])\n data_index = (data_index + 1) % len(data)\n \n for i in range(batch_size // num_skips):\n target = skip_window # target label at the center of the buffer\n targets_to_avoid = [skip_window]\n \n for j in range(num_skips):\n while target in targets_to_avoid:\n target = random.randint(0, span - 1)\n \n targets_to_avoid.append(target)\n batch[i * num_skips + j] = buffer[skip_window]\n labels[i * num_skips + j, 0] = buffer[target]\n \n buffer.append(data[data_index])\n data_index = (data_index + 1) % len(data)\n \n return batch, labels",
"_____no_output_____"
],
[
"batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1)\nfor i in range(8):\n print(batch[i], reverse_dictionary[batch[i]],\n '->', labels[i, 0], reverse_dictionary[labels[i, 0]])",
"_____no_output_____"
],
[
"# Step 4: Build and train a skip-gram model.\n\nbatch_size = 128\nembedding_size = 128 # Dimension of the embedding vector.\nskip_window = 1 # How many words to consider left and right.\nnum_skips = 2 # How many times to reuse an input to generate a label.",
"_____no_output_____"
],
[
"# We pick a random validation set to sample nearest neighbors. Here we limit the\n# validation samples to the words that have a low numeric ID, which by\n# construction are also the most frequent.\nvalid_size = 16 # Random set of words to evaluate similarity on.\nvalid_window = 100 # Only pick dev samples in the head of the distribution.\nvalid_examples = np.random.choice(valid_window, valid_size, replace=False)\nnum_sampled = 64 # Number of negative examples to sample.",
"_____no_output_____"
],
[
"graph = tf.Graph()",
"_____no_output_____"
],
[
"with graph.as_default():\n\n # Input data.\n train_inputs = tf.placeholder(tf.int32, shape=[batch_size])\n train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])\n valid_dataset = tf.constant(valid_examples, dtype=tf.int32)\n\n # Ops and variables pinned to the CPU because of missing GPU implementation\n with tf.device('/gpu:0'):\n # Look up embeddings for inputs.\n embeddings = tf.Variable(\n tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))\n embed = tf.nn.embedding_lookup(embeddings, train_inputs)\n\n # Construct the variables for the NCE loss\n nce_weights = tf.Variable(\n tf.truncated_normal([vocabulary_size, embedding_size],\n stddev=1.0 / math.sqrt(embedding_size)))\n nce_biases = tf.Variable(tf.zeros([vocabulary_size]))\n\n # Compute the average NCE loss for the batch.\n # tf.nce_loss automatically draws a new sample of the negative labels each\n # time we evaluate the loss.\n loss = tf.reduce_mean(\n tf.nn.nce_loss(weights=nce_weights,\n biases=nce_biases,\n labels=train_labels,\n inputs=embed,\n num_sampled=num_sampled,\n num_classes=vocabulary_size))\n\n # Construct the SGD optimizer using a learning rate of 1.0.\n optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)\n\n # Compute the cosine similarity between minibatch examples and all embeddings.\n norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))\n normalized_embeddings = embeddings / norm\n valid_embeddings = tf.nn.embedding_lookup(\n normalized_embeddings, valid_dataset)\n similarity = tf.matmul(\n valid_embeddings, normalized_embeddings, transpose_b=True)\n\n # Add variable initializer.\n init = tf.initialize_all_variables()",
"_____no_output_____"
],
[
"num_steps = 100001",
"_____no_output_____"
],
[
"with tf.Session(config=tf.ConfigProto(log_device_placement=True), graph=graph) as session:\n # We must initialize all variables before we use them.\n init.run()\n print(\"Initialized\")\n\n average_loss = 0\n for step in xrange(num_steps):\n batch_inputs, batch_labels = generate_batch(\n batch_size, num_skips, skip_window)\n feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels}\n\n # We perform one update step by evaluating the optimizer op (including it\n # in the list of returned values for session.run()\n _, loss_val = session.run([optimizer, loss], feed_dict=feed_dict)\n \n average_loss += loss_val\n\n if step % 2000 == 0:\n if step > 0:\n average_loss /= 2000\n # The average loss is an estimate of the loss over the last 2000 batches.\n print(\"Average loss at step \", step, \": \", average_loss)\n average_loss = 0\n\n # Note that this is expensive (~20% slowdown if computed every 500 steps)\n if step % 10000 == 0:\n sim = similarity.eval()\n for i in xrange(valid_size):\n valid_word = reverse_dictionary[valid_examples[i]]\n top_k = 8 # number of nearest neighbors\n nearest = (-sim[i, :]).argsort()[1:top_k + 1]\n log_str = \"Nearest to %s:\" % valid_word\n for k in xrange(top_k):\n close_word = reverse_dictionary[nearest[k]]\n log_str = \"%s %s,\" % (log_str, close_word)\n print(log_str)\n \n final_embeddings = normalized_embeddings.eval()",
"_____no_output_____"
],
[
"def plot_with_labels(low_dim_embs, labels, filename='tsne.png'):\n assert low_dim_embs.shape[0] >= len(labels), \"More labels than embeddings\"\n plt.figure(figsize=(18, 18)) # in inches\n for i, label in enumerate(labels):\n x, y = low_dim_embs[i, :]\n plt.scatter(x, y)\n plt.annotate(label,\n xy=(x, y),\n xytext=(5, 2),\n textcoords='offset points',\n ha='right',\n va='bottom')\n\n plt.savefig(filename)\n\n \nfrom sklearn.manifold import TSNE\nimport matplotlib.pyplot as plt\n\ntsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)\nplot_only = 500\nlow_dim_embs = tsne.fit_transform(final_embeddings[:plot_only, :])\nlabels = [reverse_dictionary[i] for i in xrange(plot_only)]\nplot_with_labels(low_dim_embs, labels) ",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e722bf083fd763433b8e620e7816aba9f522fa33 | 545,861 | ipynb | Jupyter Notebook | topic_modeling_with_LDA.ipynb | xei/topic-modeling-with-LDA | 5f8ed803f249a998d3e330c33dc58040e87c8412 | [
"MIT"
] | null | null | null | topic_modeling_with_LDA.ipynb | xei/topic-modeling-with-LDA | 5f8ed803f249a998d3e330c33dc58040e87c8412 | [
"MIT"
] | null | null | null | topic_modeling_with_LDA.ipynb | xei/topic-modeling-with-LDA | 5f8ed803f249a998d3e330c33dc58040e87c8412 | [
"MIT"
] | null | null | null | 148.979531 | 175,743 | 0.686719 | [
[
[
"<a href=\"https://colab.research.google.com/github/xei/topic-modeling-with-LDA/blob/main/topic_modeling_with_LDA.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"Copyright (c) 2021 Hamidreza Hosseinkhani ([xei](https://github.com/xei)) under the terms of the MIT license.\n\n[](https://colab.research.google.com/github/xei/topic-modeling-with-LDA/blob/main/topic_modeling_with_LDA.ipynb)\n\nGive a ⭐ if the notebook helped you!\n\n[](https://github.com/xei/topic-modeling-with-LDA/stargazers/)\n\nSome parts of this notebook are inspired by a similar work by [Selva Prabhakaran](https://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/).",
"_____no_output_____"
],
[
"# Download and install dependencies",
"_____no_output_____"
]
],
[
[
"!pip install --upgrade --quiet spacy\n!python -m spacy download en_core_web_sm\n# !pip install --upgrade --quiet contextualSpellCheck #0.4.1\n\n!pip install --upgrade --quiet gensim\n# Download Gensim's depricated model wrapper for MALLET's LDA model\n!mkdir gensimwrapper && wget https://raw.githubusercontent.com/RaRe-Technologies/gensim/e889fa3d45a406cabbc7e180fa9a8ee3f76ac6f0/gensim/models/wrappers/ldamallet.py -P gensimwrapper/\n!wget http://mallet.cs.umass.edu/dist/mallet-2.0.8.tar.gz -O - | tar zx\n\n!pip install --upgrade --quiet pyldavis",
"\u001b[K |████████████████████████████████| 5.8 MB 5.5 MB/s \n\u001b[K |████████████████████████████████| 10.1 MB 29.7 MB/s \n\u001b[K |████████████████████████████████| 42 kB 1.3 MB/s \n\u001b[K |████████████████████████████████| 623 kB 48.9 MB/s \n\u001b[K |████████████████████████████████| 456 kB 39.0 MB/s \n\u001b[?25hCollecting en-core-web-sm==3.1.0\n Downloading https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.1.0/en_core_web_sm-3.1.0-py3-none-any.whl (13.6 MB)\n\u001b[K |████████████████████████████████| 13.6 MB 77 kB/s \n\u001b[?25hRequirement already satisfied: spacy<3.2.0,>=3.1.0 in /usr/local/lib/python3.7/dist-packages (from en-core-web-sm==3.1.0) (3.1.2)\nRequirement already satisfied: pydantic!=1.8,!=1.8.1,<1.9.0,>=1.7.4 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (1.8.2)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (57.4.0)\nRequirement already satisfied: srsly<3.0.0,>=2.4.1 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (2.4.1)\nRequirement already satisfied: spacy-legacy<3.1.0,>=3.0.7 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (3.0.8)\nRequirement already satisfied: pathy>=0.3.5 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (0.6.0)\nRequirement already satisfied: catalogue<2.1.0,>=2.0.4 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (2.0.6)\nRequirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (1.0.5)\nRequirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (3.0.5)\nRequirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (2.11.3)\nRequirement already satisfied: typing-extensions<4.0.0.0,>=3.7.4 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (3.7.4.3)\nRequirement already satisfied: numpy>=1.15.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (1.19.5)\nRequirement already satisfied: tqdm<5.0.0,>=4.38.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (4.62.2)\nRequirement already satisfied: thinc<8.1.0,>=8.0.8 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (8.0.10)\nRequirement already satisfied: typer<0.4.0,>=0.3.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (0.3.2)\nRequirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (2.0.5)\nRequirement already satisfied: wasabi<1.1.0,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (0.8.2)\nRequirement already satisfied: requests<3.0.0,>=2.13.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (2.23.0)\nRequirement already satisfied: blis<0.8.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (0.4.1)\nRequirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (21.0)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from catalogue<2.1.0,>=2.0.4->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (3.5.0)\nRequirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging>=20.0->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (2.4.7)\nRequirement already satisfied: smart-open<6.0.0,>=5.0.0 in /usr/local/lib/python3.7/dist-packages (from pathy>=0.3.5->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (5.2.1)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.13.0->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (3.0.4)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.13.0->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (2021.5.30)\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<3.0.0,>=2.13.0->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (1.24.3)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.13.0->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (2.10)\nRequirement already satisfied: click<7.2.0,>=7.1.1 in /usr/local/lib/python3.7/dist-packages (from typer<0.4.0,>=0.3.0->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (7.1.2)\nRequirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->spacy<3.2.0,>=3.1.0->en-core-web-sm==3.1.0) (2.0.1)\nInstalling collected packages: en-core-web-sm\n Attempting uninstall: en-core-web-sm\n Found existing installation: en-core-web-sm 2.2.5\n Uninstalling en-core-web-sm-2.2.5:\n Successfully uninstalled en-core-web-sm-2.2.5\nSuccessfully installed en-core-web-sm-3.1.0\n\u001b[38;5;2m✔ Download and installation successful\u001b[0m\nYou can now load the package via spacy.load('en_core_web_sm')\n\u001b[K |████████████████████████████████| 24.1 MB 1.9 MB/s \n\u001b[?25h--2021-09-18 12:03:42-- https://raw.githubusercontent.com/RaRe-Technologies/gensim/e889fa3d45a406cabbc7e180fa9a8ee3f76ac6f0/gensim/models/wrappers/ldamallet.py\nResolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.111.133, 185.199.110.133, ...\nConnecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 23357 (23K) [text/plain]\nSaving to: ‘gensimwrapper/ldamallet.py’\n\nldamallet.py 100%[===================>] 22.81K --.-KB/s in 0.001s \n\n2021-09-18 12:03:43 (19.3 MB/s) - ‘gensimwrapper/ldamallet.py’ saved [23357/23357]\n\n--2021-09-18 12:03:43-- http://mallet.cs.umass.edu/dist/mallet-2.0.8.tar.gz\nResolving mallet.cs.umass.edu (mallet.cs.umass.edu)... 128.119.246.70\nConnecting to mallet.cs.umass.edu (mallet.cs.umass.edu)|128.119.246.70|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 14868234 (14M) [application/x-gzip]\nSaving to: ‘STDOUT’\n\n- 100%[===================>] 14.18M 9.33MB/s in 1.5s \n\n2021-09-18 12:03:44 (9.33 MB/s) - written to stdout [14868234/14868234]\n\n\u001b[K |████████████████████████████████| 1.7 MB 5.4 MB/s \n\u001b[?25h Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n Installing backend dependencies ... \u001b[?25l\u001b[?25hdone\n Preparing wheel metadata ... \u001b[?25l\u001b[?25hdone\n\u001b[K |████████████████████████████████| 15.7 MB 191 kB/s \n\u001b[K |████████████████████████████████| 11.3 MB 42.9 MB/s \n\u001b[?25h Building wheel for pyldavis (PEP 517) ... \u001b[?25l\u001b[?25hdone\n\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\ntensorflow 2.6.0 requires numpy~=1.19.2, but you have numpy 1.21.2 which is incompatible.\ngoogle-colab 1.0.0 requires pandas~=1.1.0; python_version >= \"3.0\", but you have pandas 1.3.3 which is incompatible.\ndatascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\nalbumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n"
],
[
"from typing import List, Tuple",
"_____no_output_____"
]
],
[
[
"# Load `20 Newsgroups` dataset into a Pandas DataFrame",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nfrom IPython.display import display",
"_____no_output_____"
],
[
"dataset_json_url = \\\n 'https://raw.githubusercontent.com/selva86/datasets/master/newsgroups.json'\ndataframe = pd.read_json(dataset_json_url)\n\ndisplay(dataframe)",
"_____no_output_____"
],
[
"target_topics_list = dataframe['target_names'].unique()\n\nprint(\n \"Unique Target Topics (%d):\\n%s\" % (len(target_topics_list),\n \" \".join(target_topics_list))\n)",
"Unique Target Topics (20):\nrec.autos comp.sys.mac.hardware comp.graphics sci.space talk.politics.guns sci.med comp.sys.ibm.pc.hardware comp.os.ms-windows.misc rec.motorcycles talk.religion.misc misc.forsale alt.atheism sci.electronics comp.windows.x rec.sport.hockey rec.sport.baseball soc.religion.christian talk.politics.mideast talk.politics.misc sci.crypt\n"
]
],
[
[
"# Shuffle and split the dataset",
"_____no_output_____"
]
],
[
[
"dataframe_shuffled = \\\n dataframe.sample(frac=1, random_state=42).reset_index(drop=True)",
"_____no_output_____"
]
],
[
[
"- 60% for `train set`\n- 20% for `validation set`\n- 20% for `test set`",
"_____no_output_____"
]
],
[
[
"trainset_portion = .6\nvalset_portion = .2\n\npivot_1 = int(trainset_portion * len(dataframe))\npivot_2 = int((trainset_portion + valset_portion) * len(dataframe))",
"_____no_output_____"
],
[
"import numpy as np",
"_____no_output_____"
],
[
"trainset_dataframe, valset_dataframe, testset_dataframe = \\\n np.split(dataframe_shuffled, [pivot_1, pivot_2])\n \n\nprint(\n \"trainset size: %d\" % trainset_dataframe.__len__()\n)\nprint(\n \"valset size: %d\" % valset_dataframe.__len__()\n)\nprint(\n \"testset size: %d\" % testset_dataframe.__len__()\n)",
"trainset size: 6788\nvalset size: 2263\ntestset size: 2263\n"
]
],
[
[
"# Make Corpora from the dataset",
"_____no_output_____"
]
],
[
[
"def make_corpus_from_dataframe(dataframe: pd.DataFrame) -> List[str]:\n return dataframe['content'].values.tolist()",
"_____no_output_____"
],
[
"%%time\n \ntrain_corpus_raw = make_corpus_from_dataframe(trainset_dataframe)\nval_corpus_raw = make_corpus_from_dataframe(valset_dataframe)\ntest_corpus_raw = make_corpus_from_dataframe(testset_dataframe)\n \nprint(train_corpus_raw[0])",
"From: [email protected] (Robert R. Novitskey)\nSubject: CYCLONE AND TEMPEST?????\nArticle-I.D.: usenet.1pskav$qtu\nReply-To: [email protected] (Robert R. Novitskey)\nOrganization: Case Western Reserve University, Cleveland, OH (USA)\nLines: 10\nNNTP-Posting-Host: thor.ins.cwru.edu\n\n\nCould someone please post any info on these systems.\n\nThanks.\nBoB\n-- \n---------------------------------------------------------------------- \nRobert Novitskey | \"Pursuing women is similar to banging one's head\[email protected] | against a wall...with less opportunity for reward\" \n---------------------------------------------------------------------- \n\nCPU times: user 2.36 ms, sys: 0 ns, total: 2.36 ms\nWall time: 2.29 ms\n"
]
],
[
[
"# Standardization\nStandardization refers to preprocessing the text, typically converts text to lowercase and remove punctuation or HTML elements to simplify the dataset.\n\nTo prevent `train/test skew` (also know as `train/serving skew`), it is important to preprocess the data identically at train and test time. To facilitate this, the `tensorflow.keras.layers.experimental.preprocessing.TextVectorization` layer can be included directly inside your model. These tasks can be accomplished with this layer:\n\n\n* Standardization (preprocessing): converts text to lowercase and strips punctuation. You have to write a custom standardization function to remove the HTML element.\n\n\n* Tokenization: splitting strings into tokens (for example, splitting a sentence into individual words, by splitting on whitespace).\n* Vectorization: converting tokens into numbers so they can be fed into a neural network.\n\n",
"_____no_output_____"
],
[
"## Lowercase the text",
"_____no_output_____"
]
],
[
[
"def lowercase(docs: List[str]) -> List[str]:\n return [doc.lower() for doc in docs ]",
"_____no_output_____"
],
[
"train_corpus_raw = lowercase(train_corpus_raw)\nval_corpus_raw = lowercase(val_corpus_raw)\ntest_corpus_raw = lowercase(test_corpus_raw)\n\nprint(train_corpus_raw[0])",
"from: [email protected] (robert r. novitskey)\nsubject: cyclone and tempest?????\narticle-i.d.: usenet.1pskav$qtu\nreply-to: [email protected] (robert r. novitskey)\norganization: case western reserve university, cleveland, oh (usa)\nlines: 10\nnntp-posting-host: thor.ins.cwru.edu\n\n\ncould someone please post any info on these systems.\n\nthanks.\nbob\n-- \n---------------------------------------------------------------------- \nrobert novitskey | \"pursuing women is similar to banging one's head\[email protected] | against a wall...with less opportunity for reward\" \n---------------------------------------------------------------------- \n\n"
]
],
[
[
"## Remove non-ASCII characters",
"_____no_output_____"
]
],
[
[
"def remove_non_ascii_chars(docs: List[str]) -> List[str]:\n \"\"\"\n https://en.wikipedia.org/wiki/List_of_Unicode_characters\n \"\"\"\n return [\n ''.join((char for char in doc if 0 < ord(char) < 127))\n for doc in docs\n ]",
"_____no_output_____"
],
[
"%%time\n \ntrain_corpus_raw = remove_non_ascii_chars(train_corpus_raw)\nval_corpus_raw = remove_non_ascii_chars(val_corpus_raw)\ntest_corpus_raw = remove_non_ascii_chars(test_corpus_raw)\n \nprint(train_corpus_raw[0])",
"from: [email protected] (robert r. novitskey)\nsubject: cyclone and tempest?????\narticle-i.d.: usenet.1pskav$qtu\nreply-to: [email protected] (robert r. novitskey)\norganization: case western reserve university, cleveland, oh (usa)\nlines: 10\nnntp-posting-host: thor.ins.cwru.edu\n\n\ncould someone please post any info on these systems.\n\nthanks.\nbob\n-- \n---------------------------------------------------------------------- \nrobert novitskey | \"pursuing women is similar to banging one's head\[email protected] | against a wall...with less opportunity for reward\" \n---------------------------------------------------------------------- \n\nCPU times: user 3.71 s, sys: 14.7 ms, total: 3.72 s\nWall time: 3.74 s\n"
]
],
[
[
"## Remove HTML Tags",
"_____no_output_____"
]
],
[
[
"import re",
"_____no_output_____"
],
[
"def remove_html_tags(docs: List[str]) -> List[str]:\n # return [re.sub('<.+?>', ' ', doc) for doc in docs]\n tmp_docs = [re.sub('<br />', ' ', doc) for doc in docs]\n tmp_docs = [re.sub('<br/>', ' ', doc) for doc in tmp_docs]\n tmp_docs = [re.sub('<br>', ' ', doc) for doc in tmp_docs]\n return tmp_docs",
"_____no_output_____"
],
[
"%%time\n \ntrain_corpus_raw = remove_html_tags(train_corpus_raw)\nval_corpus_raw = remove_html_tags(val_corpus_raw)\ntest_corpus_raw = remove_html_tags(test_corpus_raw)\n \nprint(train_corpus_raw[0])",
"from: [email protected] (robert r. novitskey)\nsubject: cyclone and tempest?????\narticle-i.d.: usenet.1pskav$qtu\nreply-to: [email protected] (robert r. novitskey)\norganization: case western reserve university, cleveland, oh (usa)\nlines: 10\nnntp-posting-host: thor.ins.cwru.edu\n\n\ncould someone please post any info on these systems.\n\nthanks.\nbob\n-- \n---------------------------------------------------------------------- \nrobert novitskey | \"pursuing women is similar to banging one's head\[email protected] | against a wall...with less opportunity for reward\" \n---------------------------------------------------------------------- \n\nCPU times: user 83.4 ms, sys: 2.93 ms, total: 86.4 ms\nWall time: 95.6 ms\n"
]
],
[
[
"## Replace common abbreviations",
"_____no_output_____"
]
],
[
[
"def replace_abbreviations_in_doc(doc: str) -> str:\n doc = re.sub(r'\\bthat\\'s\\b', 'that is', doc)\n doc = re.sub(r'\\bi\\'ve\\b', 'i have', doc)\n doc = re.sub(r'\\bi\\'m\\b', 'i am', doc)\n doc = re.sub(r'\\bit\\'s\\b', 'it is', doc)\n doc = re.sub(r'\\bya\\b', 'yeah', doc)\n doc = re.sub(r'\\bcan\\'t\\b', 'can not', doc)\n doc = re.sub(r'\\bcant\\b', 'can not', doc)\n doc = re.sub(r'\\bdon\\'t\\b', 'do not', doc)\n doc = re.sub(r'\\bdont\\b', 'do not', doc)\n doc = re.sub(r'\\bdidn\\'t\\b', 'did not', doc)\n doc = re.sub(r'\\bwon\\'t\\b', 'will not', doc)\n doc = re.sub(r'\\bwont\\b', 'will not', doc)\n doc = re.sub(r'\\bi\\'d\\b', 'i would', doc)\n doc = re.sub(r'wtf', 'what the fuck', doc)\n doc = re.sub(r'\\bwth\\b', 'what the hell', doc)\n # doc = re.sub(r'\\br\\b', 'are', doc)\n # doc = re.sub(r'\\bu\\b', 'you', doc)\n doc = re.sub(r'\\bo+k\\b', 'ok', doc)\n # doc = re.sub(r'\\bsux\\b', 'sucks', doc)\n doc = re.sub(r'\\bno+\\b', 'no', doc)\n doc = re.sub(r'\\bcoo+l\\b', 'cool', doc)\n return doc\n\ndef replace_abbreviations_in_corpus(docs: List[str]) -> List[str]:\n return [replace_abbreviations_in_doc(doc) for doc in docs]",
"_____no_output_____"
],
[
"%%time\n \ntrain_corpus_raw = replace_abbreviations_in_corpus(train_corpus_raw)\nval_corpus_raw = replace_abbreviations_in_corpus(val_corpus_raw)\ntest_corpus_raw = replace_abbreviations_in_corpus(test_corpus_raw)\n \nprint(train_corpus_raw[0])",
"from: [email protected] (robert r. novitskey)\nsubject: cyclone and tempest?????\narticle-i.d.: usenet.1pskav$qtu\nreply-to: [email protected] (robert r. novitskey)\norganization: case western reserve university, cleveland, oh (usa)\nlines: 10\nnntp-posting-host: thor.ins.cwru.edu\n\n\ncould someone please post any info on these systems.\n\nthanks.\nbob\n-- \n---------------------------------------------------------------------- \nrobert novitskey | \"pursuing women is similar to banging one's head\[email protected] | against a wall...with less opportunity for reward\" \n---------------------------------------------------------------------- \n\nCPU times: user 10.2 s, sys: 23 ms, total: 10.2 s\nWall time: 10.2 s\n"
]
],
[
[
"## Remove extra whitespaces",
"_____no_output_____"
]
],
[
[
"def remove_extra_whitespaces(docs: List[str]) -> List[str]:\n return [re.sub('\\s+', ' ', doc).strip() for doc in docs]",
"_____no_output_____"
],
[
"%%time\n \ntrain_corpus_raw = remove_extra_whitespaces(train_corpus_raw)\nval_corpus_raw = remove_extra_whitespaces(val_corpus_raw)\ntest_corpus_raw = remove_extra_whitespaces(test_corpus_raw)\n \nprint(train_corpus_raw[0])",
"from: [email protected] (robert r. novitskey) subject: cyclone and tempest????? article-i.d.: usenet.1pskav$qtu reply-to: [email protected] (robert r. novitskey) organization: case western reserve university, cleveland, oh (usa) lines: 10 nntp-posting-host: thor.ins.cwru.edu could someone please post any info on these systems. thanks. bob -- ---------------------------------------------------------------------- robert novitskey | \"pursuing women is similar to banging one's head [email protected] | against a wall...with less opportunity for reward\" ----------------------------------------------------------------------\nCPU times: user 1.05 s, sys: 3.56 ms, total: 1.06 s\nWall time: 1.07 s\n"
]
],
[
[
"# Spell correction and making `n-gram` phrases",
"_____no_output_____"
]
],
[
[
"import spacy\n# import contextualSpellCheck\n\nimport gensim",
"_____no_output_____"
],
[
"spacy_nlp = spacy.load(\n 'en_core_web_sm',\n # disable extra componens for efficiency\n disable=['parser', 'ner']\n)",
"_____no_output_____"
],
[
"from pprint import pprint",
"_____no_output_____"
],
[
"print(train_corpus_raw[0])\n\nprint('\\n', (\"ORIGINAL TOKEN\".center(20),\n \"TOKEN LEMMA\".center(20),\n \"POS\".center(10),\n \"STOP WORD\".center(11)))\nprint('', (\"-\"*20, \"-\"*20, \"-\"*10, \"-\"*11))\n\npprint(\n [\n (\n token.text.center(20),\n token.lemma_.center(20),\n token.pos_.center(10),\n str(token.is_stop).center(10)\n ) for token in spacy_nlp(train_corpus_raw[0])\n ]\n)",
"from: [email protected] (robert r. novitskey) subject: cyclone and tempest????? article-i.d.: usenet.1pskav$qtu reply-to: [email protected] (robert r. novitskey) organization: case western reserve university, cleveland, oh (usa) lines: 10 nntp-posting-host: thor.ins.cwru.edu could someone please post any info on these systems. thanks. bob -- ---------------------------------------------------------------------- robert novitskey | \"pursuing women is similar to banging one's head [email protected] | against a wall...with less opportunity for reward\" ----------------------------------------------------------------------\n\n (' ORIGINAL TOKEN ', ' TOKEN LEMMA ', ' POS ', ' STOP WORD ')\n ('--------------------', '--------------------', '----------', '-----------')\n[(' from ', ' from ', ' ADP ', ' True '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' [email protected] ', ' [email protected] ', ' PROPN ', ' False '),\n (' ( ', ' ( ', ' PUNCT ', ' False '),\n (' robert ', ' robert ', ' PROPN ', ' False '),\n (' r. ', ' r. ', ' PROPN ', ' False '),\n (' novitskey ', ' novitskey ', ' PROPN ', ' False '),\n (' ) ', ' ) ', ' PUNCT ', ' False '),\n (' subject ', ' subject ', ' NOUN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' cyclone ', ' cyclone ', ' NOUN ', ' False '),\n (' and ', ' and ', ' CCONJ ', ' True '),\n (' tempest ', ' temp ', ' ADJ ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' article ', ' article ', ' NOUN ', ' False '),\n (' - ', ' - ', ' PUNCT ', ' False '),\n (' i.d ', ' i.d ', ' PROPN ', ' False '),\n (' . ', ' . ', ' PROPN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' usenet.1pskav$qtu ', ' usenet.1pskav$qtu ', ' NUM ', ' False '),\n (' reply ', ' reply ', ' NOUN ', ' False '),\n (' - ', ' - ', ' PUNCT ', ' False '),\n (' to ', ' to ', ' ADP ', ' True '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' [email protected] ', ' [email protected] ', ' PROPN ', ' False '),\n (' ( ', ' ( ', ' PUNCT ', ' False '),\n (' robert ', ' robert ', ' PROPN ', ' False '),\n (' r. ', ' r. ', ' PROPN ', ' False '),\n (' novitskey ', ' novitskey ', ' PROPN ', ' False '),\n (' ) ', ' ) ', ' PUNCT ', ' False '),\n (' organization ', ' organization ', ' NOUN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' case ', ' case ', ' NOUN ', ' False '),\n (' western ', ' western ', ' PROPN ', ' False '),\n (' reserve ', ' reserve ', ' PROPN ', ' False '),\n (' university ', ' university ', ' PROPN ', ' False '),\n (' , ', ' , ', ' PUNCT ', ' False '),\n (' cleveland ', ' cleveland ', ' PROPN ', ' False '),\n (' , ', ' , ', ' PUNCT ', ' False '),\n (' oh ', ' oh ', ' INTJ ', ' False '),\n (' ( ', ' ( ', ' PUNCT ', ' False '),\n (' usa ', ' usa ', ' PROPN ', ' False '),\n (' ) ', ' ) ', ' PUNCT ', ' False '),\n (' lines ', ' line ', ' NOUN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' 10 ', ' 10 ', ' NUM ', ' False '),\n (' nntp ', ' nntp ', ' NOUN ', ' False '),\n (' - ', ' - ', ' PUNCT ', ' False '),\n (' posting ', ' post ', ' VERB ', ' False '),\n (' - ', ' - ', ' PUNCT ', ' False '),\n (' host ', ' host ', ' NOUN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' thor.ins.cwru.edu ', ' thor.ins.cwru.edu ', ' PROPN ', ' False '),\n (' could ', ' could ', ' AUX ', ' True '),\n (' someone ', ' someone ', ' PRON ', ' True '),\n (' please ', ' please ', ' INTJ ', ' True '),\n (' post ', ' post ', ' VERB ', ' False '),\n (' any ', ' any ', ' DET ', ' True '),\n (' info ', ' info ', ' NOUN ', ' False '),\n (' on ', ' on ', ' ADP ', ' True '),\n (' these ', ' these ', ' DET ', ' True '),\n (' systems ', ' system ', ' NOUN ', ' False '),\n (' . ', ' . ', ' PUNCT ', ' False '),\n (' thanks ', ' thank ', ' NOUN ', ' False '),\n (' . ', ' . ', ' PUNCT ', ' False '),\n (' bob ', ' bob ', ' PROPN ', ' False '),\n (' -- ', ' -- ', ' PUNCT ', ' False '),\n ('----------------------------------------------------------------------',\n '----------------------------------------------------------------------',\n ' PUNCT ',\n ' False '),\n (' robert ', ' robert ', ' PROPN ', ' False '),\n (' novitskey ', ' novitskey ', ' PROPN ', ' False '),\n (' | ', ' | ', ' ADV ', ' False '),\n (' \" ', ' \" ', ' PUNCT ', ' False '),\n (' pursuing ', ' pursue ', ' VERB ', ' False '),\n (' women ', ' woman ', ' NOUN ', ' False '),\n (' is ', ' be ', ' VERB ', ' True '),\n (' similar ', ' similar ', ' ADJ ', ' False '),\n (' to ', ' to ', ' ADP ', ' True '),\n (' banging ', ' bang ', ' VERB ', ' False '),\n (' one ', ' one ', ' PRON ', ' True '),\n (\" 's \", \" 's \", ' PART ', ' True '),\n (' head ', ' head ', ' NOUN ', ' False '),\n (' [email protected] ', ' [email protected] ', ' VERB ', ' False '),\n (' | ', ' | ', ' ADV ', ' False '),\n (' against ', ' against ', ' ADP ', ' True '),\n (' a ', ' a ', ' DET ', ' True '),\n (' wall ', ' wall ', ' NOUN ', ' False '),\n (' ... ', ' ... ', ' PUNCT ', ' False '),\n (' with ', ' with ', ' ADP ', ' True '),\n (' less ', ' less ', ' ADJ ', ' True '),\n (' opportunity ', ' opportunity ', ' NOUN ', ' False '),\n (' for ', ' for ', ' ADP ', ' True '),\n (' reward ', ' reward ', ' NOUN ', ' False '),\n (' \" ', ' \" ', ' PUNCT ', ' False '),\n ('----------------------------------------------------------------------',\n '----------------------------------------------------------------------',\n ' PUNCT ',\n ' False ')]\n"
]
],
[
[
"## Spell Correction",
"_____no_output_____"
]
],
[
[
"# add contextual spell correction using BERT to Spacy pipeline\n# https://spacy.io/universe/project/contextualSpellCheck\n# spacy_nlp.add_pipe('sentencizer')\n# contextualSpellCheck.add_to_pipe(spacy_nlp)\n# ValueError: [E030] Sentence boundaries unset. You can add the 'sentencizer' component to the pipeline with: `nlp.add_pipe('sentencizer')`. Alternatively, add the dependency parser or sentence recognizer, or set sentence boundaries by setting `doc[i].is_sent_start`.",
"_____no_output_____"
],
[
"# train_corpus_spacy = [doc._.outcome_spellCheck for doc in train_corpus_spacy]",
"_____no_output_____"
]
],
[
[
"## Make n-gram (unigram, bigram and trigram) corpus",
"_____no_output_____"
]
],
[
[
"def make_unigram(docs_raw: List[str]) -> List[List[str]]:\n \"\"\"\n Tokenizes the corpus\n \"\"\"\n return [\n [token.text for token in spacy_nlp(doc)]\n for doc in docs_raw\n ]\n\n\ndef make_bigram(unigram_docs: List[List[str]]) -> List[List[str]]:\n bigram_phraser_model = gensim.models.phrases.Phraser(\n gensim.models.Phrases(\n unigram_docs,\n # ignore all phrases with total collected count lower than `min_count`\n min_count=5,\n # the min score (based on `scoring` function) for forming the phrases\n # higher value means fewer phrases\n threshold=100,\n # https://radimrehurek.com/gensim/models/phrases.html#gensim.models.phrases.original_scorer\n # scoring='npmi',\n # connector_words=gensim.models.phrases.ENGLISH_CONNECTOR_WORDS\n )\n )\n \n return bigram_phraser_model[unigram_docs]\n \n \ndef make_trigram(bigram_docs: List[List[str]]) -> List[List[str]]:\n trigram_phraser_model = gensim.models.phrases.Phraser(\n gensim.models.Phrases(\n bigram_docs,\n threshold=100\n )\n )\n \n return trigram_phraser_model[bigram_docs]",
"_____no_output_____"
],
[
"%%time\n\ntrain_corpus_unigram = make_unigram(train_corpus_raw)\nval_corpus_unigram = make_unigram(val_corpus_raw)\ntest_corpus_unigram = make_unigram(test_corpus_raw)\n\ntrain_corpus_bigram = make_bigram(train_corpus_unigram)\nval_corpus_bigram = make_bigram(val_corpus_unigram)\ntest_corpus_bigram = make_bigram(test_corpus_unigram)\n\ntrain_corpus_trigram = make_trigram(train_corpus_bigram)\nval_corpus_trigram = make_trigram(val_corpus_bigram)\ntest_corpus_trigram = make_trigram(test_corpus_bigram)\n\n\nprint(\"Unigram Corpus:\\n{}\".format(train_corpus_unigram[0]))\nprint(\"Bigram Corpus:\\n{}\".format(train_corpus_bigram[0]))\nprint(\"Trigram Corpus:\\n{}\".format(train_corpus_trigram[0]))",
"Unigram Corpus:\n['from', ':', '[email protected]', '(', 'robert', 'r.', 'novitskey', ')', 'subject', ':', 'cyclone', 'and', 'tempest', '?', '?', '?', '?', '?', 'article', '-', 'i.d', '.', ':', 'usenet.1pskav$qtu', 'reply', '-', 'to', ':', '[email protected]', '(', 'robert', 'r.', 'novitskey', ')', 'organization', ':', 'case', 'western', 'reserve', 'university', ',', 'cleveland', ',', 'oh', '(', 'usa', ')', 'lines', ':', '10', 'nntp', '-', 'posting', '-', 'host', ':', 'thor.ins.cwru.edu', 'could', 'someone', 'please', 'post', 'any', 'info', 'on', 'these', 'systems', '.', 'thanks', '.', 'bob', '--', '----------------------------------------------------------------------', 'robert', 'novitskey', '|', '\"', 'pursuing', 'women', 'is', 'similar', 'to', 'banging', 'one', \"'s\", 'head', '[email protected]', '|', 'against', 'a', 'wall', '...', 'with', 'less', 'opportunity', 'for', 'reward', '\"', '----------------------------------------------------------------------']\nBigram Corpus:\n['from', ':', '[email protected]', '(', 'robert', 'r._novitskey', ')', 'subject', ':', 'cyclone', 'and', 'tempest', '?', '?', '?', '?', '?', 'article', '-', 'i.d', '.', ':', 'usenet.1pskav$qtu', 'reply', '-', 'to', ':', '[email protected]', '(', 'robert', 'r._novitskey', ')', 'organization', ':', 'case_western', 'reserve_university', ',', 'cleveland', ',', 'oh', '(', 'usa', ')', 'lines', ':', '10', 'nntp', '-', 'posting', '-', 'host', ':', 'thor.ins.cwru.edu', 'could', 'someone', 'please', 'post', 'any', 'info', 'on', 'these', 'systems', '.', 'thanks', '.', 'bob', '--', '----------------------------------------------------------------------', 'robert', 'novitskey', '|', '\"', 'pursuing', 'women', 'is', 'similar', 'to', 'banging', 'one', \"'s\", 'head', '[email protected]', '|', 'against', 'a', 'wall', '...', 'with', 'less', 'opportunity', 'for', 'reward', '\"', '----------------------------------------------------------------------']\nTrigram Corpus:\n['from', ':', '[email protected]', '(', 'robert_r._novitskey', ')', 'subject', ':', 'cyclone', 'and', 'tempest', '?', '?', '?', '?', '?', 'article', '-', 'i.d', '.', ':', 'usenet.1pskav$qtu', 'reply', '-', 'to', ':', '[email protected]', '(', 'robert_r._novitskey', ')', 'organization', ':', 'case_western', 'reserve_university', ',', 'cleveland', ',', 'oh', '(', 'usa', ')', 'lines', ':', '10', 'nntp', '-', 'posting', '-', 'host', ':', 'thor.ins.cwru.edu', 'could', 'someone', 'please', 'post', 'any', 'info', 'on', 'these', 'systems', '.', 'thanks', '.', 'bob', '--', '----------------------------------------------------------------------', 'robert', 'novitskey', '|', '\"', 'pursuing', 'women', 'is', 'similar', 'to', 'banging', 'one', \"'s\", 'head', '[email protected]', '|', 'against', 'a', 'wall', '...', 'with', 'less', 'opportunity', 'for', 'reward', '\"', '----------------------------------------------------------------------']\nCPU times: user 5min 5s, sys: 5.51 s, total: 5min 10s\nWall time: 5min 10s\n"
]
],
[
[
"Here we found `n-gram` phrases like `belt_clip`, `fm_transmitter`, `mp3_player`, `screen_protector` and `poorly_designed` (bound using `_`).\n\nNow we are going to replace the corresponding words in the corpora with these phrases.",
"_____no_output_____"
]
],
[
[
"def bind_phrases(docs_ngram: List[List[str]], docs_raw: List[str]) -> List[str]:\n docs_raw_phrased: List[str] = []\n for idx, doc_ngram in enumerate(docs_ngram):\n docs_raw_phrased.append(docs_raw[idx])\n for phrase in doc_ngram:\n if (\n (phrase.count('_') == 1 and len(phrase) > 1) or\n (phrase.count('_') == 2 and len(phrase) > 2)\n ):\n docs_raw_phrased[idx] = docs_raw_phrased[idx].replace(\n phrase.replace(\"_\", \" \"),\n phrase\n )\n \n return docs_raw_phrased",
"_____no_output_____"
],
[
"%%time\n\ntrain_corpus_phrased = bind_phrases(train_corpus_trigram, train_corpus_raw)\nval_corpus_phrased = bind_phrases(val_corpus_trigram, val_corpus_raw)\ntest_corpus_phrased = bind_phrases(test_corpus_trigram, test_corpus_raw)\n\npprint(train_corpus_phrased[0])",
"('from: [email protected] (robert_r._novitskey) subject: cyclone and '\n 'tempest????? article-i.d.: usenet.1pskav$qtu reply-to: [email protected] '\n '(robert_r._novitskey) organization: case_western reserve_university, '\n 'cleveland, oh (usa) lines: 10 nntp-posting-host: thor.ins.cwru.edu could '\n 'someone please post any info on these systems. thanks. bob -- '\n '---------------------------------------------------------------------- '\n 'robert novitskey | \"pursuing women is similar to banging one\\'s head '\n '[email protected] | against a wall...with less opportunity for reward\" '\n '----------------------------------------------------------------------')\nCPU times: user 12.1 s, sys: 30.7 ms, total: 12.1 s\nWall time: 12.1 s\n"
],
[
"pprint(train_corpus_phrased[0])\n\nprint('\\n', (\"ORIGINAL TOKEN\".center(20),\n \"TOKEN LEMMA\".center(20),\n \"POS\".center(10),\n \"STOP WORD\".center(11)))\nprint('', (\"-\"*20, \"-\"*20, \"-\"*10, \"-\"*11))\n\npprint(\n [\n (\n token.text.center(20),\n token.lemma_.center(20),\n token.pos_.center(10),\n str(token.is_stop).center(10)\n ) for token in spacy_nlp(train_corpus_phrased[0])\n ]\n)",
"('from: [email protected] (robert_r._novitskey) subject: cyclone and '\n 'tempest????? article-i.d.: usenet.1pskav$qtu reply-to: [email protected] '\n '(robert_r._novitskey) organization: case_western reserve_university, '\n 'cleveland, oh (usa) lines: 10 nntp-posting-host: thor.ins.cwru.edu could '\n 'someone please post any info on these systems. thanks. bob -- '\n '---------------------------------------------------------------------- '\n 'robert novitskey | \"pursuing women is similar to banging one\\'s head '\n '[email protected] | against a wall...with less opportunity for reward\" '\n '----------------------------------------------------------------------')\n\n (' ORIGINAL TOKEN ', ' TOKEN LEMMA ', ' POS ', ' STOP WORD ')\n ('--------------------', '--------------------', '----------', '-----------')\n[(' from ', ' from ', ' ADP ', ' True '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' [email protected] ', ' [email protected] ', ' PROPN ', ' False '),\n (' ( ', ' ( ', ' PUNCT ', ' False '),\n ('robert_r._novitskey ', 'robert_r._novitskey ', ' NOUN ', ' False '),\n (' ) ', ' ) ', ' PUNCT ', ' False '),\n (' subject ', ' subject ', ' NOUN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' cyclone ', ' cyclone ', ' NOUN ', ' False '),\n (' and ', ' and ', ' CCONJ ', ' True '),\n (' tempest ', ' temp ', ' ADJ ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' article ', ' article ', ' NOUN ', ' False '),\n (' - ', ' - ', ' PUNCT ', ' False '),\n (' i.d ', ' i.d ', ' PROPN ', ' False '),\n (' . ', ' . ', ' PROPN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' usenet.1pskav$qtu ', ' usenet.1pskav$qtu ', ' NUM ', ' False '),\n (' reply ', ' reply ', ' NOUN ', ' False '),\n (' - ', ' - ', ' PUNCT ', ' False '),\n (' to ', ' to ', ' ADP ', ' True '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' [email protected] ', ' [email protected] ', ' PROPN ', ' False '),\n (' ( ', ' ( ', ' PUNCT ', ' False '),\n ('robert_r._novitskey ', 'robert_r._novitskey ', ' NOUN ', ' False '),\n (' ) ', ' ) ', ' PUNCT ', ' False '),\n (' organization ', ' organization ', ' NOUN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' case_western ', ' case_western ', ' NOUN ', ' False '),\n (' reserve_university ', ' reserve_university ', ' NOUN ', ' False '),\n (' , ', ' , ', ' PUNCT ', ' False '),\n (' cleveland ', ' cleveland ', ' NOUN ', ' False '),\n (' , ', ' , ', ' PUNCT ', ' False '),\n (' oh ', ' oh ', ' INTJ ', ' False '),\n (' ( ', ' ( ', ' PUNCT ', ' False '),\n (' usa ', ' usa ', ' PROPN ', ' False '),\n (' ) ', ' ) ', ' PUNCT ', ' False '),\n (' lines ', ' line ', ' NOUN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' 10 ', ' 10 ', ' NUM ', ' False '),\n (' nntp ', ' nntp ', ' NOUN ', ' False '),\n (' - ', ' - ', ' PUNCT ', ' False '),\n (' posting ', ' post ', ' VERB ', ' False '),\n (' - ', ' - ', ' PUNCT ', ' False '),\n (' host ', ' host ', ' NOUN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' thor.ins.cwru.edu ', ' thor.ins.cwru.edu ', ' PROPN ', ' False '),\n (' could ', ' could ', ' AUX ', ' True '),\n (' someone ', ' someone ', ' PRON ', ' True '),\n (' please ', ' please ', ' INTJ ', ' True '),\n (' post ', ' post ', ' VERB ', ' False '),\n (' any ', ' any ', ' DET ', ' True '),\n (' info ', ' info ', ' NOUN ', ' False '),\n (' on ', ' on ', ' ADP ', ' True '),\n (' these ', ' these ', ' DET ', ' True '),\n (' systems ', ' system ', ' NOUN ', ' False '),\n (' . ', ' . ', ' PUNCT ', ' False '),\n (' thanks ', ' thank ', ' NOUN ', ' False '),\n (' . ', ' . ', ' PUNCT ', ' False '),\n (' bob ', ' bob ', ' PROPN ', ' False '),\n (' -- ', ' -- ', ' PUNCT ', ' False '),\n ('----------------------------------------------------------------------',\n '----------------------------------------------------------------------',\n ' PUNCT ',\n ' False '),\n (' robert ', ' robert ', ' PROPN ', ' False '),\n (' novitskey ', ' novitskey ', ' PROPN ', ' False '),\n (' | ', ' | ', ' ADV ', ' False '),\n (' \" ', ' \" ', ' PUNCT ', ' False '),\n (' pursuing ', ' pursue ', ' VERB ', ' False '),\n (' women ', ' woman ', ' NOUN ', ' False '),\n (' is ', ' be ', ' VERB ', ' True '),\n (' similar ', ' similar ', ' ADJ ', ' False '),\n (' to ', ' to ', ' ADP ', ' True '),\n (' banging ', ' bang ', ' VERB ', ' False '),\n (' one ', ' one ', ' PRON ', ' True '),\n (\" 's \", \" 's \", ' PART ', ' True '),\n (' head ', ' head ', ' NOUN ', ' False '),\n (' [email protected] ', ' [email protected] ', ' VERB ', ' False '),\n (' | ', ' | ', ' ADV ', ' False '),\n (' against ', ' against ', ' ADP ', ' True '),\n (' a ', ' a ', ' DET ', ' True '),\n (' wall ', ' wall ', ' NOUN ', ' False '),\n (' ... ', ' ... ', ' PUNCT ', ' False '),\n (' with ', ' with ', ' ADP ', ' True '),\n (' less ', ' less ', ' ADJ ', ' True '),\n (' opportunity ', ' opportunity ', ' NOUN ', ' False '),\n (' for ', ' for ', ' ADP ', ' True '),\n (' reward ', ' reward ', ' NOUN ', ' False '),\n (' \" ', ' \" ', ' PUNCT ', ' False '),\n ('----------------------------------------------------------------------',\n '----------------------------------------------------------------------',\n ' PUNCT ',\n ' False ')]\n"
]
],
[
[
"# Tokenization and lemmatization\nRemove too short and too long tokens, punctuations and unrelevant POSs, stop words, emails, urls.\n\n`Lemmatization` is a smarter version of `stemming`, taking word context into account.",
"_____no_output_____"
]
],
[
[
"domain_stop_words = {'from', 'subject', 're', 'reply'}",
"_____no_output_____"
],
[
"def lemmatize(docs: List[str]) -> List[List[str]]:\n return [\n [\n token.lemma_\n for token in spacy_nlp(doc)\n if (\n 1 < len(token.lemma_) < 20 and\n token.pos_ in {'ADJ', 'ADV', 'NOUN', 'PROPN', 'VERB'} and\n not token.is_stop and # spacy.lang.en.STOP_WORDS\n not token.lower_ in domain_stop_words and\n not token.like_url and\n not token.like_email\n )\n ]\n for doc in docs\n ]",
"_____no_output_____"
],
[
"%%time\n\ntrain_corpus_preprocessed = lemmatize(train_corpus_phrased)\nval_corpus_preprocessed = lemmatize(val_corpus_phrased)\ntest_corpus_preprocessed = lemmatize(test_corpus_phrased)\n \nprint(train_corpus_preprocessed[0])",
"['robert_r._novitskey', 'cyclone', 'temp', 'article', 'i.d', 'robert_r._novitskey', 'organization', 'case_western', 'reserve_university', 'cleveland', 'usa', 'line', 'nntp', 'post', 'host', 'post', 'info', 'system', 'thank', 'bob', 'robert', 'novitskey', 'pursue', 'woman', 'similar', 'bang', 'head', 'wall', 'opportunity', 'reward']\nCPU times: user 4min 16s, sys: 5.66 s, total: 4min 22s\nWall time: 4min 21s\n"
],
[
"pprint(train_corpus_phrased[0])\n\nprint('\\n', (\"ORIGINAL TOKEN\".center(20),\n \"TOKEN LEMMA\".center(20),\n \"POS\".center(10),\n \"STOP WORD\".center(11)))\nprint('', (\"-\"*20, \"-\"*20, \"-\"*10, \"-\"*11))\n\npprint(\n [\n (\n token.text.center(20),\n token.lemma_.center(20),\n token.pos_.center(10),\n str(token.is_stop).center(10)\n ) for token in spacy_nlp(train_corpus_phrased[0])\n ]\n)",
"('from: [email protected] (robert_r._novitskey) subject: cyclone and '\n 'tempest????? article-i.d.: usenet.1pskav$qtu reply-to: [email protected] '\n '(robert_r._novitskey) organization: case_western reserve_university, '\n 'cleveland, oh (usa) lines: 10 nntp-posting-host: thor.ins.cwru.edu could '\n 'someone please post any info on these systems. thanks. bob -- '\n '---------------------------------------------------------------------- '\n 'robert novitskey | \"pursuing women is similar to banging one\\'s head '\n '[email protected] | against a wall...with less opportunity for reward\" '\n '----------------------------------------------------------------------')\n\n (' ORIGINAL TOKEN ', ' TOKEN LEMMA ', ' POS ', ' STOP WORD ')\n ('--------------------', '--------------------', '----------', '-----------')\n[(' from ', ' from ', ' ADP ', ' True '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' [email protected] ', ' [email protected] ', ' PROPN ', ' False '),\n (' ( ', ' ( ', ' PUNCT ', ' False '),\n ('robert_r._novitskey ', 'robert_r._novitskey ', ' NOUN ', ' False '),\n (' ) ', ' ) ', ' PUNCT ', ' False '),\n (' subject ', ' subject ', ' NOUN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' cyclone ', ' cyclone ', ' NOUN ', ' False '),\n (' and ', ' and ', ' CCONJ ', ' True '),\n (' tempest ', ' temp ', ' ADJ ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' ? ', ' ? ', ' PUNCT ', ' False '),\n (' article ', ' article ', ' NOUN ', ' False '),\n (' - ', ' - ', ' PUNCT ', ' False '),\n (' i.d ', ' i.d ', ' PROPN ', ' False '),\n (' . ', ' . ', ' PROPN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' usenet.1pskav$qtu ', ' usenet.1pskav$qtu ', ' NUM ', ' False '),\n (' reply ', ' reply ', ' NOUN ', ' False '),\n (' - ', ' - ', ' PUNCT ', ' False '),\n (' to ', ' to ', ' ADP ', ' True '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' [email protected] ', ' [email protected] ', ' PROPN ', ' False '),\n (' ( ', ' ( ', ' PUNCT ', ' False '),\n ('robert_r._novitskey ', 'robert_r._novitskey ', ' NOUN ', ' False '),\n (' ) ', ' ) ', ' PUNCT ', ' False '),\n (' organization ', ' organization ', ' NOUN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' case_western ', ' case_western ', ' NOUN ', ' False '),\n (' reserve_university ', ' reserve_university ', ' NOUN ', ' False '),\n (' , ', ' , ', ' PUNCT ', ' False '),\n (' cleveland ', ' cleveland ', ' NOUN ', ' False '),\n (' , ', ' , ', ' PUNCT ', ' False '),\n (' oh ', ' oh ', ' INTJ ', ' False '),\n (' ( ', ' ( ', ' PUNCT ', ' False '),\n (' usa ', ' usa ', ' PROPN ', ' False '),\n (' ) ', ' ) ', ' PUNCT ', ' False '),\n (' lines ', ' line ', ' NOUN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' 10 ', ' 10 ', ' NUM ', ' False '),\n (' nntp ', ' nntp ', ' NOUN ', ' False '),\n (' - ', ' - ', ' PUNCT ', ' False '),\n (' posting ', ' post ', ' VERB ', ' False '),\n (' - ', ' - ', ' PUNCT ', ' False '),\n (' host ', ' host ', ' NOUN ', ' False '),\n (' : ', ' : ', ' PUNCT ', ' False '),\n (' thor.ins.cwru.edu ', ' thor.ins.cwru.edu ', ' PROPN ', ' False '),\n (' could ', ' could ', ' AUX ', ' True '),\n (' someone ', ' someone ', ' PRON ', ' True '),\n (' please ', ' please ', ' INTJ ', ' True '),\n (' post ', ' post ', ' VERB ', ' False '),\n (' any ', ' any ', ' DET ', ' True '),\n (' info ', ' info ', ' NOUN ', ' False '),\n (' on ', ' on ', ' ADP ', ' True '),\n (' these ', ' these ', ' DET ', ' True '),\n (' systems ', ' system ', ' NOUN ', ' False '),\n (' . ', ' . ', ' PUNCT ', ' False '),\n (' thanks ', ' thank ', ' NOUN ', ' False '),\n (' . ', ' . ', ' PUNCT ', ' False '),\n (' bob ', ' bob ', ' PROPN ', ' False '),\n (' -- ', ' -- ', ' PUNCT ', ' False '),\n ('----------------------------------------------------------------------',\n '----------------------------------------------------------------------',\n ' PUNCT ',\n ' False '),\n (' robert ', ' robert ', ' PROPN ', ' False '),\n (' novitskey ', ' novitskey ', ' PROPN ', ' False '),\n (' | ', ' | ', ' ADV ', ' False '),\n (' \" ', ' \" ', ' PUNCT ', ' False '),\n (' pursuing ', ' pursue ', ' VERB ', ' False '),\n (' women ', ' woman ', ' NOUN ', ' False '),\n (' is ', ' be ', ' VERB ', ' True '),\n (' similar ', ' similar ', ' ADJ ', ' False '),\n (' to ', ' to ', ' ADP ', ' True '),\n (' banging ', ' bang ', ' VERB ', ' False '),\n (' one ', ' one ', ' PRON ', ' True '),\n (\" 's \", \" 's \", ' PART ', ' True '),\n (' head ', ' head ', ' NOUN ', ' False '),\n (' [email protected] ', ' [email protected] ', ' VERB ', ' False '),\n (' | ', ' | ', ' ADV ', ' False '),\n (' against ', ' against ', ' ADP ', ' True '),\n (' a ', ' a ', ' DET ', ' True '),\n (' wall ', ' wall ', ' NOUN ', ' False '),\n (' ... ', ' ... ', ' PUNCT ', ' False '),\n (' with ', ' with ', ' ADP ', ' True '),\n (' less ', ' less ', ' ADJ ', ' True '),\n (' opportunity ', ' opportunity ', ' NOUN ', ' False '),\n (' for ', ' for ', ' ADP ', ' True '),\n (' reward ', ' reward ', ' NOUN ', ' False '),\n (' \" ', ' \" ', ' PUNCT ', ' False '),\n ('----------------------------------------------------------------------',\n '----------------------------------------------------------------------',\n ' PUNCT ',\n ' False ')]\n"
]
],
[
[
"# Build the dictionary",
"_____no_output_____"
]
],
[
[
"dictionary = gensim.corpora.Dictionary(train_corpus_preprocessed)\n# dictionary.filter_extremes(no_below=15, no_above=0.5, keep_n=100_000)\n \n# Save the dictionary as a file for later use\ndictionary.save('dictionary.dict')",
"_____no_output_____"
]
],
[
[
"# Represent documents as a `bag of words`\nEach document will be represented by a list of tuples: `(term_id -> in_doc_term_frequency)`",
"_____no_output_____"
]
],
[
[
"def make_bow_corpus(\n preprocessed_docs: List[List[str]]\n) -> List[List[Tuple[int, int]]]:\n return [dictionary.doc2bow(doc) for doc in preprocessed_docs]",
"_____no_output_____"
],
[
"train_corpus_bow = make_bow_corpus(train_corpus_preprocessed)\nval_corpus_bow = make_bow_corpus(val_corpus_preprocessed)\ntest_corpus_bow = make_bow_corpus(test_corpus_preprocessed)\n \n# Save the BOW corpora as files for later use\ngensim.corpora.MmCorpus.serialize('corpus_train.mm', train_corpus_bow)\ngensim.corpora.MmCorpus.serialize('corpus_val.mm', val_corpus_bow)\ngensim.corpora.MmCorpus.serialize('corpus_test.mm', test_corpus_bow)\n \n \nprint('',\n (\"TERM ID\".center(8), \"TERM\".center(20), \"IN-DOC FREQUENCY\".center(18)))\nprint('', (\"-\"*8, \"-\"*20, \"-\"*18))\npprint(\n [\n (\n str(token[0]).center(8),\n dictionary[token[0]].center(20),\n str(token[1]).center(18)\n )\n for token in train_corpus_bow[0]\n ]\n)",
" ('TERM ID ', ' TERM ', ' IN-DOC FREQUENCY ')\n ('--------', '--------------------', '------------------')\n[(' 0 ', ' article ', ' 1 '),\n (' 1 ', ' bang ', ' 1 '),\n (' 2 ', ' bob ', ' 1 '),\n (' 3 ', ' case_western ', ' 1 '),\n (' 4 ', ' cleveland ', ' 1 '),\n (' 5 ', ' cyclone ', ' 1 '),\n (' 6 ', ' head ', ' 1 '),\n (' 7 ', ' host ', ' 1 '),\n (' 8 ', ' i.d ', ' 1 '),\n (' 9 ', ' info ', ' 1 '),\n (' 10 ', ' line ', ' 1 '),\n (' 11 ', ' nntp ', ' 1 '),\n (' 12 ', ' novitskey ', ' 1 '),\n (' 13 ', ' opportunity ', ' 1 '),\n (' 14 ', ' organization ', ' 1 '),\n (' 15 ', ' post ', ' 2 '),\n (' 16 ', ' pursue ', ' 1 '),\n (' 17 ', ' reserve_university ', ' 1 '),\n (' 18 ', ' reward ', ' 1 '),\n (' 19 ', ' robert ', ' 1 '),\n (' 20 ', 'robert_r._novitskey ', ' 2 '),\n (' 21 ', ' similar ', ' 1 '),\n (' 22 ', ' system ', ' 1 '),\n (' 23 ', ' temp ', ' 1 '),\n (' 24 ', ' thank ', ' 1 '),\n (' 25 ', ' usa ', ' 1 '),\n (' 26 ', ' wall ', ' 1 '),\n (' 27 ', ' woman ', ' 1 ')]\n"
]
],
[
[
"# Train and evaluate an `LDA` topic model\n`LDA` or `Latent Dirichlet Allocation` is a generative probabilistic model that tries to find groups of words that appear frequently together across different documents.\nIt is the most commonly used method to discover a user-specified number of `topics` shared by documents within a text corpus. Here each observation is a document, the features are the presence (or occurrence count) of each word, and the categories are the topics. Since the method is unsupervised, the topics are not specified up front, and are not guaranteed to align with how a human may naturally categorize documents. The topics are learned as a probability distribution over the words that occur in each document. Each document, in turn, is described as a mixture of topics. [https://docs.aws.amazon.com/sagemaker/latest/dg/lda.html]\n\n* Input to LDA: a bag-of-words matrix\n* Output from LDA: A document-to-topic matrix + A word-to-topic matrix\n\npaper: `Latent Dirichlet Allocation, David M. Blei, Andrew Y. Ng, and Michael I. Jordan, Journal of Machine Learning Research 3, pages: 993–1022, Jan 2003.`\n\nOther options are `HDP` and `NTM`.\n\nThe difference between HDP and LDA is that HDP is a non-parametric method. Which means that we don't need to specify the number of topics. HDP will fit as many topics as it can and find the optimal number of topics by itself.\n\nChoosing between Latent Dirichlet Allocation (LDA) and Neural Topic Model (NTM) is described here: https://docs.aws.amazon.com/sagemaker/latest/dg/lda.html\n\nRecent research by Amazon, Dinget et al., 2018 has shown that NTM is promising for achieving high topic coherence but LDA trained with collapsed Gibbs sampling achieves better perplexity. Research has shown that the likelihood computed per word often does not align to human judgement, and can be entirely non-correlated, thus topic coherence i more important for our task.\n\nMore infor about NTM: https://docs.aws.amazon.com/sagemaker/latest/dg/ntm.html\n\n\n####Mallet’s LDA:\n`MALLET` is a Java-based package for statistical natural language processing, document classification, clustering, topic modeling, information extraction, and other machine learning applications to text.\nThe MALLET topic model package includes an extremely fast and highly scalable implementation of `Gibbs sampling`, efficient methods for document-topic hyperparameter optimization, and tools for inferring topics for new documents given trained models.\n",
"_____no_output_____"
]
],
[
[
"import sys\nsys.path.append('/content/gensimwrapper')\nfrom gensimwrapper.ldamallet import LdaMallet\n \nimport numpy as np",
"_____no_output_____"
],
[
"def train_gensim_lda(dictionary: gensim.corpora.dictionary.Dictionary,\n corpus: list,\n num_topics: int = 20) -> gensim.models.ldamodel.LdaModel:\n return gensim.models.ldamodel.LdaModel(\n corpus=corpus,\n num_topics=num_topics,\n id2word=dictionary,\n chunksize=100, # the number of docs to be used in each training chunk\n passes=10, # the total number of training passes\n update_every=1, # how often the model parameters should be updated\n alpha='auto', # alpha and eta are hyperparameters that affect sparsity\\\n # eta=None, # of the topics, both defaults to 1.0/num_topics prior.\n random_state=100,\n per_word_topics=True,\n )\n \n \ndef train_mallet_lda(dictionary: gensim.corpora.dictionary.Dictionary,\n corpus: list,\n num_topics: int = 20) -> LdaMallet:\n \"\"\"\n an (optimized version of) collapsed gibbs sampling from MALLET.\n MALLET’s LDA training requires `O(corpus_words)` of memory, keeping the entire\n corpus in RAM. If you find yourself running out of memory, either decrease the\n workers constructor parameter, or use Gensim's native LDA model which needs\n only O(1) memory.\n \"\"\"\n return LdaMallet(\n mallet_path='/content/mallet-2.0.8/bin/mallet',\n corpus=corpus,\n num_topics=num_topics,\n # alpha=50,\n id2word=dictionary,\n # workers=4,\n iterations=1000,\n random_seed=100,\n )\n \n \ndef convert_mallet_model_to_gensim_model(\n mallet_model,\n gamma_threshold=0.001,\n iterations=50 # or 1000?\n) -> gensim.models.ldamodel.LdaModel:\n gensim_model = gensim.models.ldamodel.LdaModel(\n id2word=mallet_model.id2word,\n num_topics=mallet_model.num_topics,\n alpha=mallet_model.alpha,\n eta=0,\n iterations=iterations,\n gamma_threshold=gamma_threshold,\n dtype=np.float64 # don't loose precision when converting from MALLET\n )\n gensim_model.state.sstats[...] = mallet_model.wordtopics\n gensim_model.sync_state()\n return gensim_model\n \n \ndef compute_log_perplexity(lda_model: gensim.models.ldamodel.LdaModel,\n chunk,\n total_docs=None) -> np.float64:\n \"\"\"\n per-word likelihood bound, using the chunk of documents as evaluation corpus.\n perplexity=2^(-bound)\n lower the better!\n \"\"\"\n return lda_model.log_perplexity(chunk, total_docs)\n\n\ndef compute_topic_coherence(lda_model: gensim.models.ldamodel.LdaModel,\n dictionary: gensim.corpora.dictionary.Dictionary,\n texts: list,\n coherence_measure: str = 'c_v') -> np.float64:\n \"\"\"\n topic coherence for topic models.\n https://rare-technologies.com/what-is-topic-coherence/\n paper: http://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdf\n \"\"\"\n return gensim.models.CoherenceModel(\n model=lda_model,\n texts=texts, # tokenized texts\n dictionary=dictionary,\n # coherence measure: 'u_mass', 'c_v', 'c_uci', 'c_npmi'\n coherence=coherence_measure,\n topn=10, # the number of top words to be extracted from each topic.\n ).get_coherence()",
"_____no_output_____"
]
],
[
[
"## Tune `num_topics` hyper parameter:\n\nTopic models aim to minimize `perplexity` and maximize `topic coherence`.\n\nPerplexity is an intrinsic language modeling evaluation metric that measures the inverse of the geometric mean per-word likelihood in your test data. A lower perplexity score indicates better generalization performance [https://docs.aws.amazon.com/sagemaker/latest/dg/lda.html].",
"_____no_output_____"
]
],
[
[
"%%time\n \nnum_topics_min = 2\nnum_topics_max = 31\nnum_topics_surge_step = 2\n \ncandidate_lda_models = []\n\nfor num_topics in range(num_topics_min, num_topics_max, num_topics_surge_step):\n print(\"Training an LDA model with %d topics...\" % num_topics)\n lda_model = train_mallet_lda(dictionary, train_corpus_bow, num_topics)\n\n # print(\"Computing Log Perplexity of the LDA model with %d topics...\")\n # log_perplexity = compute_log_perplexity(lda_model, val_corpus_bow)\n # print(\n # \"Log Perplexity of the LDA model with %d topics is: %f\" %(num_topics,\n # log_perplexity)\n # )\n\n print(\n \"Computing Topic Coherence for the LDA model with %d topics...\" % num_topics\n )\n topic_coherence = compute_topic_coherence(lda_model,\n dictionary,\n val_corpus_preprocessed,\n # coherence_measure='c_v')\n coherence_measure='u_mass')\n print(\n \"Topic Coherence for the LDA model with %d topic is: %f\" % (num_topics,\n topic_coherence)\n )\n\n candidate_lda_models.append(\n {\n 'num_topics': num_topics,\n 'lda_model': lda_model,\n # 'perplexity': np.exp2(-log_perplexity),\n # 'log_perplexity': log_perplexity,\n 'topic_coherence': topic_coherence\n }\n )\n print(\"--------------------------------------------------------------\")",
"Training an LDA model with 2 topics...\nComputing Topic Coherence for the LDA model with 2 topics...\nTopic Coherence for the LDA model with 2 topic is: -1.328114\n--------------------------------------------------------------\nTraining an LDA model with 4 topics...\nComputing Topic Coherence for the LDA model with 4 topics...\nTopic Coherence for the LDA model with 4 topic is: -1.439494\n--------------------------------------------------------------\nTraining an LDA model with 6 topics...\nComputing Topic Coherence for the LDA model with 6 topics...\nTopic Coherence for the LDA model with 6 topic is: -1.450413\n--------------------------------------------------------------\nTraining an LDA model with 8 topics...\nComputing Topic Coherence for the LDA model with 8 topics...\nTopic Coherence for the LDA model with 8 topic is: -2.149721\n--------------------------------------------------------------\nTraining an LDA model with 10 topics...\nComputing Topic Coherence for the LDA model with 10 topics...\nTopic Coherence for the LDA model with 10 topic is: -1.998588\n--------------------------------------------------------------\nTraining an LDA model with 12 topics...\nComputing Topic Coherence for the LDA model with 12 topics...\nTopic Coherence for the LDA model with 12 topic is: -2.297091\n--------------------------------------------------------------\nTraining an LDA model with 14 topics...\nComputing Topic Coherence for the LDA model with 14 topics...\nTopic Coherence for the LDA model with 14 topic is: -2.758334\n--------------------------------------------------------------\nTraining an LDA model with 16 topics...\nComputing Topic Coherence for the LDA model with 16 topics...\nTopic Coherence for the LDA model with 16 topic is: -2.339935\n--------------------------------------------------------------\nTraining an LDA model with 18 topics...\nComputing Topic Coherence for the LDA model with 18 topics...\nTopic Coherence for the LDA model with 18 topic is: -2.307495\n--------------------------------------------------------------\nTraining an LDA model with 20 topics...\nComputing Topic Coherence for the LDA model with 20 topics...\nTopic Coherence for the LDA model with 20 topic is: -2.587363\n--------------------------------------------------------------\nTraining an LDA model with 22 topics...\nComputing Topic Coherence for the LDA model with 22 topics...\nTopic Coherence for the LDA model with 22 topic is: -2.291835\n--------------------------------------------------------------\nTraining an LDA model with 24 topics...\nComputing Topic Coherence for the LDA model with 24 topics...\nTopic Coherence for the LDA model with 24 topic is: -2.547238\n--------------------------------------------------------------\nTraining an LDA model with 26 topics...\nComputing Topic Coherence for the LDA model with 26 topics...\nTopic Coherence for the LDA model with 26 topic is: -2.157264\n--------------------------------------------------------------\nTraining an LDA model with 28 topics...\nComputing Topic Coherence for the LDA model with 28 topics...\nTopic Coherence for the LDA model with 28 topic is: -2.368436\n--------------------------------------------------------------\nTraining an LDA model with 30 topics...\nComputing Topic Coherence for the LDA model with 30 topics...\nTopic Coherence for the LDA model with 30 topic is: -2.370172\n--------------------------------------------------------------\nCPU times: user 1min 18s, sys: 2.69 s, total: 1min 21s\nWall time: 32min 5s\n"
]
],
[
[
"## Plot the topic coherence landscape",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"plt.plot(\n [candidate['num_topics'] for candidate in candidate_lda_models],\n [candidate['topic_coherence'] for candidate in candidate_lda_models]\n)\nplt.xlabel(\"num_topics\")\nplt.ylabel(\"topic_coherence\")\nplt.title(\"Tuning number of topics\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Find the best model\nChoosing a ‘k’ that marks the end of a rapid growth of topic coherence (for `c_v` cherence measure) usually offers meaningful and interpretable topics. Picking an even higher value can sometimes provide more granular sub-topics.\n\nIf the coherence score seems to keep increasing, it may make better sense to pick the model that gave the highest CV before flattening out.\n\nIf you see the same keywords being repeated in multiple topics, it’s probably a sign that the ‘k’ is too large.\n\nFor `u_mass` coherence measure, we should choose the lowest negative value.",
"_____no_output_____"
]
],
[
[
"# Choose based on the plot\nbest_model_idx = 6",
"_____no_output_____"
],
[
"num_topics = candidate_lda_models[best_model_idx]['num_topics']\n\nlda_model = candidate_lda_models[best_model_idx]['lda_model']\nlda_model.save('lda.model')",
"_____no_output_____"
]
],
[
[
"# List the keywords for each topic and the weightage (importance) of each keyword\n\nThe weights reflect how important a keyword is to that topic.",
"_____no_output_____"
]
],
[
[
"# lda_model.show_topics(num_topics=num_topics, formatted=False)\nlda_model.print_topics()",
"_____no_output_____"
]
],
[
[
"## Get a topic keywords and their weightage",
"_____no_output_____"
]
],
[
[
"def get_topic_keywords(lda_model: LdaMallet,\n topic_id: int) -> List[Tuple[str, float]]:\n return lda_model.show_topic(topic_id)",
"_____no_output_____"
],
[
"get_topic_keywords(\n lda_model=lda_model,\n topic_id=0\n)",
"_____no_output_____"
],
[
"from wordcloud import WordCloud",
"_____no_output_____"
],
[
"def plot_topic_word_cloud(lda_model: LdaMallet,\n topic_id: int) -> None:\n keyword_frequencies = dict(\n get_topic_keywords(\n lda_model=lda_model,\n topic_id=topic_id\n )\n )\n\n wordcloud = WordCloud(background_color='white',\n width=2500,\n height=1800,\n max_words=10,\n colormap='tab10',\n color_func=lambda *args, **kwargs: '#1f77b4',\n prefer_horizontal=1.0)\n \n wordcloud.generate_from_frequencies(keyword_frequencies,\n max_font_size=300)\n \n plt.gca().imshow(wordcloud)\n plt.gca().set_title(\n 'Top Keywords for topic #%d' % topic_id,\n fontdict=dict(size=16)\n )\n plt.gca().axis('off')\n\n plt.show() ",
"_____no_output_____"
],
[
"plot_topic_word_cloud(\n lda_model=lda_model,\n topic_id=0\n)",
"_____no_output_____"
]
],
[
[
"## Visualize topic-term relevance and relationship\n`pyLDAvis` (sievert-illvi2014 - https://nlp.stanford.edu/events/illvi2014/papers/sievert-illvi2014.pdf) is designed to help users interpret the topics in an LDA topic model fitted to a corpus of text data.\n\nyou need to provide the topic-term distributions, document-topic distributions, and basic information about the corpus which the model was trained on to the function `prepare` that will transform your data into the format needed for the visualization.",
"_____no_output_____"
],
[
"Convert `MALLET`'s model to `Gensim`'s model in order to be used in `pyLDAvis` package.",
"_____no_output_____"
]
],
[
[
"lda_model_gensim = convert_mallet_model_to_gensim_model(lda_model)",
"_____no_output_____"
],
[
"import pyLDAvis\nimport pyLDAvis.gensim_models as gensimvis",
"/usr/local/lib/python3.7/dist-packages/past/types/oldstr.py:5: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working\n from collections import Iterable\n/usr/local/lib/python3.7/dist-packages/past/builtins/misc.py:4: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working\n from collections import Mapping\n/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_least_angle.py:30: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\nDeprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n method='lar', copy_X=True, eps=np.finfo(np.float).eps,\n/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_least_angle.py:169: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\nDeprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n method='lar', copy_X=True, eps=np.finfo(np.float).eps,\n/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_least_angle.py:286: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\nDeprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n eps=np.finfo(np.float).eps, copy_Gram=True, verbose=0,\n/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_least_angle.py:858: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\nDeprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n eps=np.finfo(np.float).eps, copy_X=True, fit_path=True):\n/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_least_angle.py:1094: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\nDeprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n eps=np.finfo(np.float).eps, copy_X=True, fit_path=True,\n/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_least_angle.py:1120: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\nDeprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n eps=np.finfo(np.float).eps, positive=False):\n/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_least_angle.py:1349: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\nDeprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n max_n_alphas=1000, n_jobs=None, eps=np.finfo(np.float).eps,\n/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_least_angle.py:1590: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\nDeprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n max_n_alphas=1000, n_jobs=None, eps=np.finfo(np.float).eps,\n/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_least_angle.py:1723: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\nDeprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n eps=np.finfo(np.float).eps, copy_X=True, positive=False):\n/usr/local/lib/python3.7/dist-packages/sklearn/decomposition/_lda.py:29: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\nDeprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n EPS = np.finfo(np.float).eps\n"
],
[
"pyldavis_prepared_data = gensimvis.prepare(\n topic_model=lda_model_gensim,\n corpus=test_corpus_bow,\n dictionary=dictionary,\n # mds='tsne' # require that you have sklearn installed\n)\n \npyLDAvis.save_html(pyldavis_prepared_data, 'pyLDAvis.html')\n \npyLDAvis.display(pyldavis_prepared_data)",
"/usr/local/lib/python3.7/dist-packages/pyLDAvis/_prepare.py:247: FutureWarning: In a future version of pandas all arguments of DataFrame.drop except for the argument 'labels' will be keyword-only\n by='saliency', ascending=False).head(R).drop('saliency', 1)\n"
]
],
[
[
"# Get Topic proportions and dominant topic",
"_____no_output_____"
]
],
[
[
"def get_topic_proportions(\n lda_model: LdaMallet,\n docs_bow: List[List[Tuple[int, int]]]\n) -> List[List[Tuple[int, float]]]:\n return lda_model[docs_bow]\n\n\ndef sort_topic_proportions(\n unsorted_topic_proportions: List[Tuple[int, float]],\n reverse=True\n) -> List[Tuple[int, float]]:\n return list(\n sorted(\n unsorted_topic_proportions,\n key=lambda t: t[1],\n reverse=reverse\n )\n )",
"_____no_output_____"
],
[
"%%time\n\ntrain_corpus_topic_proportions = get_topic_proportions(lda_model,\n train_corpus_bow)\n\ntest_corpus_topic_proportions = get_topic_proportions(lda_model,\n test_corpus_bow)\n\nprint(\"Review:\")\npprint(test_corpus_raw[0])\nprint(\"\\n In order topics:\")\npprint(test_corpus_topic_proportions[0])\nprint(\"\\n Sorted topics:\")\npprint(\n sort_topic_proportions(test_corpus_topic_proportions[0])\n)",
"Review:\n(\"from: [email protected] subject: what's the diff.between \"\n \"mouse.sys/com?? organization: western michigan university lines: 8 what's \"\n 'the difference between loading mouse.com in autoexec.bat and doing '\n 'device=mouse.sys in config.sys?? which one is better? thanks a lot enrique')\n\n In order topics:\n[(0, 0.06219099661722614),\n (1, 0.0749414519906323),\n (2, 0.06219099661722614),\n (3, 0.06219099661722614),\n (4, 0.06219099661722614),\n (5, 0.0858704137392662),\n (6, 0.058548009367681515),\n (7, 0.06947697111631537),\n (8, 0.06401249024199845),\n (9, 0.06219099661722614),\n (10, 0.06036950299245382),\n (11, 0.11137132448607857),\n (12, 0.06947697111631537),\n (13, 0.09497788186312776)]\n\n Sorted topics:\n[(11, 0.11137132448607857),\n (13, 0.09497788186312776),\n (5, 0.0858704137392662),\n (1, 0.0749414519906323),\n (7, 0.06947697111631537),\n (12, 0.06947697111631537),\n (8, 0.06401249024199845),\n (0, 0.06219099661722614),\n (2, 0.06219099661722614),\n (3, 0.06219099661722614),\n (4, 0.06219099661722614),\n (9, 0.06219099661722614),\n (10, 0.06036950299245382),\n (6, 0.058548009367681515)]\nCPU times: user 1.6 s, sys: 158 ms, total: 1.75 s\nWall time: 19.6 s\n"
]
],
[
[
"## Plot topic proportions",
"_____no_output_____"
]
],
[
[
"i = 0\n\n\nprint(\"REVIEW #%d:\" % i)\npprint(test_corpus_raw[i])\nprint()\n\n\ndef print_keywords_text(lda_model: LdaMallet, topic_id: int) -> str:\n keywords = get_topic_keywords(lda_model, topic_id)\n keywords_text = [text for text, proportion in keywords]\n return (\"TOPIC #%d: \" % topic_id).ljust(11) + \", \".join(keywords_text)\n\n# topic_proportions = test_corpus_topic_proportions[i]\ntopic_proportions = sort_topic_proportions(\n test_corpus_topic_proportions[i],\n reverse=False\n)\nproportions = [proportion for _, proportion in topic_proportions]\nkeywords = [print_keywords_text(lda_model, id) for id, _ in topic_proportions]\n\nmy_range = range(num_topics)\n\n\nplt.figure(figsize=(8,10))\nplt.hlines(\n y=my_range,\n xmin=0,\n xmax=proportions,\n color='skyblue'\n)\n\n# Plot\nplt.plot(\n proportions,\n my_range,\n 'o'\n)\n \nplt.gca().yaxis.set_ticks_position(\"right\")\nplt.yticks(\n my_range,\n keywords,\n fontsize=12\n)\n \nplt.ylabel('TOPICS')\nplt.xlabel('TOPIC PROPORTION')\n\nplt.show()",
"REVIEW #0:\n(\"from: [email protected] subject: what's the diff.between \"\n \"mouse.sys/com?? organization: western michigan university lines: 8 what's \"\n 'the difference between loading mouse.com in autoexec.bat and doing '\n 'device=mouse.sys in config.sys?? which one is better? thanks a lot enrique')\n\n"
]
],
[
[
"# Check out the dominant topic keywords for some randomly-selected unseen documents",
"_____no_output_____"
]
],
[
[
"num_docs = 10\n\nfor i in np.random.randint(len(testset_dataframe), size=num_docs):\n print(\"Review #%d:\" % i)\n pprint(test_corpus_raw[i])\n\n sorted_topic_proportions = sort_topic_proportions(\n test_corpus_topic_proportions[i]\n )\n\n print(\"\\nDominant Topic (%f) Keywords:\" % sorted_topic_proportions[0][1])\n first_dominant_topic_id = sorted_topic_proportions[0][0]\n print(\n get_topic_keywords(\n lda_model,\n first_dominant_topic_id\n )\n )\n\n print(\"\\nSecond Topic (%f) Keywords:\" % sorted_topic_proportions[1][1])\n second_topic_id = sorted_topic_proportions[1][0]\n print(\n get_topic_keywords(\n lda_model,\n second_topic_id\n )\n )\n \n print(\"-\" * 335)",
"Review #2029:\n('organization: esoc european space operations centre from: '\n '<[email protected]> subject: re: apollo training in iceland distribution: '\n 'sci lines: 10 the apollo astronauts also trained at (in) meteor crater in '\n 'the flagstaff area (arizona). there is now a museum with a space shop. '\n 'caution: they ease you by 6$. compared to a ksc visit it is not worth. '\n '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- '\n 'thorsten nedderhut | disclaimer: mbp software & systems gmbh | c/o '\n 'esa/esoc/fcsd/oad/stb | neither esa nor mbp is responsible darmstadt, '\n 'germany | for my postings! [email protected] |')\n\nDominant Topic (0.179954) Keywords:\n[('key', 0.021244613688746368), ('space', 0.011991849550723185), ('system', 0.010789324247586598), ('information', 0.007799712730066473), ('technology', 0.007348765741390253), ('encryption', 0.006580485686608545), ('chip', 0.0056785917092561046), ('message', 0.005428065604435982), ('communication', 0.005327855162507934), ('security', 0.005327855162507934)]\n\nSecond Topic (0.082575) Keywords:\n[('israel', 0.010571395501369651), ('jews', 0.010301323353524442), ('war', 0.007986419229136926), ('world', 0.00790925575832401), ('turkish', 0.00653960415139473), ('armenian', 0.006346695474362437), ('people', 0.006134495929626915), ('history', 0.0058451329140784755), ('israeli', 0.005690805972452641), ('attack', 0.005382152089200972)]\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nReview #46:\n('from: [email protected] (john nagle) subject: re: waco: the militia assembles '\n 'keywords: we salute them organization: netcom on-line communication services '\n '(408 241-9760 guest) distribution: usa lines: 7 dumb move. the smart move '\n 'would be to sneak in someone with a tv camera and video transmitter. john '\n 'nagle')\n\nDominant Topic (0.145282) Keywords:\n[('line', 0.013409803597953457), ('power', 0.010707212411288991), ('work', 0.009139296913682126), ('high', 0.006106618253837267), ('low', 0.006024096385542169), ('ground', 0.006003465918468394), ('design', 0.005982835451394619), ('box', 0.005838422181878198), ('organization', 0.005735269846509325), ('wire', 0.005446443307476481)]\n\nSecond Topic (0.098986) Keywords:\n[('line', 0.07118181087812324), ('organization', 0.07009721217964168), ('post', 0.06445328191532096), ('host', 0.05884952197316622), ('nntp', 0.05678075038161806), ('university', 0.044508716959910016), ('distribution', 0.01873945529043143), ('usa', 0.012894673415280791), ('mail', 0.011408371495139392), ('david', 0.007973808949947779)]\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nReview #319:\n('from: [email protected] (matt freivald x8043) subject: re: nlns: fascism '\n 'with a friendly face nntp-posting-host: pogo.nsc.com organization: thought '\n 'police watchdog agency, u.s.a. lines: 370 who wants to look through the bars '\n 'at some reactionary liberal conspiracy- theory idiots and see how they rant '\n 'and rave at the erosion of their populist support? this is very typical of '\n 'the elitist liberal attitude that the people are incapable of thinking for '\n 'themselves. this elitist attitude will be the eventual undoing of the '\n 'arrogant liberal tide sweeping america, as the people begin to realize more '\n 'and more that they are being treated like errant children and robbed of '\n 'their freedoms by a bunch of utopian arrogent socialist jerks. in article '\n '167077 in talk.politics.misc, new liberation news service <[email protected]> '\n 'writes: >subject: nlns: fascism with a friendly face >lines: 164 >from: new '\n 'liberation news service <nlns> >subject: nlns: fascism with a friendly face '\n '>/* written 8:33 pm apr 14, 1993 by [email protected] in igc:nlns.news */ >/* '\n '---------- \"nlns packet 3.11 *** 4-14-93\" ---------- */ >fascism with a '\n 'friendly face: does rush limbaugh remind you of >anyone? >daevid '\n 'bornhuetter-machen, the madison edge >\"the main difference between adolf '\n 'hitler and rush limbaugh is that >hitler was original and showed '\n 'initiative.\" >--mort sahl on the tom snyder radio show, abc radio network, '\n '>october 27, 1992. although i find myself often disagreeing with the '\n 'populist rationale of mr. limbaugh, i find him entertaining and i often '\n 'agree with his conclusions. the fact that he sends liberal reactionaries '\n 'like these idiots through the roof makes him all the more entertaining. '\n '>(nlns)--believe it or not, i was planning this comparative review of >mein '\n \"kampf and limbaugh's transcribed rant, the way things ought to >be before \"\n \"sahl issued his comparative review. as usual, sahl's was >independent and \"\n 'sharp as a scalpel. > my effort can only dream of comparing favorably to '\n \"mort's. at >least it has a fairly popular orginating premise; everyone i \"\n 'would mention the >idea to thought it was either divinely inspired or at '\n 'least past due for >delivery. > those reactions are based on parallels that '\n 'should be obvious to the >most peripheral observer of the acts of those '\n 'false prophets. both are >noted for their galvanizing oratorical skills, '\n 'which they both used with >passion to generate a political cult of massive '\n 'numerical proportions (in >fact, limbaugh claims to have an audience of just '\n 'over 12 million, almost >identical to the number of votes cast for hitler in '\n 'the april 1932 german >election). both used a myopic social perspective to '\n 'build the cult, and >enthusiastically amputated facts from the record to '\n \"fabricate their >ideological quilt. actually, i find limbaugh's oratory less \"\n 'than sizzling and his debating skills sometimes lacking, even though his '\n 'conclusions are often correct. i would suggest that a bankrupt leftist '\n 'ideology that hopes to use concentrated political power and a loaded gun to '\n 'force everyone to do the \"right\" things (where \"right\" is defined by the '\n 'elitist academics who lead the movement) is showing an acute case of \"myopic '\n 'social perspective\", not to mention arrogance and utter stupidity. limbaugh '\n 'is certainly far from perfect, but his opponents in the established body '\n 'politic and the media are the ones arguing for federal control of virtually '\n 'all aspects of the lives of the citizenry, and for the elimination of local '\n 'control over affairs public. perhaps limbaugh has a following because the '\n 'people are tired of being treated like errant children by a self-important '\n 'group of arrogant controlling myopic people who have no understanding of how '\n 'life operates outside of the \"oughta-be\\'s\" inside their own hopelessly '\n 'closed minds. > the last point is glaringly documented by passages in the '\n \"opening >pages of both books. hitler's example is when, on page 5, he claims \"\n 'the >german nationalist terrorist leo schlageter (he bombed part of a '\n 'railway >line between dusseldorf and duisburg, being caught in the act, in '\n '1923) >was \"betrayed to france by a representative of his government\" when '\n '>there has never been any factual foundation for such a statement. > in '\n 'fact, the governments of both the reich and prussia, as well as >the '\n 'vatican, actively intervened to save him from execution, and almost '\n '>succeeded. ok, let us take your word for that and work with it. a nice '\n 'specific incident. >limbaugh follows suit by making the hysterically '\n 'sarcastic >claim in his introduction that \"in a school or during a '\n 'commencement >ceremony or many other public places... god is '\n 'unconstitutional.\" of >course, it is not god but the official imposition of '\n \"particular concepts of >god against an individual's will that is \"\n 'unconstitutional. but limbaugh is >too gleeful in his talent for distortion '\n 'to want you to know that. hmmm, \"congress shall pass no law regarding an '\n 'establishment of religion, nor prohibiting the free exercise thereof.\" '\n 'liberal translation: \"the federal government (as long as it is run by '\n 'liberals) may force local school districts to include certain iconic content '\n 'in christmas displays, while prohibiting others.\" i think limbaugh has you '\n 'on this one. it seems to me that he is arguing for less imposition of the '\n 'federal government into religion. nice job on the specificity of that one, '\n 'too. [analysis of historical/modern communication media deleted] > but, as '\n 'mort sahl also observed on the radio the other night, some >cloutmeister of '\n 'the radical right wants limbaugh to be a focal point of >their propoganda. '\n '(and remember, sahl is an al haig conservative these >days.) > mort might '\n \"not know exactly who rush's equivalent of rodolf >hess is (the book itself \"\n 'suggests ed mclaughlin, the former president of >abc radio and now '\n \"limbaugh's partner in efm media, the radio >program's production company). \"\n 'but mort himself is a veteran of the talk >show, having hosted them in new '\n 'york, washington and los angeles. he >knows what evil lurks in the hearts of '\n 'major market media men. he knows >that limbaugh could not have collected his '\n 'audience had not the >opportunity been placed on a silver platter and handed '\n 'to him. limbaugh >earns his money just as honestly as al capone did; it is '\n 'almost worthy of a >rico indictment. ah yes, it is a conspiracy of profound '\n \"proportions. methinks that you may be a bit resentful of mr. limbaugh's \"\n 'success because you attribute it primarily to luck (how, after all, could '\n 'anyone with profound differences of opinion from yourself have become '\n 'successful without the operation of conspiracy or blind luck!) do you feel '\n 'this same level of knee-jerk resentment against lottery winners, or do you '\n 'congratulate them on their good fortune? > on questions of social issues, '\n 'there is an overabundance of >material in the limbaugh book that seems to '\n \"echo hitler's venom. for >example: this should be great fun, since it is the \"\n 'liberal movement in america that is pushing the hardest for centralized '\n 'fascist control of the people and business (government/business '\n \"'partnership' indeed), and mr. limbaugh is the populist nemesis of that \"\n \"movement. i have read mr. limbaugh's book, and although it was not the most \"\n 'literary piece i have read in recent memory it certainly did not contain '\n '\"venom\" at all, let alone \"venom\" comparable to an individual who callously '\n 'murdered millions out of racism. >on their own qualifications to control '\n 'society > hitler: \"out of the host of sometimes millions of people, who '\n '>individually more or less clearly and distinctly guess the truth, partly '\n \">perhaps understand it, one man [author's emphasis] must step forward in \"\n '>order to form, with apodeictic force, out of the wavering world of '\n '>imagination of the great masses, granite principles, and to take up the '\n 'fight >for their sole correctness, until out of the playing waves of a free '\n 'world of >thought a brazen rock of uniform combination of form and will '\n 'arises\" >(page 577). a very serious tone in that oratory. > limbaugh: \"who '\n \"needs the media when they've got me? ... the >show is devoted exclusively to \"\n 'what i think ... [the phrase \"with half my >brain tied behind my back to '\n 'make it even\"] denotes the egress of mental >aptitude i require to engage '\n 'and demolish liberals and others who disagree >with me ... it might take '\n 'four or five years, but i am convinced the media >will slowly and '\n 'reluctantly come around to my way of thinking, kicking >and screaming all '\n 'the way.\" (pages 266, 21, 299 and 273, respectively.) you neglect to mention '\n 'that mr. limbaugh (have you ever listened to his show, btw?) continuously '\n 'encourages his audience to think for themselves rather than blindly '\n 'following any media icon, himself included. you yourself mention that he '\n 'makes no bones about his show being strictly about his own opinions. he also '\n 'adopts a rather satirical approach, and presumes his audience to be '\n 'intelligent enough to distinguish satire from seriousness (and he says as '\n 'much). this is in contrast to the average mass-media show, in which the '\n \"audience is treated as society's intellectual lowest common denominator. i \"\n 'am sure that adolf hitler was a master of satire; i am sure he was just '\n \"kidding when he said that the jews were the cause of germany's problems and \"\n 'needed to be exterminated. >on religion as the basis of a nation > hitler: '\n '\"in this world human culture and civilization are >inseperably bound up with '\n 'the existence of the aryan. his dying-off or his >decline would again lower '\n 'upon this earth the dark veils of a time without >culture ... he who dares '\n 'to lay hand upon the highest image of the lord >sins against the benevolent '\n 'creator of this miracle and helps in the >expulsion from paradise.\" (page '\n '581.) this is not religion, it is clearly a perverse worship of race. since '\n \"christ was a jew, it seems quite unlikely that hitler's characterization of \"\n 'the aryan as \"the highest image of the lord\" fits with christian doctrine. > '\n 'limbaugh: \"america was founded as a judeo-christian country ... >but our '\n 'intellectual and political elites are often either hostile or >ambivalent '\n 'toward religion ... people for whom belief in god is at best a >charming '\n 'superstition have managed to ban prayer from the public schools >for the '\n 'last thirty years. is it only a coincidence that the quality of >american '\n 'education has declined ever since?\" (pages 274-5.) private religious schools '\n 'have a vastly better record of success than publicly funded schools. '\n 'american history is indeed primarily judeo- christian. i suppose that mr. '\n 'limbaugh pointing out facts is equivalent to adolf hitler worshiping the '\n 'aryan race. i think you might be reaching just a wee bit here. >on popular '\n 'culture as a reason for social collapse > hitler: \"the fight against the '\n 'poisoning of the soul has to set in ... >one has only to look at the menus '\n 'of our movie houses, vaudevilles and >theatres; and one can hardly deny that '\n 'this is not the right kind of food ... >theatre, art, literature, movies, '\n 'the press, billposters and window displays >must be cleaned of the symptoms '\n 'of a rotting world and put into the >service of a moral idea of state and '\n 'culture.\" (pages 346 and 348.) definite suggestion that the government '\n 'should control the entertainment industry here. > limbaugh: \"today, '\n 'hollywood is in trouble. the reason [is] that >hollywood has forgotten who '\n 'its audience is ... they make fun of people >who believe in god. they '\n 'ridicule the traditional family, heterosexuality >and monagamy. they '\n 'disparage american heroes.\" (page 254.) just a guess here, but i do not '\n 'think that mr. limbaugh would advocate government control of hollywood. you '\n 'should perhaps call his radio show to confirm this. i believe this is more a '\n 'criticism of hollywood and the depraved moral values it espouses, not an '\n \"advocation of government control of hollywood. 90's liberals, on the other \"\n 'hand, want to have complete government control of our school systems, so '\n 'that the government can teach the people at an early age the \"right\" way to '\n 'view religion and morality. i believe mr. limbaugh is against this, as his '\n 'satirical use of the \"young heads full of mush\" hyperbole indicates. >on the '\n 'news meida > hitler: \"the activity of the so-called liberal press was the '\n 'work of >gravediggers for the german people and the german reich. one can '\n 'pass >by in silence the marxist papers of lies ... it is task is only to '\n \"break the >people's folkish and national spine, in order to make it ripe for \"\n 'the yoke of >slavery of international capital and its masters, the jews.\" '\n '(page 331.) pretty strong conspiracy theory insinuated here, with an '\n 'implicit plea for government power to be used to break up the conspiracy. > '\n 'limbaugh: \"elements of the media have jumped on the >bandwagon of leftist '\n 'causes. the cynical journalist of the past has been >replaced in many cases '\n 'by an enthusiastic cheerleader for causes ... during >the gulf war, cnn '\n 'correspondent bernard shaw [said] cnn is a global >network. we can not take '\n 'sides. can not take sides? --- --- ---! ... if they do not >realize that '\n 'their freedom lies in the united states of america and that >therefore they '\n 'should defend this nation, they are hopelessly misguided >and, may i '\n 'suggest, flirting with megalomania.\" (pages 270 and 268.) indication here '\n 'that \"elements of the media\" (since career is a self-selected '\n \"categorization, perhaps an inferred 'larger percentage than represented in \"\n \"the populace at large') has a leftist bias. doesn't sound too unreasonable. \"\n 'no insinuation that cnn should not report in an objective fashion, only that '\n 'for reporters to say that they do not have any personal bias in the '\n 'situation is disingenuous to megalomaniacal. you may disagree, and it may '\n 'well be exagerrated, but it is not an unreasonable opinion; and mr. limbaugh '\n 'goes well out of his way to make sure that his audience knows that these are '\n 'his opinions, unlike most other reporting that purports to achieve perfect '\n 'objectivity but in actuality will in some degree or other, in a statistical '\n 'sense, reflect the biases of the reporters. who is being disingenuous here, '\n 'mr. shaw or mr. limbaugh? again, you should ask mr. limbaugh himself, but i '\n 'expect that he would oppose government control of the media. >* * * >to '\n 'continue these comparative excerpts is certainly possible, but >ultimately '\n 'too depressing to take in one reading. it is indeed depressing to see such '\n 'myopia and tiresome liberal arrogance. liberals love to play games with '\n 'paradigms as a way of discrediting people who disagree with them. why do not '\n 'you challenge conservative ideology on an intellectual level rather than '\n 'engaging in ludicrous comparisons? perhaps the underpinnings of your '\n 'ideology are intellectual only in that they exist in your mind, not the real '\n 'world. > after putting these books down, there is one undeniable fact that '\n '>haunts me. in the 1920s, adolf hitler fed depressed and frightened >germans '\n 'the opiate of hatred of those around them; in turn, it allowed >germans to '\n 'hand their collective national power to the nazis. in the 1990s, >rush '\n 'limbaugh is doing the very same thing: distributing hatred to >depressed and '\n 'frightened americans; in turn, it is helping the american >radical right to '\n 'maintain its power base as the 12-year nightmare of the >reagan-bush era '\n 'comes to an end, hoping to rebuild it into their hopes for >the fascist '\n 'states of america. perhaps there are a few among the intellectually '\n 'challenged who percieve rush limbaugh as a hate-monger, but in my experience '\n 'he has been spreading laughter at the ludicrous self-importance of the left, '\n 'not hatred. as to mr. bush, you may be correct about his fascist economic '\n 'leanings. mr. reagan, on the other hand, did his best to reverse the fascist '\n 'trend of government involvement in business. mr. clinton is increasing '\n 'fascism in america through \"business/government partnership\" and increased '\n 'levels of taxation. perhaps you should not have skipped your vocabulary '\n 'classes in grade school. > and if limbaugh is not as repellant a hitler, it '\n 'is only because the >radical right utilizes limbaugh as its own gateway '\n 'opiate. one can only >wonder what the ultimate drug is they plan to hook '\n 'america on. hmmm. seems to me that limbaugh is not in any way comparable to '\n 'hitler because he has not murdered six million jews and many, many others '\n 'out of racism. i come from a mixed-race family, so i am quite well attuned '\n 'to racism; i do not hear any coming from rush limbaugh. the only place i '\n 'hear racism coming from these days and being taken seriously is from the '\n 'liberal left. the liberal left is the movement i see trying to get america '\n 'hooked on the opiates of socialized medicine, socialized transportation, '\n 'socialized education, etc. the left already has america hopelessly addicted '\n 'to that liberal drug, the social security chain letter. it is quite clear to '\n 'me that while the hitler analogy does not really apply to either rush '\n 'limbaugh or william jefferson clinton, if one of the two is closer than the '\n 'other it is clearly the fascist clinton. >the madison edge can be reached at '\n 'po box 845, madison, wi 53701- >0845; (608) 255-4460. > >--- 30 --- this is '\n 'the same address as \"idiots anonymous\", isn\\'t it? matt freivald '\n '-------------------------------------------------------------------------- '\n 'liborgalism: thinking is irrelevant. integrity is irrelevant. free speech is '\n 'irrelevant. private property is irrelevant. personal responsibility is '\n 'irrelevant. conservativism is futile. you will be assimilated. '\n '-------------------------------------------------------------------------- '\n 'these are my opinions only and not those of my employer!!!!!!!!!!!!!!!!!!! '\n '--------------------------------------------------------------------------')\n\nDominant Topic (0.258115) Keywords:\n[('government', 0.011706679343950558), ('people', 0.011127287853577372), ('mr', 0.010265628714048016), ('state', 0.008453173282624198), ('work', 0.008349179938198241), ('president', 0.00756180175897314), ('time', 0.00664071785120038), ('year', 0.006209888281435702), ('money', 0.006195032089374852), ('stephanopoulos', 0.005155098645115284)]\n\nSecond Topic (0.204162) Keywords:\n[('israel', 0.010571395501369651), ('jews', 0.010301323353524442), ('war', 0.007986419229136926), ('world', 0.00790925575832401), ('turkish', 0.00653960415139473), ('armenian', 0.006346695474362437), ('people', 0.006134495929626915), ('history', 0.0058451329140784755), ('israeli', 0.005690805972452641), ('attack', 0.005382152089200972)]\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nReview #348:\n('from: michelle zumbo <[email protected]> subject: darkroom '\n 'supplies/enlarger organization: athletics and physical education, carnegie '\n 'mellon, pittsburgh, pa lines: 28 nntp-posting-host: po3.andrew.cmu.edu for '\n 'sale: * besler 23c ii enlarger (including filters & negative carriers) * '\n 'darkroom supplies (containers, trays, thermometer, beakers, paper focuser, '\n 'etc...i also have paper & chemicals, but i think these 2 are past expiration '\n 'date) everything is in great working condition. i bought it about a year ago '\n \"and it has served its purpose well. it hasn't been used it in a few months \"\n 'because i do not have the time or money to keep up with it and its just '\n 'sitting in my bathroom taking up space i would like to use. so, i would like '\n 'to sell it to someone who would use it rather than it collect dust in my '\n 'bathroom. if you are interested in the whole package, i will sell everything '\n '(including shipping) for $300. if you have something else in mind, i am open '\n 'to suggestions. please reply to this account. thank you... michelle')\n\nDominant Topic (0.117550) Keywords:\n[('people', 0.022174046635485303), ('time', 0.016097094670717967), ('happen', 0.012136833839745996), ('start', 0.01171008159502919), ('day', 0.011658871325663173), ('leave', 0.010856577105595575), ('live', 0.008910586869686935), ('hear', 0.008074152470041993), ('man', 0.007886381482366598), ('woman', 0.007391348878495101)]\n\nSecond Topic (0.096586) Keywords:\n[('line', 0.07118181087812324), ('organization', 0.07009721217964168), ('post', 0.06445328191532096), ('host', 0.05884952197316622), ('nntp', 0.05678075038161806), ('university', 0.044508716959910016), ('distribution', 0.01873945529043143), ('usa', 0.012894673415280791), ('mail', 0.011408371495139392), ('david', 0.007973808949947779)]\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nReview #619:\n('from: [email protected] (andrew molitor) subject: re: once tapped, your code '\n 'is no good any more. organization: department of mathematical sciences '\n 'lines: 58 distribution: na nntp-posting-host: moink.nmsu.edu [email protected] '\n '(al donaldson) writes: >[email protected] (andrew molitor) writes: >>yes, '\n 'those evil guys in the fbi can probably, with some >>effort, abuse the '\n 'system. i got news for you, if the evil guys in >>the fbi decide they want '\n \"to persecute you, they're gonna, ... > >and if richard nixon had had this \"\n \"kind of toy, he wouldn't have had >to send people into the watergate. > this \"\n 'appears to be generic calling upon the name of the anti-christ. just for the '\n \"hell of it, let's destroy this remark. let us imagine that the executive \"\n 'branch actually could extract keys from the escrow houses without anyone '\n \"knowing, or telling. now what? dick has 80 bits of data. what the hell's he \"\n \"gonna do with it? 1) trot around to the telco and say 'we'd like an \"\n \"unauthorised decrypting tap'. uh huh. 2) break in to watergate and install \"\n 'his own tap (so his people still do have to break in, neat, huh?) record '\n \"some noise, then get the executive branch phone decryption box (huh? they've \"\n \"got one? goodness, wait 'til the washington post gets hold of this) and \"\n \"decrypt the noise. 3) more likely, stare at the key, and say 'oh, hell it is \"\n \"not worth all this bloody hassle' truth is, even granted *lots* of covert \"\n 'power on the part of the executive branch, this system is *more* difficult '\n 'to tap with than pots gear. the fact that it is easier to tap than some '\n 'hypothetical system neither you nor i am going to place on our phones is '\n 'neither here nor there. the only rational concerns i am seeing raised are: '\n 'a) is the key really just chopped in half, and not some xor arrangement? '\n 'that is, has some egregious technical error been built in to the plan? b) is '\n 'this is the first step toward strict regulation of strong encryption? >but '\n 'that is not really the issue. the real issue is whether this >will be used '\n \"to justify a ban against individuals' use of private >(i.e., anything else) \"\n 'encryption methods. this is b), of course. i suspect not. if the government '\n \"actually wanted to make such regs, they'd just do it. a few hundred people \"\n \"on usenet yelling about it wouldn't even slow the machine down. besides, who \"\n \"is this mysterious 'they' who's going to take away all our rights the \"\n 'instant we let our guard down? congress? that gang of buffoons can not even '\n 'balance their checkbooks. the fbi? but.. they do not make the laws. the nsa? '\n 'ditto. the white house? bill clinton is probably still looking for the '\n 'bathroom. it is a big place, after all. andrew > >al')\n\nDominant Topic (0.195314) Keywords:\n[('key', 0.021244613688746368), ('space', 0.011991849550723185), ('system', 0.010789324247586598), ('information', 0.007799712730066473), ('technology', 0.007348765741390253), ('encryption', 0.006580485686608545), ('chip', 0.0056785917092561046), ('message', 0.005428065604435982), ('communication', 0.005327855162507934), ('security', 0.005327855162507934)]\n\nSecond Topic (0.120711) Keywords:\n[('gun', 0.01471265214429079), ('law', 0.0139392711805108), ('line', 0.009262157732888946), ('write', 0.008046844789806102), ('state', 0.007512843648148489), ('entry', 0.007383946820851824), ('case', 0.007107739333787541), ('firearm', 0.005800357228349936), ('people', 0.0056898742335242235), ('crime', 0.005671460401053271)]\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nReview #920:\n('from: [email protected] (steve hendricks) subject: re: limiting govt '\n '(was re: employment (was re: why not concentrate...) summary: but how do '\n 'restrain unpleasant impulses? organization: free the barbers, inc. lines: 46 '\n 'nntp-posting-host: thor.isc-br.com in article '\n '<[email protected]> [email protected] '\n 'writes: >in article <[email protected]>, '\n '[email protected] (steve hendricks) writes: > >> in article '\n '<[email protected]> [email protected] '\n '(patrick.b.hailey) writes: > >>>... the point is that this law protects no '\n 'one but the >>>established car dealers or people with enough money to start '\n 'a >>>fairly big operation all at once. protecting these folks from '\n '>>>competition protects the rest of us from low prices and high >>>quality. '\n '> >> an excellent point. but you seem to be missing a more subtle >> point. '\n 'it is not \"the government\" that should be the recipient >> of your '\n 'displeasure, but the established business interests >> that influence and '\n 'direct government action in this case. > >it is the government that is '\n 'preventing entry to the market. the >desire of those running established '\n 'businesses to prevent or >restrict the entry of competitors is an '\n 'understandable, though >generally unpleasant, human failing. but without a '\n 'means to act >on this desire, without a government with sufficient power to '\n '>restrict the options of the potential competitor, the >anti-competitive '\n 'desire remains just an unpleasant wish. the >government is the linchpin, so '\n 'we seek to disengage it so we >do not get the shaft. once again, mark, you '\n 'do not specify the means through which the government is to be prevented '\n 'from becoming the tool of business interests. as a left-wing, big '\n 'government, conventional liberal, i am just as willing as you are to vote '\n 'against anti-competitive regulations that favor auto dealers. but what i '\n \"hear from libertarians is a desire to limit incumbents' terms, to weaken \"\n 'government by eliminating its power to enforce antitrust laws, and a desire '\n \"to eliminate legislator's pay. each strikes me as a particularly ineffective \"\n 'way to insure that auto dealers and other special interests cannot influence '\n 'public policy. in fact, they seem clearly designed to accomplish the '\n 'opposite. jsh > >=mark -- steve hendricks | domain: [email protected] '\n '\"one thing about data, it sure does cut| uucp: ...!uunet!isc-br!thor!steveh '\n 'the bulls**t.\" - r. hofferbert | ma bell: 509 838-8826')\n\nDominant Topic (0.391081) Keywords:\n[('government', 0.011706679343950558), ('people', 0.011127287853577372), ('mr', 0.010265628714048016), ('state', 0.008453173282624198), ('work', 0.008349179938198241), ('president', 0.00756180175897314), ('time', 0.00664071785120038), ('year', 0.006209888281435702), ('money', 0.006195032089374852), ('stephanopoulos', 0.005155098645115284)]\n\nSecond Topic (0.089494) Keywords:\n[('car', 0.02335647552927059), ('organization', 0.011571097968629467), ('good', 0.010156852661352533), ('bike', 0.009685437558926887), ('buy', 0.0094283020485129), ('sale', 0.009042598782891917), ('sell', 0.008742607354075598), ('line', 0.008421187966058112), ('price', 0.006771235107568355), ('ride', 0.006642667352361361)]\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nReview #1196:\n('from: [email protected] subject: re: cache card for iisi '\n 'news-software: ibm os/2 pm rn (nr/2) v0.17h by o. vishnepolsky and r. rogers '\n 'lines: 18 reply-to: [email protected] disclaimer: this posting '\n \"represents the poster's views, not necessarily those of ibm. \"\n 'nntp-posting-host: xlalonde.torolab.ibm.com organization: ibm toronto lab > '\n \">as of last week, mac's place had the applied engineering quicksilver card \"\n '>(32k cache, one pds slot, socket for fpu) on sale for $99.00 (without fpu). '\n '>regular price is $199. > >no idea if this is still going on, but i can get '\n 'the phone no. if anyone is >interested (i found their ad in macuser). > can '\n 'some people with cache cards please post speedometer numbers they get with '\n 'the cards. i have only one report, which seems to indicate that a 32k cache '\n 'card gives you only about a 1% speedup!! access to memory takes longer when '\n 'you have a cache card(and get a miss) thus a small cache card of 32k may be '\n 'worth $0. i do not know what kind of numbers 64k cards get you. also i found '\n 'it interesting that you can disable the cache cards via software(read about '\n 'it in the mac iisi tech notes from ftp.apple.com) so is $99 a good deal or '\n 'not, i still do not know.')\n\nDominant Topic (0.336645) Keywords:\n[('drive', 0.01729781126003401), ('card', 0.014920733602735468), ('system', 0.013147067966135786), ('bit', 0.012360803817952421), ('problem', 0.011007698074567097), ('db', 0.010221433926383734), ('work', 0.009325458501709667), ('driver', 0.008813472544753058), ('mac', 0.008520909140777853), ('run', 0.007880926694582091)]\n\nSecond Topic (0.099235) Keywords:\n[('write', 0.10022698810269255), ('article', 0.07386897307451472), ('line', 0.03563321853475266), ('organization', 0.03432216656230432), ('thing', 0.01903960551033187), ('post', 0.015791327489041954), ('good', 0.0127778647463995), ('opinion', 0.011779899812147778), ('bad', 0.010801502817783344), ('problem', 0.010488415779586726)]\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nReview #2156:\n('from: [email protected] (strider) subject: re: guns in backcountry? '\n 'no thanks organization: the university of texas at austin, austin tx lines: '\n '34 nntp-posting-host: louie.cc.utexas.edu [email protected] (paul '\n 'e. reimer) writes: |there are a lot of automobile accidents, but atleast '\n 'there is some |regulation to try to combat this. when i got my drivers '\n 'license, i had |to take a drivers safety class. i have to be licensed to '\n 'drive. my car |must be registered. i must (at least where i live) have '\n 'liability |insurance on both myself driving and my car (if someone else had '\n \"an |accident with it). hmm, wouldn't manditory saftey classes, registration \"\n '|of both the owner and gun, and manditory liability insurance be nice for '\n '|gun owners. as i am sure others will have pointed out to you by now, none '\n 'of the above measures are required for you *on your own property*. you do '\n 'not have to have a license, your car does not have to be registered or '\n 'inspected, and you do not have to have insurance or safety training classes, '\n 'when you own and operate that vehicle on your own premises. if you are going '\n 'to make use of this dubious analogy, at least make it accurate. and by the '\n 'way, in texas you can drive a car in public (with the proper credentials), '\n 'but an ordinary civilian can not carry a gun legally in public to save '\n 'his/her life. so i will not even consider registration, *manadatory* safety '\n 'classes, or *manadatory* liability insurance unless i get a federal law '\n 'repealing all local, state, and federal gun control laws which abridge the '\n 'second amendment, and a non-discretionary federal weapons carry permit, good '\n 'anywhere in the united states. come on, you wanted the analogy. mike ruff -- '\n '- this above all, to thine own s t r i d e r [email protected] - self '\n 'be true. --polonius * * ***** ** * * **** ***** *** * * those who would '\n 'sacrifice essential * * * * * * * * * * ** * liberties for a little '\n 'temporary * * * **** * * **** * * * * * safety deserve neither liberty * * * '\n '* * * * * * * * ** nor safety. --b. franklin **** * * * **** **** * *** * *')\n\nDominant Topic (0.297284) Keywords:\n[('gun', 0.01471265214429079), ('law', 0.0139392711805108), ('line', 0.009262157732888946), ('write', 0.008046844789806102), ('state', 0.007512843648148489), ('entry', 0.007383946820851824), ('case', 0.007107739333787541), ('firearm', 0.005800357228349936), ('people', 0.0056898742335242235), ('crime', 0.005671460401053271)]\n\nSecond Topic (0.154045) Keywords:\n[('car', 0.02335647552927059), ('organization', 0.011571097968629467), ('good', 0.010156852661352533), ('bike', 0.009685437558926887), ('buy', 0.0094283020485129), ('sale', 0.009042598782891917), ('sell', 0.008742607354075598), ('line', 0.008421187966058112), ('price', 0.006771235107568355), ('ride', 0.006642667352361361)]\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nReview #952:\n('from: [email protected] (jon leech) subject: space faq 09/15 - mission '\n 'schedules supersedes: <[email protected]> organization: '\n 'university of north carolina, chapel hill lines: 177 distribution: world '\n 'expires: 6 may 1993 19:59:07 gmt nntp-posting-host: mahler.cs.unc.edu '\n 'keywords: frequently asked questions archive-name: space/schedule '\n 'last-modified: $date: 93/04/01 14:39:23 $ space shuttle answers, launch '\n 'schedules, tv coverage shuttle launchings and landings; schedules and how to '\n 'see them shuttle operations are discussed in the usenet group '\n 'sci.space.shuttle, and ken hollis ([email protected]) posts a '\n 'compressed version of the shuttle manifest (launch dates and other '\n 'information) periodically there. the manifest is also available from the '\n 'ames space archive in space/faq/manifest. the portion of his manifest '\n 'formerly included in this faq has been removed; please refer to his posting '\n 'or the archived copy. for the most up to date information on upcoming '\n 'missions, call (407) 867-info (867-4636) at kennedy space center. official '\n 'nasa shuttle status reports are posted to sci.space.news frequently. why '\n 'does the shuttle roll just after liftoff? the following answer and '\n 'translation are provided by ken jenks ([email protected]). the '\n '\"ascent guidance and flight control training manual,\" asc g&c 2102, says: '\n '\"during the vertical rise phase, the launch pad attitude is commanded until '\n 'an i-loaded v(rel) sufficient to assure launch tower clearance is achieved. '\n 'then, the tilt maneuver (roll program) orients the vehicle to a heads down '\n 'attitude required to generate a negative q-alpha, which in turn alleviates '\n 'structural loading. other advantages with this attitude are performance '\n 'gain, decreased abort maneuver complexity, improved s-band look angles, and '\n 'crew view of the horizon. the tilt maneuver is also required to start '\n 'gaining downrange velocity to achieve the main engine cutoff (meco) target '\n 'in second stage.\" this really is a good answer, but it is couched in nasa '\n \"jargon. i'll try to interpret. 1) we wait until the shuttle clears the tower \"\n 'before rolling. 2) then, we roll the shuttle around so that the angle of '\n 'attack between the wind caused by passage through the atmosphere (the '\n '\"relative wind\") and the chord of the wings (the imaginary line between the '\n 'leading edge and the trailing edge) is a slightly negative angle (\"a '\n 'negative q-alpha\"). this causes a little bit of \"downward\" force (toward the '\n 'belly of the orbiter, or the +z direction) and this force \"alleviates '\n 'structural loading.\" we have to be careful about those wings -- they\\'re '\n 'about the most \"delicate\" part of the vehicle. 3) the new attitude (after '\n 'the roll) also allows us to carry more mass to orbit, or to achieve a higher '\n 'orbit with the same mass, or to change the orbit to a higher or lower '\n 'inclination than would be the case if we did not roll (\"performance gain\"). '\n '4) the new attitude allows the crew to fly a less complicated flight path if '\n 'they had to execute one of the more dangerous abort maneuvers, the return to '\n 'launch site (\"decreased abort maneuver complexity\"). 5) the new attitude '\n 'improves the ability for ground-based radio antennae to have a good '\n 'line-of-sight signal with the s-band radio antennae on the orbiter '\n '(\"improved s-band look angles\"). 6) the new attitude allows the crew to see '\n 'the horizon, which is a helpful (but not mandatory) part of piloting any '\n 'flying machine. 7) the new attitude orients the shuttle so that the body is '\n 'more nearly parallel with the ground, and the nose to the east (usually). '\n 'this allows the thrust from the engines to add velocity in the correct '\n 'direction to eventually achieve orbit. remember: velocity is a vector '\n 'quantity made of both speed and direction. the shuttle has to have a large '\n 'horizontal component to its velocity and a very small vertical component to '\n 'attain orbit. this all begs the question, \"why isn\\'t the launch pad '\n 'oriented to give this nice attitude to begin with? why does the shuttle need '\n 'to roll to achieve that attitude?\" the answer is that the pads were '\n 'leftovers from the apollo days. the shuttle straddles two flame trenches -- '\n 'one for the solid rocket motor exhaust, one for the space shuttle main '\n 'engine exhaust. (you can see the effects of this on any daytime launch. the '\n 'srm exhaust is dirty gray garbage, and the ssme exhaust is fluffy white '\n 'steam. watch for the difference between the \"top\" [orbiter side] and the '\n '\"bottom\" [external tank side] of the stack.) the access tower and other '\n 'support and service structure are all oriented basically the same way they '\n \"were for the saturn v's. (a side note: the saturn v's also had a roll \"\n 'program. do not ask me why -- i am a shuttle guy.) i checked with a buddy in '\n 'ascent dynamics. he added that the \"roll maneuver\" is really a maneuver in '\n 'all three axes: roll, pitch and yaw. the roll component of that maneuver is '\n 'performed for the reasons stated. the pitch component controls loading on '\n 'the wings by keeping the angle of attack (q-alpha) within a tight tolerance. '\n 'the yaw component is used to determine the orbital inclination. the total '\n 'maneuver is really expressed as a \"quaternion,\" a grad-level-math concept '\n 'for combining all three rotation matrices in one four-element array. how to '\n 'receive the nasa tv channel, nasa select nasa select is broadcast by '\n 'satellite. if you have access to a satellite dish, you can find select on '\n 'satcom f2r, transponder 13, c-band, 72 degrees west longitude, audio 6.8, '\n 'frequency 3960 mhz. f2r is stationed over the atlantic, and is increasingly '\n 'difficult to receive from california and points west. during events of '\n 'special interest (e.g. shuttle missions), select is sometimes broadcast on a '\n 'second satellite for these viewers. if you can not get a satellite feed, '\n \"some cable operators carry select. it is worth asking if yours doesn't. the \"\n 'select schedule is found in the nasa headline news which is frequently '\n 'posted to sci.space.news. generally it carries press conferences, briefings '\n 'by nasa officials, and live coverage of shuttle missions and planetary '\n 'encounters. select has recently begun carrying much more secondary material '\n '(associated with spacelink) when missions are not being covered. amateur '\n 'radio frequencies for shuttle missions the following are believed to '\n 'rebroadcast space shuttle mission audio: w6fxn - los angeles k6mf - ames '\n 'research center, mountain view, california wa3nan - goddard space flight '\n 'center (gsfc), greenbelt, maryland. w5rrr - johnson space center (jsc), '\n 'houston, texas w6vio - jet propulsion laboratory (jpl), pasadena, '\n 'california. w1aw voice bulletins station vhf 10m 15m 20m 40m 80m ------ '\n '------ ------ ------ ------ ----- ----- w6fxn 145.46 k6mf 145.585 7.165 '\n '3.840 wa3nan 147.45 28.650 21.395 14.295 7.185 3.860 w5rrr 146.64 28.400 '\n '21.350 14.280 7.227 3.850 w6vio 224.04 21.340 14.270 w6vio 224.04 21.280 '\n '14.282 7.165 3.840 w1aw 28.590 21.390 14.290 7.290 3.990 w5rrr transmits '\n 'mission audio on 146.64, a special event station on the other frequencies '\n 'supplying keplerian elements and mission information. w1aw also transmits on '\n '147.555, 18.160. no mission audio but they transmit voice bulletins at 0245 '\n 'and 0545 utc. frequencies in the 10-20m bands require usb and frequencies in '\n 'the 40 and 80m bands lsb. use fm for the vhf frequencies. [this item was '\n 'most recently updated courtesy of gary morris ([email protected], kk6yb, '\n 'n5qwc)] solid rocket booster fuel composition reference: \"shuttle flight '\n 'operations manual\" volume 8b - solid rocket booster systems, nasa document '\n 'jsc-12770 propellant composition (percent) ammonium perchlorate (oxidizer) '\n '69.6 aluminum 16 iron oxide (burn rate catalyst) 0.4 polybutadiene-acrilic '\n 'acid-acrylonitrile (a rubber) 12.04 epoxy curing agent 1.96 end reference '\n 'comment: the aluminum, rubber, and epoxy all burn with the oxidizer. next: '\n 'faq #10/15 - historical planetary probes')\n\nDominant Topic (0.384076) Keywords:\n[('key', 0.021244613688746368), ('space', 0.011991849550723185), ('system', 0.010789324247586598), ('information', 0.007799712730066473), ('technology', 0.007348765741390253), ('encryption', 0.006580485686608545), ('chip', 0.0056785917092561046), ('message', 0.005428065604435982), ('communication', 0.005327855162507934), ('security', 0.005327855162507934)]\n\nSecond Topic (0.178699) Keywords:\n[('line', 0.013409803597953457), ('power', 0.010707212411288991), ('work', 0.009139296913682126), ('high', 0.006106618253837267), ('low', 0.006024096385542169), ('ground', 0.006003465918468394), ('design', 0.005982835451394619), ('box', 0.005838422181878198), ('organization', 0.005735269846509325), ('wire', 0.005446443307476481)]\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nReview #616:\n('from: [email protected] subject: re: hismanal, et. al.--side effects '\n 'organization: wright state university lines: 22 in article '\n '<[email protected]>, [email protected] (steve dyer) writes: > in '\n 'article <[email protected]> [email protected] writes: >>can someone '\n 'tell me whether or not any of the following medications >>has been linked to '\n 'rapid/excessive weight gain and/or a distorted >>sense of taste or smell: '\n 'hismanal; azmacort (a topical steroid to >>prevent asthma); vancenase. > > '\n 'hismanal (astemizole) is most definitely linked to weight gain. > it really '\n 'is peculiar that some antihistamines have this effect, > and even more so an '\n \"antihistamine like astemizole which purportedly > doesn't cross the \"\n 'blood-brain barrier and so tends not to cause > drowsiness. it also gave me '\n 'lots of problems with joint and muscle pain. seemed to trigger '\n 'arthritis-like problems. sue > > -- > steve dyer > [email protected] '\n 'aka {ima,harvard,rayssd,linus,m2c}!spdcc!dyer')\n\nDominant Topic (0.436579) Keywords:\n[('study', 0.009525146386460254), ('science', 0.00770032886821208), ('drug', 0.0064369936632710355), ('problem', 0.005654929012593246), ('year', 0.005374187855939681), ('test', 0.005173658458329991), ('case', 0.005073393759525147), ('effect', 0.004872864361915457), ('time', 0.004652282024544798), ('result', 0.004652282024544798)]\n\nSecond Topic (0.094237) Keywords:\n[('write', 0.10022698810269255), ('article', 0.07386897307451472), ('line', 0.03563321853475266), ('organization', 0.03432216656230432), ('thing', 0.01903960551033187), ('post', 0.015791327489041954), ('good', 0.0127778647463995), ('opinion', 0.011779899812147778), ('bad', 0.010801502817783344), ('problem', 0.010488415779586726)]\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n"
]
],
[
[
"# Find the most representative documents in trainset for each topic\nFind the documents in trainset a given topic has contributed to the most, in order to infer what a topic is actually about.",
"_____no_output_____"
]
],
[
[
"def get_most_representative_docs(docs_text: List[str],\n docs_topics: List[List[Tuple[int, float]]],\n topic: int,\n limit: int = 5) -> pd.DataFrame:\n docs_dominant_topic = [\n sort_topic_proportions(doc_topics)[0]\n for doc_topics in docs_topics\n ]\n\n docs_topic_id, docs_topic_proportion = \\\n tuple(map(list, zip(*docs_dominant_topic)))\n\n df = pd.DataFrame(\n {\n 'raw_text': docs_text,\n 'topic_id': docs_topic_id,\n 'topic_proportion': docs_topic_proportion\n }\n ).groupby('topic_id').get_group(topic).sort_values(by='topic_proportion',\n ascending = False,\n ignore_index = True)\n \n return df.head(limit)",
"_____no_output_____"
],
[
"get_most_representative_docs(\n test_corpus_raw,\n test_corpus_topic_proportions,\n 0,\n 5\n)",
"_____no_output_____"
]
],
[
[
"# Topic distribution across documents\nThe distribution of topics across all documents in a corpus demonstrates how widely the topics are discussed.",
"_____no_output_____"
]
],
[
[
"def get_topics_contribution_in_corpus(\n docs_topics: List[List[Tuple[int, float]]]\n) -> pd.DataFrame:\n docs_dominant_topic = [\n sort_topic_proportions(doc_topics)[0][0]\n for doc_topics in docs_topics\n ]\n\n return pd.Series(\n docs_dominant_topic\n ).value_counts(normalize=True).sort_index()",
"_____no_output_____"
],
[
"ax = pd.DataFrame(\n {\n 'Trainset': get_topics_contribution_in_corpus(\n train_corpus_topic_proportions\n ),\n 'Testset': get_topics_contribution_in_corpus(\n test_corpus_topic_proportions\n )\n }\n).plot.bar(rot=0)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e722bfcf263d5550366743125545975d572b28c3 | 192,254 | ipynb | Jupyter Notebook | DS_Sprint_Challenge_5_Linear_Models.ipynb | cicbeast/DS-Unit-2-Linear-Models | bcda296b0a67f44752173deb2cab2e4667073d24 | [
"MIT"
] | null | null | null | DS_Sprint_Challenge_5_Linear_Models.ipynb | cicbeast/DS-Unit-2-Linear-Models | bcda296b0a67f44752173deb2cab2e4667073d24 | [
"MIT"
] | null | null | null | DS_Sprint_Challenge_5_Linear_Models.ipynb | cicbeast/DS-Unit-2-Linear-Models | bcda296b0a67f44752173deb2cab2e4667073d24 | [
"MIT"
] | null | null | null | 87.190023 | 25,336 | 0.785731 | [
[
[
"_Lambda School Data Science, Unit 2_\n \n# Linear Models Sprint Challenge: Predict home prices in Ames, Iowa 🏠💸\n\nTo demonstrate mastery on your Sprint Challenge, do all the required, numbered instructions in this notebook.\n\nTo earn a score of \"3\", also do all the stretch goals.\n\nFor your Sprint Challenge, you'll use historical housing data. There's a data dictionary at the bottom of the notebook. \n\nRun this code cell to load the dataset:\n\n\n\n",
"_____no_output_____"
]
],
[
[
"# First let's import\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\nimport seaborn as sns; sns.set()\nimport category_encoders as ce\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import StandardScaler \nfrom sklearn.model_selection import train_test_split\n%matplotlib inline",
"_____no_output_____"
],
[
"# Let's get our data\nURL = 'https://drive.google.com/uc?export=download&id=1522WlEW6HFss36roD_Cd9nybqSuiVcCK'\ndf = pd.read_csv(URL)\nassert df.shape == (2904, 47)",
"_____no_output_____"
],
[
"# I would like to see the features\nlist(df)",
"_____no_output_____"
]
],
[
[
"## 1. Do train/test split\nTrain on houses sold in the years 2006 - 2008. Test on houses sold in the years 2009 - 2010.",
"_____no_output_____"
]
],
[
[
"# Let's explore Yr_Sold\ndf['Yr_Sold'].describe()",
"_____no_output_____"
],
[
"# We can do this split with inequalities, don't need the function\ntrain = df[df['Yr_Sold'] < 2009]\ntest = df[df['Yr_Sold'] >= 2009]",
"_____no_output_____"
],
[
"# What kind of split did we get?\ntrain.shape, test.shape",
"_____no_output_____"
]
],
[
[
"## 2. Begin with baselines\n\nWhat is the Mean Absolute Error and R^2 score for a mean baseline?",
"_____no_output_____"
]
],
[
[
"# Let's calculate the mean for the baseline\ntspm = train['SalePrice'].mean()\ntspm",
"_____no_output_____"
],
[
"# Now we can use tspm to get our baseline\nytest = test['SalePrice']\nypred = np.full_like(ytest, fill_value=tspm)\n\nnp.set_printoptions(threshold=100)\nassert len(ytest) == len(ypred)\nprint(ypred)\nprint(f\"MAE: {mean_absolute_error(ytest, ypred)}\")\nprint(f\"R^2: {r2_score(ytest, ypred)}\")",
"[181515 181515 181515 ... 181515 181515 181515]\nMAE: 58276.60467479675\nR^2: -0.001791240523888682\n"
]
],
[
[
"## 3. Arrange data into X features matrix and y target vector\nSelect at least one numeric feature and at least one categorical feature.",
"_____no_output_____"
]
],
[
[
"train.describe(exclude='number').T",
"_____no_output_____"
],
[
"train.describe().T",
"_____no_output_____"
],
[
"# We'll use Bldg_Type and Lot_Area for our features\nfeats = ['Bldg_Type', 'Lot_Area']\ntarget = 'SalePrice'\n\nxtrain = train[feats]\nytrain = train[target]\n\nxtest = test[feats]\nytest = test[target]",
"_____no_output_____"
]
],
[
[
"## 4. Do one-hot encoding\n\nEncode your categorical feature(s).",
"_____no_output_____"
]
],
[
[
"# Now let's one hot encode Bldg_Type \nencoder = ce.OneHotEncoder(use_cat_names=True)\nencoded = encoder.fit_transform(train['Bldg_Type'])\n\nencoded.sample(20)",
"_____no_output_____"
]
],
[
[
"## 5. Use scikit-learn for Linear Regression\nFit your model.",
"_____no_output_____"
]
],
[
[
"# Now it's time to fit our model\n# We'll be combining the steps we did previously into a smooth workflow\n\n# First, Features and target\nfeats = ['Bldg_Type', 'Lot_Area']\ntarget = 'SalePrice'\n\nxtrain = train[feats]\nytrain = train[target]\n\nxtest = test[feats]\nytest = test[target]\n\n# Then, One Hot Encoding\nencoder = ce.OneHotEncoder(use_cat_names=True)\nxtrain = encoder.fit_transform(xtrain)\nxtest = encoder.fit_transform(xtest)\n\n# Finaly we can fit our model\nmodel = LinearRegression()\nmodel.fit(xtrain, ytrain)\nypred = model.predict(xtest)\n\nypred",
"_____no_output_____"
]
],
[
[
"## 6. Use regression metrics: MAE, R^2\nWhat is the Mean Absolute Error and R^2 score for your model? ***Beat the mean baseline!***",
"_____no_output_____"
]
],
[
[
"# Alright, let's see if we beat our baseline\nprint('MAE:', mean_absolute_error(ytest, ypred))\nprint('R2 Score:', r2_score(ytest, ypred))",
"MAE: 54685.2686106037\nR2 Score: 0.0892944150748256\n"
],
[
"# SUCCESS!!!...if just barely",
"_____no_output_____"
]
],
[
[
"## 7. Get coefficients of a linear model\nPrint or plot the coefficients for the features in your model.",
"_____no_output_____"
]
],
[
[
"# Now let's show our coefficients\npd.Series(model.coef_, xtrain.columns)",
"_____no_output_____"
],
[
"# We can also plot our coefficients\ncoefs = pd.Series(model.coef_, xtrain.columns)\ncoefs.sort_values().plot.barh()",
"_____no_output_____"
]
],
[
[
"## Stretch Goals\n- Try at least 3 different feature combinations.\n- Plot exploratory visualizations.\n- Get regression metrics RMSE, MAE, and $R^2$, for both the train and test data.",
"_____no_output_____"
]
],
[
[
"# Admittedly, we can do better with our MAE and R^2. Let's try again\n# First, Features and target\nfeats = [\n 'Bedroom_AbvGr', \n 'Full_Bath',\n 'Central_Air',\n 'Kitchen_Qual',\n ]\ntarget = 'SalePrice'\n\nxtrain = train[feats]\nytrain = train[target]\n\nxtest = test[feats]\nytest = test[target]\n\n# Then, One Hot Encoding\nencoder = ce.OneHotEncoder(use_cat_names=True)\nxtrain = encoder.fit_transform(xtrain)\nxtest = encoder.fit_transform(xtest)\n\n# # Finaly we can fit our model\n# model = LinearRegression()\n# model.fit(xtrain, ytrain)\n# ypred = model.predict(xtest)\n\n# ypred",
"_____no_output_____"
],
[
"list(xtrain)",
"_____no_output_____"
],
[
"list(xtest)",
"_____no_output_____"
],
[
"# Ok, can't use Kitchen_Qual\n# First, Features and target\nfeats = [\n 'Bedroom_AbvGr', \n 'Full_Bath',\n 'Central_Air',\n 'Exter_Qual',\n ]\ntarget = 'SalePrice'\n\nxtrain = train[feats]\nytrain = train[target]\n\nxtest = test[feats]\nytest = test[target]\n\n# Then, One Hot Encoding\nencoder = ce.OneHotEncoder(use_cat_names=True)\nxtrain = encoder.fit_transform(xtrain)\nxtest = encoder.fit_transform(xtest)\n\n# Finaly we can fit our model\nmodel = LinearRegression()\nmodel.fit(xtrain, ytrain)\nypred = model.predict(xtest)\n\nypred",
"_____no_output_____"
],
[
"# Alright, let's see if there is any improvement\nprint('MAE:', mean_absolute_error(ytest, ypred))\nprint('R2 Score:', r2_score(ytest, ypred))",
"MAE: 150913.31687521352\nR2 Score: -3.7086775826412177\n"
],
[
"list(xtrain)",
"_____no_output_____"
],
[
"# That was horrible, let's graph our coefficients\ncoefs = pd.Series(model.coef_, xtrain.columns)\ncoefs.sort_values().plot.barh()",
"_____no_output_____"
],
[
"# Alright, let's try again\n# First, Features and target\nfeats = [\n 'Bedroom_AbvGr', \n 'Full_Bath',\n 'Overall_Cond',\n 'Overall_Qual',\n ]\ntarget = 'SalePrice'\n\nxtrain = train[feats]\nytrain = train[target]\n\nxtest = test[feats]\nytest = test[target]\n\n# # Then, One Hot Encoding\n# encoder = ce.OneHotEncoder(use_cat_names=True)\n# xtrain = encoder.fit_transform(xtrain)\n# xtest = encoder.fit_transform(xtest)\n\n# Finaly we can fit our model\nmodel = LinearRegression()\nmodel.fit(xtrain, ytrain)\nypred = model.predict(xtest)\n\nypred",
"_____no_output_____"
],
[
"# Alright, let's see if there is any improvement\nprint('MAE:', mean_absolute_error(ytest, ypred))\nprint('R2 Score:', r2_score(ytest, ypred))",
"MAE: 32733.7777407947\nR2 Score: 0.6634442653877481\n"
],
[
"# Huge improvement!!! Let's graph our coefficients\ncoefs = pd.Series(model.coef_, xtrain.columns)\ncoefs.sort_values().plot.barh()",
"_____no_output_____"
],
[
"# Let's take a look at the features themselves\nfor feature in feats:\n sns.lmplot(x=feature, y=target, data=df)",
"_____no_output_____"
],
[
"# And we can now show all of our required error values\n\n# First the test set\nmae_test = mean_absolute_error(ytest, ypred)\nmse_test = mean_squared_error(ytest, ypred)\nrms_test = np.sqrt(mse_test)\nr2_test = r2_score(ytest, ypred)\n\nprint('For out Test Set:',\n '\\nMean Absolute Error = ', mae_test,\n '\\nRoot Mean Squared Error = ', rms_test,\n '\\nR-Squared Error = ', r2_test\n )",
"For out Test Set: \nMean Absolute Error = 32733.7777407947 \nRoot Mean Squared Error = 45791.522621739416 \nR-Squared Error = 0.6634442653877481\n"
],
[
"# And for the Training set\nypred = model.predict(xtrain)\n\nmae_train = mean_absolute_error(ytrain, ypred)\nmse_train = mean_squared_error(ytrain, ypred)\nrms_train = np.sqrt(mse_train)\nr2_train = r2_score(ytrain, ypred)\n\nprint('For out Training Set:',\n '\\nMean Absolute Error = ', mae_train,\n '\\nRoot Mean Squared Error = ', rms_train,\n '\\nR-Squared Error = ', r2_train\n )",
"For out Training Set: \nMean Absolute Error = 32760.7788749927 \nRoot Mean Squared Error = 46684.28721158147 \nR-Squared Error = 0.6611689835684331\n"
]
],
[
[
"## Data Dictionary \n\nHere's a description of the data fields:\n\n```\n1st_Flr_SF: First Floor square feet\n\nBedroom_AbvGr: Bedrooms above grade (does NOT include basement bedrooms)\n\nBldg_Type: Type of dwelling\n\t\t\n 1Fam\tSingle-family Detached\t\n 2FmCon\tTwo-family Conversion; originally built as one-family dwelling\n Duplx\tDuplex\n TwnhsE\tTownhouse End Unit\n TwnhsI\tTownhouse Inside Unit\n \nBsmt_Half_Bath: Basement half bathrooms\n\nBsmt_Full_Bath: Basement full bathrooms\n\nCentral_Air: Central air conditioning\n\n N\tNo\n Y\tYes\n\t\t\nCondition_1: Proximity to various conditions\n\t\n Artery\tAdjacent to arterial street\n Feedr\tAdjacent to feeder street\t\n Norm\tNormal\t\n RRNn\tWithin 200' of North-South Railroad\n RRAn\tAdjacent to North-South Railroad\n PosN\tNear positive off-site feature--park, greenbelt, etc.\n PosA\tAdjacent to postive off-site feature\n RRNe\tWithin 200' of East-West Railroad\n RRAe\tAdjacent to East-West Railroad\n\t\nCondition_2: Proximity to various conditions (if more than one is present)\n\t\t\n Artery\tAdjacent to arterial street\n Feedr\tAdjacent to feeder street\t\n Norm\tNormal\t\n RRNn\tWithin 200' of North-South Railroad\n RRAn\tAdjacent to North-South Railroad\n PosN\tNear positive off-site feature--park, greenbelt, etc.\n PosA\tAdjacent to postive off-site feature\n RRNe\tWithin 200' of East-West Railroad\n RRAe\tAdjacent to East-West Railroad\n \n Electrical: Electrical system\n\n SBrkr\tStandard Circuit Breakers & Romex\n FuseA\tFuse Box over 60 AMP and all Romex wiring (Average)\t\n FuseF\t60 AMP Fuse Box and mostly Romex wiring (Fair)\n FuseP\t60 AMP Fuse Box and mostly knob & tube wiring (poor)\n Mix\tMixed\n \n Exter_Cond: Evaluates the present condition of the material on the exterior\n\t\t\n Ex\tExcellent\n Gd\tGood\n TA\tAverage/Typical\n Fa\tFair\n Po\tPoor\n \n Exter_Qual: Evaluates the quality of the material on the exterior \n\t\t\n Ex\tExcellent\n Gd\tGood\n TA\tAverage/Typical\n Fa\tFair\n Po\tPoor\n\t\t\nExterior_1st: Exterior covering on house\n\n AsbShng\tAsbestos Shingles\n AsphShn\tAsphalt Shingles\n BrkComm\tBrick Common\n BrkFace\tBrick Face\n CBlock\tCinder Block\n CemntBd\tCement Board\n HdBoard\tHard Board\n ImStucc\tImitation Stucco\n MetalSd\tMetal Siding\n Other\tOther\n Plywood\tPlywood\n PreCast\tPreCast\t\n Stone\tStone\n Stucco\tStucco\n VinylSd\tVinyl Siding\n Wd Sdng\tWood Siding\n WdShing\tWood Shingles\n\t\nExterior_2nd: Exterior covering on house (if more than one material)\n\n AsbShng\tAsbestos Shingles\n AsphShn\tAsphalt Shingles\n BrkComm\tBrick Common\n BrkFace\tBrick Face\n CBlock\tCinder Block\n CemntBd\tCement Board\n HdBoard\tHard Board\n ImStucc\tImitation Stucco\n MetalSd\tMetal Siding\n Other\tOther\n Plywood\tPlywood\n PreCast\tPreCast\n Stone\tStone\n Stucco\tStucco\n VinylSd\tVinyl Siding\n Wd Sdng\tWood Siding\n WdShing\tWood Shingles\n \nFoundation: Type of foundation\n\t\t\n BrkTil\tBrick & Tile\n CBlock\tCinder Block\n PConc\tPoured Contrete\t\n Slab\tSlab\n Stone\tStone\n Wood\tWood\n\t\t\nFull_Bath: Full bathrooms above grade\n\nFunctional: Home functionality (Assume typical unless deductions are warranted)\n\n Typ\tTypical Functionality\n Min1\tMinor Deductions 1\n Min2\tMinor Deductions 2\n Mod\tModerate Deductions\n Maj1\tMajor Deductions 1\n Maj2\tMajor Deductions 2\n Sev\tSeverely Damaged\n Sal\tSalvage only\n\t\t\nGr_Liv_Area: Above grade (ground) living area square feet\n \nHalf_Bath: Half baths above grade\n\nHeating: Type of heating\n\t\t\n Floor\tFloor Furnace\n GasA\tGas forced warm air furnace\n GasW\tGas hot water or steam heat\n Grav\tGravity furnace\t\n OthW\tHot water or steam heat other than gas\n Wall\tWall furnace\n\t\t\nHeating_QC: Heating quality and condition\n\n Ex\tExcellent\n Gd\tGood\n TA\tAverage/Typical\n Fa\tFair\n Po\tPoor\n\nHouse_Style: Style of dwelling\n\t\n 1Story\tOne story\n 1.5Fin\tOne and one-half story: 2nd level finished\n 1.5Unf\tOne and one-half story: 2nd level unfinished\n 2Story\tTwo story\n 2.5Fin\tTwo and one-half story: 2nd level finished\n 2.5Unf\tTwo and one-half story: 2nd level unfinished\n SFoyer\tSplit Foyer\n SLvl\tSplit Level\n\nKitchen_AbvGr: Kitchens above grade\n\nKitchen_Qual: Kitchen quality\n\n Ex\tExcellent\n Gd\tGood\n TA\tTypical/Average\n Fa\tFair\n Po\tPoor\n\nLandContour: Flatness of the property\n\n Lvl\tNear Flat/Level\t\n Bnk\tBanked - Quick and significant rise from street grade to building\n HLS\tHillside - Significant slope from side to side\n Low\tDepression\n\t\t\nLand_Slope: Slope of property\n\t\t\n Gtl\tGentle slope\n Mod\tModerate Slope\t\n Sev\tSevere Slope\n\nLot_Area: Lot size in square feet\n\nLot_Config: Lot configuration\n\n Inside\tInside lot\n Corner\tCorner lot\n CulDSac\tCul-de-sac\n FR2\tFrontage on 2 sides of property\n FR3\tFrontage on 3 sides of property\n\nLot_Shape: General shape of property\n\n Reg\tRegular\t\n IR1\tSlightly irregular\n IR2\tModerately Irregular\n IR3\tIrregular\n\nMS_SubClass: Identifies the type of dwelling involved in the sale.\t\n\n 20\t1-STORY 1946 & NEWER ALL STYLES\n 30\t1-STORY 1945 & OLDER\n 40\t1-STORY W/FINISHED ATTIC ALL AGES\n 45\t1-1/2 STORY - UNFINISHED ALL AGES\n 50\t1-1/2 STORY FINISHED ALL AGES\n 60\t2-STORY 1946 & NEWER\n 70\t2-STORY 1945 & OLDER\n 75\t2-1/2 STORY ALL AGES\n 80\tSPLIT OR MULTI-LEVEL\n 85\tSPLIT FOYER\n 90\tDUPLEX - ALL STYLES AND AGES\n 120\t1-STORY PUD (Planned Unit Development) - 1946 & NEWER\n 150\t1-1/2 STORY PUD - ALL AGES\n 160\t2-STORY PUD - 1946 & NEWER\n 180\tPUD - MULTILEVEL - INCL SPLIT LEV/FOYER\n 190\t2 FAMILY CONVERSION - ALL STYLES AND AGES\n\nMS_Zoning: Identifies the general zoning classification of the sale.\n\t\t\n A\tAgriculture\n C\tCommercial\n FV\tFloating Village Residential\n I\tIndustrial\n RH\tResidential High Density\n RL\tResidential Low Density\n RP\tResidential Low Density Park \n RM\tResidential Medium Density\n\nMas_Vnr_Type: Masonry veneer type\n\n BrkCmn\tBrick Common\n BrkFace\tBrick Face\n CBlock\tCinder Block\n None\tNone\n Stone\tStone\n\nMo_Sold: Month Sold (MM)\n\nNeighborhood: Physical locations within Ames city limits\n\n Blmngtn\tBloomington Heights\n Blueste\tBluestem\n BrDale\tBriardale\n BrkSide\tBrookside\n ClearCr\tClear Creek\n CollgCr\tCollege Creek\n Crawfor\tCrawford\n Edwards\tEdwards\n Gilbert\tGilbert\n IDOTRR\tIowa DOT and Rail Road\n MeadowV\tMeadow Village\n Mitchel\tMitchell\n Names\tNorth Ames\n NoRidge\tNorthridge\n NPkVill\tNorthpark Villa\n NridgHt\tNorthridge Heights\n NWAmes\tNorthwest Ames\n OldTown\tOld Town\n SWISU\tSouth & West of Iowa State University\n Sawyer\tSawyer\n SawyerW\tSawyer West\n Somerst\tSomerset\n StoneBr\tStone Brook\n Timber\tTimberland\n Veenker\tVeenker\n\t\t\t\nOverall_Cond: Rates the overall condition of the house\n\n 10\tVery Excellent\n 9\tExcellent\n 8\tVery Good\n 7\tGood\n 6\tAbove Average\t\n 5\tAverage\n 4\tBelow Average\t\n 3\tFair\n 2\tPoor\n 1\tVery Poor\n\nOverall_Qual: Rates the overall material and finish of the house\n\n 10\tVery Excellent\n 9\tExcellent\n 8\tVery Good\n 7\tGood\n 6\tAbove Average\n 5\tAverage\n 4\tBelow Average\n 3\tFair\n 2\tPoor\n 1\tVery Poor\n\nPaved_Drive: Paved driveway\n\n Y\tPaved \n P\tPartial Pavement\n N\tDirt/Gravel\n\nRoof_Matl: Roof material\n\n ClyTile\tClay or Tile\n CompShg\tStandard (Composite) Shingle\n Membran\tMembrane\n Metal\tMetal\n Roll\tRoll\n Tar&Grv\tGravel & Tar\n WdShake\tWood Shakes\n WdShngl\tWood Shingles\n\nRoof_Style: Type of roof\n\n Flat\tFlat\n Gable\tGable\n Gambrel\tGabrel (Barn)\n Hip\tHip\n Mansard\tMansard\n Shed\tShed\n\nSalePrice: the sales price for each house\n\nSale_Condition: Condition of sale\n\n Normal\tNormal Sale\n Abnorml\tAbnormal Sale - trade, foreclosure, short sale\n AdjLand\tAdjoining Land Purchase\n Alloca\tAllocation - two linked properties with separate deeds, typically condo with a garage unit\t\n Family\tSale between family members\n Partial\tHome was not completed when last assessed (associated with New Homes)\n\nSale_Type: Type of sale\n\t\t\n WD \tWarranty Deed - Conventional\n CWD\tWarranty Deed - Cash\n VWD\tWarranty Deed - VA Loan\n New\tHome just constructed and sold\n COD\tCourt Officer Deed/Estate\n Con\tContract 15% Down payment regular terms\n ConLw\tContract Low Down payment and low interest\n ConLI\tContract Low Interest\n ConLD\tContract Low Down\n Oth\tOther\n\t\nStreet: Type of road access to property\n\n Grvl\tGravel\t\n Pave\tPaved\n \t\nTotRms_AbvGrd: Total rooms above grade (does not include bathrooms)\n\nUtilities: Type of utilities available\n\t\t\n AllPub\tAll public Utilities (E,G,W,& S)\t\n NoSewr\tElectricity, Gas, and Water (Septic Tank)\n NoSeWa\tElectricity and Gas Only\n ELO\tElectricity only\t\n\t\nYear_Built: Original construction date\n\nYear_Remod/Add: Remodel date (same as construction date if no remodeling or additions)\n\t\t\t\t\t\t\nYr_Sold: Year Sold (YYYY)\t\n\n```",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e722c338b13821c3b284941d6c04fc5f3b22ae0c | 689 | ipynb | Jupyter Notebook | scripts/sgan/Untitled.ipynb | sapan-ostic/deep_prediction | e4709e4a66477755e6afe39849597ae1e3e969b5 | [
"MIT"
] | 26 | 2020-04-06T18:11:51.000Z | 2022-03-26T02:53:10.000Z | scripts/sgan/Untitled.ipynb | sapan-ostic/deep_prediction | e4709e4a66477755e6afe39849597ae1e3e969b5 | [
"MIT"
] | 5 | 2020-04-03T00:07:20.000Z | 2022-01-13T03:20:21.000Z | scripts/sgan/Untitled.ipynb | sapan-ostic/deep_prediction | e4709e4a66477755e6afe39849597ae1e3e969b5 | [
"MIT"
] | 6 | 2020-06-02T14:51:22.000Z | 2021-08-02T12:47:54.000Z | 16.404762 | 34 | 0.509434 | [
[
[
"from data import *",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code"
]
] |
e722c4536e52223d9aecc67e06718953287f2074 | 242,202 | ipynb | Jupyter Notebook | soluciones/g.gonzalezp/tarea4/GabrielGonzalez_tarea4.ipynb | policelula/FISI2028-202120 | fa3578d74a79b395ac03cddc1d44fba2fa5ae1fc | [
"MIT"
] | null | null | null | soluciones/g.gonzalezp/tarea4/GabrielGonzalez_tarea4.ipynb | policelula/FISI2028-202120 | fa3578d74a79b395ac03cddc1d44fba2fa5ae1fc | [
"MIT"
] | null | null | null | soluciones/g.gonzalezp/tarea4/GabrielGonzalez_tarea4.ipynb | policelula/FISI2028-202120 | fa3578d74a79b395ac03cddc1d44fba2fa5ae1fc | [
"MIT"
] | null | null | null | 152.616257 | 23,904 | 0.873209 | [
[
[
"import numpy as np\nimport pandas as pd\nimport scipy as sp\nimport sklearn as sl\nimport time\n\nimport seaborn as sns; sns.set()\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import axes3d\nfrom matplotlib import cm\n",
"_____no_output_____"
]
],
[
[
"# Tarea 3: Encuentre la regresión\n\nUd recibe unos datos $x$ y $y$ cómo se muestran a continuación. Ud debe responder cuatro preguntas a partir de estos datos. Suponga que ud tiene un modelo tal que $y=f(x)$ más aún desconoce $f$.",
"_____no_output_____"
]
],
[
[
"df = pd.read_pickle('ex1.gz')\nsns.scatterplot(x='x',y='y',data=df)\nplt.show()\ndf\n",
"_____no_output_____"
]
],
[
[
"## (A) Pendiente e intercepto\nDetermine la pendiente de los datos en el intervalo $[0,1.5]$ y el valor del intercepto con el eje $y$. Es decir, $f(0)=?$. ¿Cuál es el valor de $r^2$?",
"_____no_output_____"
]
],
[
[
"x = df[\"x\"].to_numpy().reshape(-1,1)\ny = df[\"y\"].to_numpy().reshape(-1,1)\n\n\nlx = []\nly = []\nlx2 = []\nly2 = []\ne_y = []\nfor i in range(len(x)):\n if x[i]<=1.5 :\n lx.append(x[i])\n ly.append(y[i])\n else:\n if y[i]!=0:\n lx2.append(x[i])\n ly2.append(y[i])\n e_y.append(np.log(y[i]))\n \n \nx_a = np.array(lx).reshape(-1,1)\ny_a = np.array(ly).reshape(-1,1)\nx_b = np.array(lx2).reshape(-1,1)\ny_b = np.array(ly2).reshape(-1,1)\nf_x = np.array(e_y).reshape(-1,1)\n \n\n\n\n\nP = np.array([np.ones([len(x_a), 1]) , x_a]).reshape(2,len(x_a)).T\ncoeffs = np.linalg.inv(P.T @ P) @ P.T @ y_a\nb, m = coeffs\nf_ajuste = b + m*x_a\n\n\n\nP2 = np.array([np.ones([len(x_b), 1]) , x_b]).reshape(2,len(x_b)).T\ncoeffs2 = np.linalg.inv(P2.T @ P2) @ P2.T @ f_x\nb2, m2 = coeffs2\nf_ajuste_lineal2 = b2 + m2*x_b\nf_ajuste2 = np.exp(b2 + m2*x_b)\n\n\n\nplt.plot(x_a, y_a, 'bo')\nplt.plot(x_a,f_ajuste,'r')\nplt.plot(x_b, y_b, 'bo')\nplt.plot(x_b,f_ajuste2,'r')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.show()\n\n\n\ndiv = len(x_a)\ns_x = sum(x_a)\ns_y = sum(y_a)\ns_xy = sum(x_a*y_a)\ns_xcu = sum(x_a*x_a)\ns_ycu = sum(y_a*y_a)\nprom_x = s_x/div\nprom_y = s_y/div\n\nsigma_x = np.sqrt((s_xcu/div) - prom_x*prom_x)\nsigma_y = np.sqrt(s_ycu/div - prom_y*prom_y)\n\ncov = (s_xy/div) - (prom_x*prom_y)\nrr = (cov/(sigma_x*sigma_y))*(cov/(sigma_x*sigma_y))\n\n\n\n\n\nprint('De 0 a 1.5, el valor de la pendiente es: ', m)\nprint('El valor del intercepto, es decir f(0) es: ', b)\nprint('El valor de r^2 es: ', rr)\n\n\n\n\n\n\n\n\n\n\n",
"_____no_output_____"
]
],
[
[
"\n\n\n\n\n\n\n\n## (B) Regresión polinomial\nSuponga que quiere realizar la siguiente regresión polinomial,\n$$y=\\beta_1+\\beta_2x+\\beta_2x^2+\\beta_2x^3+\\beta_2x^4+\\beta_2x^5.$$\nPlantee la función de costo que le permita calcular los coeficientes y calcule $\\beta_1$, $\\beta_2$, $\\beta_3$, $\\beta_4$, y $\\beta_5$. ¿Cuál es el $r^2$?\n\nCalcule $f(0)$ y compare con los resultados anteriores\n\n\n",
"_____no_output_____"
]
],
[
[
"\nx = df[\"x\"]\ny = df[\"y\"]\n\nx_a = np.array(lx)\ny_a = np.array(ly)\n\n\nlista = []\nfor i in range(len(x)):\n lista.append([1, x[i], x[i]*x[i], x[i]*x[i]*x[i], x[i]*x[i]*x[i]*x[i], x[i]*x[i]*x[i]*x[i]*x[i]])\n\n \nMbg = np.matrix(lista)\nb = np.array([y]).reshape(-1,1)\nMb = np.matrix(b)\n\n\ndef L_cost(k ,Mbg ,Mb):\n \n m,n = Mbg.shape\n X = np.matrix(k).T\n DeltaB=(Mbg*X - Mb) \n return (DeltaB.T*DeltaB)[0,0]/m \n \n\nah1 = sp.optimize.minimize(fun=L_cost,x0=np.zeros(Mbg.shape[1]), args = (Mbg,Mb), tol=1e-10)\nah1['x']\n\n\ncons = np.linspace(0,4,100)\n\ndef Polinomio(a_5,a_4,a_3,a_2,a_1,a_0,var):\n return a_0 + a_1*var +a_2*var*var + a_3*var*var*var+ a_4*var*var*var*var + a_5*var*var*var*var*var \n\n\nf = Polinomio(ah1['x'][5],ah1['x'][4],ah1['x'][3],ah1['x'][2],ah1['x'][1],ah1['x'][0],cons)\nrr = 1-np.sum((f - y)**2)/np.sum((y-y.mean())**2)\n\n\nsns.scatterplot(x ='x', y ='y',data=df)\nplt.plot(x,f,\"-\", color='r')\nplt.show()\n\nprint('Beta_1: ',ah1['x'][1])\nprint('Beta_2: ',ah1['x'][2])\nprint('Beta_3: ',ah1['x'][3])\nprint('Beta_4: ',ah1['x'][4])\nprint('Beta_5: ',ah1['x'][5])\n\nprint()\nprint()\nprint('Valor de costo: ',L_cost(ah1['x'],Mbg,Mb))\nprint('El valor de r^2 es: ',rr, '. El valor de r^2 es bastante cercano a 1, por lo que la función dada presenta un buen ajuste') \nprint('Valor de F(0): ',f[0])\n\n\n\n\n",
"_____no_output_____"
]
],
[
[
"## (C) Regresión polinomial exacta\nResulta, que cuando se quiere hacer alguna regresión polinomial esta se puede hacer de forma exacta. ¿Cómo? Suponga que ud va a considerar que su problema en lugar de tener $1$ variable ($x$) tiene $n+1$, siendo $n$ el orden del polinomio a ajustar. Es decir, sus nuevas variables van a ser $\\{x_0,\\,x_1,\\,x_2,\\,x_3,\\dots,\\,x_n\\}$ definiendo $x_j=x^j$. Así pues, siguiendo el mismo procedimiento para la regresión lineal multidimensional que realizamos para el ejercicio de datos inmobiliarios, puede encontrar los valores de los coeficientes $\\beta_1$, $\\beta_2$, $\\beta_3$, $\\beta_4$, y $\\beta_5$. Encuentre estos valores y compare con los resultados en la sección **(B)**.\n\nCalcule $f(0)$ y compare con los resultados anteriores.\n\n> Si ud se pregunta si esto es posible la respuesta es sí. Inclusive, esto se puede extender a cualquier a cualquier conjunto de funciones, tal que $x_j=f_j(x)$, que represente un conjunto \"linealmente independiente\" (¡Me estoy adelantando a *Fourier*!). Para quienes quieran explorar algunas curiosidades matemáticas, cuando $n+1$ es igual al número de puntos o valores de $x$ (y todos diferentes) la matriz es siempre invertible y resulta ser la inversa de una matriz de Vandermonde.",
"_____no_output_____"
]
],
[
[
"Y = df.loc[:, ['y']]\n\nY\n",
"_____no_output_____"
],
[
"\ny, type(y), Y, type(Y)",
"_____no_output_____"
],
[
"x = df[\"x\"]\ny = df[\"y\"]\n\n\narreglo_x = np.array(x).reshape(-1, 1)\narreglo_y = np.array(y).reshape(-1, 1)\n\nP3 = np.array([np.ones([len(x), 1]), arreglo_x, arreglo_x**2, arreglo_x**3, arreglo_x**4, arreglo_x**5]).reshape(6, len(x)).T\ncoeffs = np.linalg.inv(P3.T @ P3) @ P3.T @ arreglo_y\na0, a1, a2, a3, a4, a5 = coeffs\nf_ajuste3 = a0 + (a1*arreglo_x) + (a2*arreglo_x*arreglo_x) + (a3*arreglo_x*arreglo_x*arreglo_x) + (a4*arreglo_x*arreglo_x*arreglo_x*arreglo_x) + (a5*arreglo_x*arreglo_x*arreglo_x*arreglo_x*arreglo_x) \n\n\nplt.figure()\nsns.scatterplot(x='x',y='y',data = df)\nplt.plot(arreglo_x, f_ajuste3, c ='r')\nplt.ylabel('y')\nplt.xlabel('x')\nplt.show()\n\n\nprint('Beta_1: ',coeffs.tolist()[1][0])\nprint('Beta_2: ',coeffs.tolist()[2][0])\nprint('Beta_3: ',coeffs.tolist()[3][0])\nprint('Beta_4: ',coeffs.tolist()[4][0])\nprint('Beta_5: ',coeffs.tolist()[5][0])\nprint('F(0): ',coeffs.tolist()[0][0])",
"_____no_output_____"
],
[
"X = df.loc[:, ['x']].rename(columns={'x': 'x1'})\nX.insert(0, 'x0', 1)\nX['x2'] = X['x1']*X['x1']\n\nX",
"_____no_output_____"
],
[
"x, type(x), X, type(X)",
"_____no_output_____"
]
],
[
[
"## (D) Regresión a un modelo teórico\n\nSuponga que su modelo teórico es el siguiente:\n$$y=\\frac{a}{\\left[(x-b)^2+c\\right]^\\gamma}.$$\nHalle $a$, $b$, $c$ y $\\gamma$.\n\nCalcule $f(0)$ y compare con los resultados anteriores",
"_____no_output_____"
]
],
[
[
"x = df[\"x\"]\ny = df[\"y\"]\n\n\nlx = []\nly = []\nfor i in range(len(x)):\n if x[i]<=1.5 :\n lx.append(x[i])\n ly.append(y[i])\n \n \nx_a = np.array(lx)\ny_a = np.array(ly)\n\ndef f(vec,x_a): \n return (vec[0])/((x_a-vec[1])**2 + vec[2])**vec[3]\n\ndef L_ajuste(vec,x_a,y_a): \n deltaY=f(vec,x_a) - y_a\n return np.dot(deltaY,deltaY)/len(y_a)\n\n\nres2 = sp.optimize.minimize(fun=L_ajuste, x0=np.array([0,1,0,0]), args = (x_a,y_a), method='L-BFGS-B', tol=1e-8)\nb = f(res2.x,0)\n\n\nplt.figure()\nplt.scatter(x,y, label = \"Datos\")\nplt.plot(x,f(res2.x,x), c = 'r', label = \"Ajuste\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.show()\n\n\nprint('a: ',res2[\"x\"][0])\nprint('b: ', res2[\"x\"][1])\nprint('c: ',res2[\"x\"][2])\nprint('gama: ',res2[\"x\"][3])\n\nprint('Finalmente, F(0) es: ',b, ', con buena aproximacion a los valores anteriormente reportados')\n\n\n\n\n",
"_____no_output_____"
]
],
[
[
"# Tarea 4\n\nCon base a los métodos vistos en clase resuelva las siguientes dos preguntas",
"_____no_output_____"
],
[
"## (A) Integrales\n\n* $\\int_{0}^{1}x^{-1/2}\\,\\text{d}x$\n* $\\int_{0}^{\\infty}e^{-x}\\ln{x}\\,\\text{d}x$\n* $\\int_{0}^{\\infty}\\frac{\\sin{x}}{x}\\,\\text{d}x$",
"_____no_output_____"
]
],
[
[
"#Cuadraturas gaussianas\n\n\n\n#(1) Vandermonde Matrix\n\nx_ini = 1/2\nx_fin = 1\nx_fin_2 = 10\nnodos = 11\n\nX = np.linspace(x_ini,x_fin, nodos)\nX2 = np.linspace(x_ini,x_fin_2, nodos)\n\n\nV = np.matrix([X**i for i in range(len(X))] )\nV_inv = np.linalg.inv(V)\n\n\n\nV2 = np.matrix([X2**i for i in range(len(X2))] )\nV2_inv = np.linalg.inv(V2)\n\n\n\n\nI = np.matrix([ ( ( x_fin**(n+1) - x_ini**(n+1) ) /(n+1) ) for n in range(len(X)) ]).T\nI2 = np.matrix([ ( ( x_fin_2**(n+1) - x_ini**(n+1) ) /(n+1) ) for n in range(len(X2)) ]).T\n\n\ndef f(x):\n return x**(-1/2)\n\ndef g(x):\n return np.exp(-x)*np.log(x)\n\ndef h(x):\n return np.sin(x)/x\n\n\nvec_f = np.matrix([ f(X[i]) for i in range(len(X))] ).T\nvec_g = np.matrix([ g(X2[i]) for i in range(len(X2))] ).T\nvec_h = np.matrix([ h(X2[i]) for i in range(len(X2))] ).T\n\n\n\n\n#print(X)\n#print(V)\n#print(V_inv)\n#print(I)\n#print(vec_f)\n#print(vec_g)\n#print(vec_h)\n\n#print(vec_f.shape)\n#print(vec_g.shape)\n#print(vec_h.shape)\n\n\nprint(\"El calculo de la primera integral es: \", (vec_f.T*V_inv*I)[0,0])\nprint(\"El calculo de la segunda integral es: \", (vec_g.T*V2_inv*I)[0,0])\nprint(\"El calculo de la tercera integral es: \", (vec_h.T*V_inv*I)[0,0])\n\n\n\n\n\n\n\n",
"El calculo de la primera integral es: 0.5857855909801515\nEl calculo de la segunda integral es: -0.08835991357603967\nEl calculo de la tercera integral es: 0.061327572679147124\n"
],
[
"#Simpson\n\ninicio = time.time()\n\nx_f_ini = 0.000001\nx_f_fin = 1\nx_ini =0.000001\nx_fin =100\nnodos=1000001\n\n\ndef f(x):\n return x**(-1/2)\n\ndef g(x):\n return np.exp(-x)*np.log(x)\n\ndef h(x):\n return np.sin(x)/x\n\n\ndef simpson_integrate(desde, hasta, nodos, f):\n x, delta_x = np.linspace( desde, hasta, num=nodos-1 , retstep=True )\n return (delta_x/3)*( f(x[0]) + 2*np.sum(f(x[2:len(x)-1:2])) + 4*np.sum(f(x[1::2])) + f(x[-1]) )\n\n\n\n \nintegral_f = simpson_integrate(x_f_ini, x_f_fin, nodos, f) \nintegral_g = simpson_integrate(x_ini, x_fin, nodos, g)\nintegral_h = simpson_integrate(x_ini, x_fin, nodos, h)\n\n\n\nprint(f\"El calculo de la primera integral es {integral_f}\")\nprint(f\"El calculo de la segunda integral es {integral_g}\")\nprint(f\"El calculo de la tercera integral es {integral_h}\")\n\ntime.sleep(0)\n\n\n\nfin = time.time()\n\nprint(\"Tiempo de ejecución: \",fin-inicio, \"s\")\n\n\n\n",
"El calculo de la primera integral es 1.9980056792766332\nEl calculo de la segunda integral es -0.5772747948147595\nEl calculo de la tercera integral es 1.5622239605373698\nTiempo de ejecución: 0.10571551322937012 s\n"
],
[
"#Trapecio\n\ninicio = time.time()\n\n\nn=100\nx_f = np.linspace(0.000001,1,1000001) #se necesita esta precision de division en intervalos para obtener coincidenciaen los primeros \nx = np.linspace(0.000001,n,1000001)\n\n\ndef f(x):\n return x**(-1/2)\n\ndef g(x):\n return np.exp(-x)*np.log(x)\n\ndef h(x):\n return np.sin(x)/x\n\ndef integrate(x,f):\n calculo=0\n for i in range(len(x)-1):\n calculo = calculo + (f(x[i+1])+(f(x[i])))*abs(x[i+1]-x[i])/2\n return(calculo)\n\n \nintegral_f = integrate(x_f,f) \nintegral_g = integrate(x,g)\nintegral_h = integrate(x,h)\n\n\n\nprint(f\"El calculo de la primera integral es {integral_f}\")\nprint(f\"El calculo de la segunda integral es {integral_g}\")\nprint(f\"El calculo de la tercera integral es {integral_h}\")\n\n\n#Demora aprox. 13 segundos en arrojar el resultado RAM 16 GB\n\n\ntime.sleep(0)\n\n\n\nfin = time.time()\n\nprint(\"Tiempo de ejecución: \",fin-inicio, \"s\")\n\n\n",
"El calculo de la primera integral es 1.9980396454151288\nEl calculo de la segunda integral es -0.5773442593303427\nEl calculo de la tercera integral es 1.5622244668962069\nTiempo de ejecución: 13.009706974029541 s\n"
]
],
[
[
"## (B) Fourier\n\nCalcule la transformada rápida de Fourier para la función de la **Tarea 3 (D)** en el intervalo $[0,4]$ ($k$ máximo $2\\pi n/L$ para $n=25$). Ajuste la transformada de Fourier para los datos de la **Tarea 3** usando el método de regresión exacto de la **Tarea 3 (C)** y compare con el anterior resultado. Para ambos ejercicios haga una interpolación y grafique para comparar.",
"_____no_output_____"
]
],
[
[
"\nx = df[\"x\"]\ny = df[\"y\"]\n\n\nlx = []\nly = []\nfor i in range(len(x)):\n if x[i]<=1.5 :\n lx.append(x[i])\n ly.append(y[i])\n \n \nx_a = np.array(lx)\ny_a = np.array(ly)\n\ndef f(vec,x_a): \n return (vec[0])/((x_a-vec[1])**2 + vec[2])**vec[3]\n\ndef L_ajuste(vec,x_a,y_a): \n deltaY=f(vec,x_a) - y_a\n return np.dot(deltaY,deltaY)/len(y_a)\n\n\nres2 = sp.optimize.minimize(fun=L_ajuste, x0=np.array([0,1,0,0]), args = (x_a,y_a), method='L-BFGS-B', tol=1e-8)\nb = f(res2.x,0)\n\n\nplt.figure()\nplt.scatter(x,y, label = \"Datos\")\nplt.plot(x,f(res2.x,x), c = 'r', label = \"Ajuste\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.show()\n\n\"\"\"\nprint('a: ',res2[\"x\"][0])\nprint('b: ', res2[\"x\"][1])\nprint('c: ',res2[\"x\"][2])\nprint('gama: ',res2[\"x\"][3])\n\nprint('Finalmente, F(0) es: ',b, ', con buena aproximacion a los valores anteriormente reportados')\n\n\"\"\"\n\n\n\n\n",
"_____no_output_____"
],
[
"plt.plot(x,f(res2.x,x), c = 'r', label = \"Ajuste\")\nx = x_a \ny = f(res2.x,x)\n",
"_____no_output_____"
],
[
"# 1ro, hallar coeficientes a_j, b_j\n\n\nNf = 25\n\ndef a_j(j):\n global x, y\n #debe integrar la función de 0 a 4\n k_j = 2*np.pi*j/4\n new_y = y*np.cos(k_j*x)\n \n return sp.integrate.simpson(new_y, x)\n\ndef b_j(j):\n global x, y\n #debe integrar la función de 0 a 4\n k_j = 2*np.pi*j/4\n new_y = y*np.sin(k_j*x)\n return sp.integrate.simpson(new_y, x)\n \n \n\n \nA_j = np. array([a_j(j) for j in range(Nf)])\nB_j = np. array([b_j(j) for j in range(Nf)])\n\n\n\n\n\n",
"_____no_output_____"
],
[
"print(A_j)\nprint()\nprint(B_j)",
"[ 1.12271993 0.09055661 -0.54156923 0.16987651 0.03040855 -0.18666674\n 0.10906827 -0.05535532 -0.06469796 0.07045033 -0.12074357 -0.03242398\n 0.06094871 -0.05507659 0.06575006 0.08933063 -0.0248382 -0.02626271\n -0.03952117 0.02046983 -0.05281754 -0.17375368 0.07904749 0.12834424\n -0.04505808]\n\n[ 0. 0.94052492 0.0153534 -0.19920088 0.26636325 -0.04459506\n -0.03541277 0.13238869 -0.0721588 0.05025412 0.06449748 -0.11403931\n 0.01766879 -0.00695634 -0.07597523 0.07690022 0.07675283 0.03695708\n 0.0133034 0.01074276 0.10953406 -0.06706653 -0.17461797 0.08136979\n 0.03024549]\n"
],
[
"#Trnasformada de Fourier\n\n\nx_tilde = np.linspace(0, 4, 10000) \nk_j = np. array([2*np.pi*j/4 for j in range(Nf)])\ny_tilde = np.sum([ (A_j[j]*np.cos(k_j[j]*x_tilde) + B_j[j]*np.sin(k_j[j]*x_tilde)) for j in range(Nf) ], axis=0)\n\n\n\n",
"_____no_output_____"
],
[
"\n\n\nplt.plot(x_tilde, (A_j[0]*np.cos(k_j[0]*x_tilde) + B_j[0]*np.sin(k_j[0]*x_tilde)) )\nplt.plot(x_tilde, (A_j[1]*np.cos(k_j[1]*x_tilde) + B_j[1]*np.sin(k_j[1]*x_tilde)) )\nplt.plot(x_tilde, (A_j[2]*np.cos(k_j[2]*x_tilde) + B_j[2]*np.sin(k_j[2]*x_tilde)) )\n",
"_____no_output_____"
],
[
"# Gráfica de la Transformada rápida (discreta) de fourier de 0 a 4\n\nplt.plot(x_tilde, y_tilde)",
"_____no_output_____"
],
[
"\n\nx = df[\"x\"]\ny = df[\"y\"]\n\n\nlx = []\nly = []\nfor i in range(len(x)):\n if x[i]<=1.5 :\n lx.append(x[i])\n ly.append(y[i])\n \n \nx_a = np.array(lx)\ny_a = np.array(ly)\n\ndef f(vec,x_a): \n return (vec[0])/((x_a-vec[1])**2 + vec[2])**vec[3]\n\ndef L_ajuste(vec,x_a,y_a): \n deltaY=f(vec,x_a) - y_a\n return np.dot(deltaY,deltaY)/len(y_a)\n\n\nres4 = sp.optimize.minimize(fun=L_ajuste, x0=np.array([0,1,0,0]), args = (x_tilde,y_tilde), method='L-BFGS-B', tol=1e-8)\nb = f(res4.x,0)\n\n\nplt.figure()\nplt.scatter(x,y, label = \"Datos\")\nplt.plot(x_tilde,f(res4.x,x_tilde), c = 'r', label = \"Ajuste\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.show()\n\n\nprint('a: ',res4[\"x\"][0])\nprint('b: ', res4[\"x\"][1])\nprint('c: ',res4[\"x\"][2])\nprint('gama: ',res4[\"x\"][3])\n\nprint('Finalmente, F(0) es: ',b, ', sin aproximación a los datos anteriores')\n\n\n\n\n# la grafica ajustada no me da (me da absurdamente una linea constante)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
"<ipython-input-38-e02a1733a4e9>:17: RuntimeWarning: invalid value encountered in power\n return (vec[0])/((x_a-vec[1])**2 + vec[2])**vec[3]\n<ipython-input-38-e02a1733a4e9>:17: RuntimeWarning: divide by zero encountered in true_divide\n return (vec[0])/((x_a-vec[1])**2 + vec[2])**vec[3]\n<ipython-input-38-e02a1733a4e9>:17: RuntimeWarning: overflow encountered in true_divide\n return (vec[0])/((x_a-vec[1])**2 + vec[2])**vec[3]\n<ipython-input-38-e02a1733a4e9>:17: RuntimeWarning: overflow encountered in power\n return (vec[0])/((x_a-vec[1])**2 + vec[2])**vec[3]\n<ipython-input-38-e02a1733a4e9>:17: RuntimeWarning: overflow encountered in double_scalars\n return (vec[0])/((x_a-vec[1])**2 + vec[2])**vec[3]\n"
]
]
] | [
"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",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e722e40ababd3774ba8e1dde45fcd2231fc8c1e9 | 2,270 | ipynb | Jupyter Notebook | Python_training.ipynb | jgaman/python_training | daa95ffe76eda1a1667016c3018980b3680ba17a | [
"MIT"
] | null | null | null | Python_training.ipynb | jgaman/python_training | daa95ffe76eda1a1667016c3018980b3680ba17a | [
"MIT"
] | null | null | null | Python_training.ipynb | jgaman/python_training | daa95ffe76eda1a1667016c3018980b3680ba17a | [
"MIT"
] | null | null | null | 28.024691 | 234 | 0.476652 | [
[
[
"<a href=\"https://colab.research.google.com/github/jgaman/python_training/blob/main/Python_training.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"**Ce notebook contient tous mes exercices pendant le bootcamp CodingNomad**",
"_____no_output_____"
]
],
[
[
"#litle game with conditions\r\n\r\nimport random \r\nnum = random.randint(1, 10)\r\nguess = None\r\n\r\nwhile guess != num:\r\n guess = input(\"guess a number between 1and 10: \")\r\n guess = int(guess)\r\n if guess == num:\r\n print(\"congratulatons! you won!\")\r\n break\r\n else:\r\n print(\"nope, sorry, try again!\")\r\n\r\n",
"guess a number between 1and 10: 8\nnope, sorry, try again!\nguess a number between 1and 10: 9\nnope, sorry, try again!\nguess a number between 1and 10: 7\nnope, sorry, try again!\nguess a number between 1and 10: 6\ncongratulatons! you won!\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
]
] |
e722ee185cfbf8fdf6f5fcef986ed81afb93358e | 167,056 | ipynb | Jupyter Notebook | examples/CheckZorder.ipynb | leechr/myGeospatial | cd06c246123bb8649e4b8e63c394ddcee57adb53 | [
"MIT"
] | 10 | 2019-09-09T15:53:39.000Z | 2022-01-15T19:35:41.000Z | examples/CheckZorder.ipynb | leechr/myGeospatial | cd06c246123bb8649e4b8e63c394ddcee57adb53 | [
"MIT"
] | 1 | 2018-10-26T14:07:53.000Z | 2018-10-26T14:07:53.000Z | examples/CheckZorder.ipynb | leechr/myGeospatial | cd06c246123bb8649e4b8e63c394ddcee57adb53 | [
"MIT"
] | 1 | 2019-12-13T11:01:04.000Z | 2019-12-13T11:01:04.000Z | 1,561.271028 | 164,872 | 0.992625 | [
[
[
"import os\nimport folium\n\nprint(folium.__version__)",
"0.5.0+27.g2d457b0.dirty\n"
],
[
"import pandas as pd\n\n\nstate_geo = os.path.join('data', 'us-states.json')\nstate_unemployment = os.path.join('data', 'US_Unemployment_Oct2012.csv')\n\nstate_data = pd.read_csv(state_unemployment)\n\nm = folium.Map(\n location=[48, -102],\n zoom_start=3,\n tiles='Stamen Toner'\n)\n\nm.choropleth(\n state_geo,\n data=state_data,\n columns=['State', 'Unemployment'],\n key_on='feature.id',\n fill_color='YlGn',\n fill_opacity=0.7,\n line_opacity=0.2,\n legend_name='Unemployment Rate (%)'\n)\n\n\npopup = 'Must be on top of the choropleth'\n\nfolium.CircleMarker(\n location=[48, -102],\n radius=10,\n fill=True,\n popup=popup,\n weight=1,\n).add_to(m)\n\nm.save(os.path.join('results', 'CheckZorder.html'))\n\nm",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code"
]
] |
e722f1990ed56b9579810225c69425356439edbb | 15,069 | ipynb | Jupyter Notebook | junkyard.ipynb | rachelbasse/kaggle-recipes | 8233feea74858c957e828fe71ee62a60cbec46ec | [
"MIT"
] | null | null | null | junkyard.ipynb | rachelbasse/kaggle-recipes | 8233feea74858c957e828fe71ee62a60cbec46ec | [
"MIT"
] | null | null | null | junkyard.ipynb | rachelbasse/kaggle-recipes | 8233feea74858c957e828fe71ee62a60cbec46ec | [
"MIT"
] | null | null | null | 35.708531 | 142 | 0.566925 | [
[
[
"# imports\n\n# extra\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\n# local\nfrom feature_helpers import *\n\n# display settings\nsns.set(style='whitegrid', palette='husl')\npd.set_option('display.max_colwidth', 400)\npd.set_option('display.precision', 4)\npd.set_option('display.width', 1600)",
"_____no_output_____"
],
[
"recipes = load_clean_data()",
"_____no_output_____"
],
[
"metrics = get_metrics(recipes)",
"_____no_output_____"
],
[
"metrics.sort_values('unique_count')",
"_____no_output_____"
],
[
"sns.set(style='whitegrid', palette='husl')\nrecipe_counts_plot = sns.catplot(x='recipe_count', y='cuisine', data=metrics, kind='bar', height=7, aspect=1.8,\n order=metrics.recipe_count.sort_values(ascending=False).index)\nrecipe_counts_plot.set(xticks=range(0, 10500, 500));",
"_____no_output_____"
],
[
"recipe_lengths_plot = sns.catplot(x='recipe_length', y='cuisine', data=metrics, kind='bar', height=7, aspect=1.5,\n order=metrics.recipe_length.sort_values(ascending=False).index)\nrecipe_lengths_plot.set(xticks=range(0, 15, 2));",
"_____no_output_____"
],
[
"head_counts_plot = sns.catplot(x='head_count', y='cuisine', data=metrics, kind='bar', height=7, aspect=1.5,\n order=metrics.head_count.sort_values(ascending=False).index)\nhead_counts_plot.set(xticks=range(0, 122000, 20000));",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(16, 8))\nsns.set_color_codes('pastel')\nunique_counts_plot = sns.barplot(x='unique_count', y='cuisine', data=metrics, label='unique ings', color='b', ax=ax,\n order=metrics.unique_count.sort_values(ascending=False).index)\nrare_counts_plot = sns.barplot(x='rare_count', y='cuisine', data=metrics, label='rare ings', color='r', ax=ax,\n order=metrics.unique_count.sort_values(ascending=False).index)\nax.legend(ncol=2, loc='lower right', frameon=True)\nunique_counts_plot.set(xticks=range(0, 1100, 100));",
"_____no_output_____"
],
[
"# for friendlier plotting\ndef reshape_tfidfs(tfidfs):\n pairs = []\n for cuisine, vals in tfidfs.iterrows():\n pairs.extend([[cuisine, v] for v in vals if v > 0.0001])\n return pd.DataFrame(pairs, columns=['cuisine', 'tfidf'])\ntfidfs = make_tfidfs(recipes.query('cuisine != \"test\"'))\nsmoothed_tfidfs = smooth_tfidfs(tfidfs, .6)\nreshaped_tfidfs = reshape_tfidfs(tfidfs)\nreshaped_smoothed_tfidfs = reshape_tfidfs(smoothed_tfidfs)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(16, 8))\nall_tfidfs_plot = sns.distplot(reshaped_tfidfs.tfidf, kde=False)\nall_tfidfs_plot.set(xticks=np.arange(0, .46, .02));",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(16, 8))\nmax_tfidf = reshaped_smoothed_tfidfs.tfidf.max()\nall_smoothed_tfidfs_plot = sns.distplot(reshaped_smoothed_tfidfs.tfidf, kde=False)\nall_smoothed_tfidfs_plot.set(xticks=np.arange(0, max_tfidf + .05, .1));",
"_____no_output_____"
],
[
"cuisine_tfidfs_plot = sns.catplot(y='tfidf', x='cuisine', data=reshaped_tfidfs, kind='strip', height=7, aspect=2.5,\n order=metrics.unique_count.sort_values(ascending=False).index)\ncuisine_tfidfs_plot.set(yticks=np.arange(0, .45, .05));",
"_____no_output_____"
],
[
"max_tfidf = reshaped_smoothed_tfidfs.tfidf.max()\nsmoothed_cuisine_tfidfs_plot = sns.catplot(y='tfidf', x='cuisine', data=reshaped_smoothed_tfidfs, kind='strip', height=7, aspect=2.5,\n order=metrics.unique_count.sort_values(ascending=False).index)\nsmoothed_cuisine_tfidfs_plot.set(yticks=np.arange(0, max_tfidf + .1, .05));",
"_____no_output_____"
],
[
"def normalize_dist(dist):\n dist_min = dist.min()\n dist_range = dist.max() - dist_min\n normed = dist.map(lambda x: (x - dist_min) / dist_range)\n return normed",
"_____no_output_____"
],
[
"def make_indicators(recipes, features, renamed):\n indicators = np.zeros([recipes.shape[0], len(features)], dtype=np.uint8)\n feature_index = {feature: i for i, feature in enumerate(features)}\n for row_i, ings in enumerate(recipes.ingredients):\n recipe_features = [renamed[feature] if feature in renamed else feature for feature in ings]\n for feature in recipe_features:\n indicators[row_i, feature_index[feature]] = 1\n indicators = pd.DataFrame(indicators, index=recipes.index, columns=features)\n return pd.concat([recipes.cuisine, indicators], axis='columns')",
"_____no_output_____"
],
[
"def get_feature_importances(train):\n X = train.drop(columns=['cuisine'])\n y = train['cuisine']\n rfc = RandomForestClassifier(min_samples_leaf=8, random_state=1, class_weight='balanced', n_estimators=200, criterion='gini')\n rfc_grid = {\n 'max_depth': [20, 24],\n 'min_samples_split': [15, 25, 35]\n }\n search = RandomizedSearchCV(rfc, param_distributions=rfc_grid, refit=True, n_iter=5, cv=3, n_jobs=-1)\n search.fit(X, y)\n best = search.best_estimator_\n print('Best score: {0:.3f}, train score: {1:.3f}'.format(search.best_score_, best.score(X, y)))\n print(search.best_params_)\n return pd.Series(best.feature_importances_, index=X.columns)\n\ndef merge_unused_features(recipes, counts, renamed, catchall):\n indicators = make_indicators(recipes, counts.index.to_list(), renamed)\n importances = get_feature_importances(indicators)\n \n unused_features = importances[importances == 0].index.to_list()\n long_features = [feature for feature in unused_features if len(feature.split('-')) > 1]\n merged, renamed_update = merge_features(counts, long_features, catchall)\n renamed = merge_arrows(renamed, renamed_update)\n \n indicators = make_indicators(recipes, merged.index.to_list(), renamed)\n importances = get_feature_importances(indicators)\n \n unused_features = importances[importances == 0].index.to_list()\n merged, renamed_update = merge_features(merged, unused_features, catchall)\n renamed = merge_arrows(renamed, renamed_update)\n \n return (merged, renamed)\n\nunused_merged, renamed_update = merge_unused_features(recipes, rare_merged, renamed, 'raretype')\nrenamed = merge_arrows(renamed, renamed_update)",
"_____no_output_____"
],
[
"def make_tfidfs(recipes):\n recipe_strings = recipes.ingredients.map(lambda ings: ' '.join(ings))\n vectorizer = TfidfVectorizer(ngram_range=(1, 1), max_df=1.0, min_df=1, token_pattern=r'[\\w\\-_]+',\n binary=False, norm='l2', use_idf=True, smooth_idf=True, sublinear_tf=True,\n analyzer='word', encoding='utf-8',\n strip_accents=None, stop_words=None, max_features=None, lowercase=False)\n tfidfs = vectorizer.fit_transform(recipe_strings)\n tfidfs = pd.SparseDataFrame(tfidfs).to_dense()\n tfidfs.fillna(0, inplace=True)\n tfidfs.index = recipes.index\n tfidfs.columns = vectorizer.get_feature_names()\n return tfidfs",
"_____no_output_____"
],
[
"def make_scores(recipe, points, rank=True):\n scores = points.loc[recipe.ingredients]\n if not rank:\n return scores.mean()\n totals = scores.sum(axis='index')\n n_ings = len(recipe.ingredients)\n ranks = pd.Series(0.0, index=points.columns)\n if n_ings == 1:\n leaders = totals.nlargest(2).index\n ranks[leaders[0]] += 1.1\n ranks[leaders[1]] += 1\n return ranks / n_ings\n for ing in recipe.ingredients:\n leaders = (totals - scores.loc[ing].iloc[0]).nlargest(2).index\n ranks[leaders[0]] += 1.1\n ranks[leaders[1]] += 1\n return ranks / n_ings",
"_____no_output_____"
],
[
"def make_scores(recipe, points, group=True):\n scores = points.loc[recipe.ingredients]\n if group:\n groups = scores.groupby(lambda ing: ing.split('-')[0])\n return groups.mean().mean()\n return scores.mean()",
"_____no_output_____"
],
[
"def equalize_counts(counts, smooth_type='linear', smooth_intensity=.7):\n smoothing_funcs = {\n 'linear': lambda x: smooth_intensity * x,\n 'tanh': lambda x: tanh(x),\n 'sqrt_sigmoid': lambda x: x / sqrt(1 + x**2),\n 'frac_sigmoid': lambda x: x / (smooth_intensity + x)\n }\n total = counts.sum(axis='columns')\n inverse_total = total.map(lambda x: 1 / x if x else 0)\n proportions = counts.T * inverse_total\n if smooth_type:\n proportions = proportions.applymap(smoothing_funcs[smooth_type])\n return proportions.T",
"_____no_output_____"
],
[
"def train_validate_split(data, val_size, seed):\n samples = []\n for cuisine, group in data.groupby('cuisine'):\n jiggle = np.random.choice([0, .01, .02, .03])\n samples.append(group.sample(frac=val_size + jiggle, replace=False, random_state=seed, axis='index'))\n val = pd.concat(samples, axis='index')\n train = data.drop(index=val.index)\n X_train = train.drop(columns=['cuisine'])\n X_val = val.drop(columns=['cuisine'])\n y_train = train['cuisine']\n y_val = val['cuisine']\n return (X_train, y_train, X_val, y_val)",
"_____no_output_____"
],
[
"def test_hyperparams(data, clf, grid, metric, val_size, splits=3):\n param_grid = ParameterGrid(grid)\n scores = defaultdict(list)\n for i in range(splits):\n X_train, y_train, X_val, y_val = train_validate_split(data, val_size, seed=i)\n best_model, best_score, _, _ = pf.bestFit(\n clf, param_grid, X_train, y_train, X_val, y_val, metric=metric, greater_is_better=True)\n scores[best_score].append(best_model)\n return scores",
"_____no_output_____"
],
[
"pct = lambda v: int(v * 100)\n\ndef test(X, y, title, clf, sampler=None, splits=3):\n kfold = KFold(n_splits=splits, shuffle=True, random_state=1)\n for train_i, test_i in kfold.split(X):\n X_train, X_test = X.iloc[train_i], X.iloc[test_i]\n y_train, y_test = y.iloc[train_i], y.iloc[test_i]\n if sampler:\n X_train, y_train = sampler.fit_resample(X_train, y_train)\n model = clf.fit(X_train, y_train)\n preds = model.predict(X_test)\n print(metrics.accuracy_score(y_test, preds))\n print(metrics.classification_report(y_test, preds))\n\ndef get_errors(X, y, model, sort_col=None):\n errors = []\n preds = []\n for i in range(X.shape[0]):\n obs = X.iloc[i:i+1]\n real = y.iloc[i]\n y_pred = model.predict(obs)\n if y_pred != [real]:\n errors.append(i)\n preds.append(y_pred)\n errs = pd.concat([X.iloc[errors], y.iloc[errors]], axis=1)\n preds_df = pd.DataFrame(preds, index=errs.index, columns=['pred'])\n errs = pd.concat([errs, preds_df], axis=1)\n print('Errors:', errs.shape[0])\n if sort_col:\n errs.sort_values(sort_col, inplace=True)\n return errs",
"_____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"
]
] |
e7232138b2d0a1e02b03b4ef539db6d73fc55390 | 557,260 | ipynb | Jupyter Notebook | experiments/BatchBALD/AMN_ens_BatchBALD_original_breakout.ipynb | Tony-Cheng/Active-Reinforcement-Learning | 50bb65106ae1f957d8cb6cb5706ce1285519e6b4 | [
"MIT"
] | null | null | null | experiments/BatchBALD/AMN_ens_BatchBALD_original_breakout.ipynb | Tony-Cheng/Active-Reinforcement-Learning | 50bb65106ae1f957d8cb6cb5706ce1285519e6b4 | [
"MIT"
] | null | null | null | experiments/BatchBALD/AMN_ens_BatchBALD_original_breakout.ipynb | Tony-Cheng/Active-Reinforcement-Learning | 50bb65106ae1f957d8cb6cb5706ce1285519e6b4 | [
"MIT"
] | null | null | null | 27.130477 | 359 | 0.532086 | [
[
[
"from tqdm.notebook import tqdm\nimport math\nimport gym\nimport torch\nimport torch.optim as optim \nfrom torch.utils.tensorboard import SummaryWriter\nfrom collections import deque\n\nfrom active_rl.networks.dqn_atari import ENS_DQN\nfrom active_rl.utils.memory import RankedReplayMemory, BatchBALDReplayMemoryForEnsDQN\nfrom active_rl.utils.optimization import AMN_optimization_ensemble\nfrom active_rl.environments.atari_wrappers import make_atari, wrap_deepmind\nfrom active_rl.utils.atari_utils import fp, ActionSelector, evaluate\nfrom active_rl.utils.acquisition_functions import ens_BALD",
"_____no_output_____"
],
[
"env_name = 'Breakout'\nenv_raw = make_atari('{}NoFrameskip-v4'.format(env_name))\nenv = wrap_deepmind(env_raw, frame_stack=False, episode_life=False, clip_rewards=True)\nc,h,w = c,h,w = fp(env.reset()).shape\nn_actions = env.action_space.n",
"_____no_output_____"
],
[
"BATCH_SIZE = 64\nLR = 0.0000625\nGAMMA = 0.99\nEPS = 0.05\nNUM_STEPS = 10000000\nNOT_LABELLED_CAPACITY = 1000\nLABELLED_CAPACITY = 100000\nINITIAL_STEPS=NOT_LABELLED_CAPACITY\nTRAINING_PER_LABEL = 80.\nPERCENTAGE = 0.02\nTRAINING_ITER = int(TRAINING_PER_LABEL * NOT_LABELLED_CAPACITY * PERCENTAGE)\n\nNAME = f\"AMN_ens_BatchBALD_breakout_original_label_percentage_{PERCENTAGE}_BatchBALD_samples_1000\"",
"_____no_output_____"
],
[
"device = 'cuda:0'\n# AMN_net = MC_DQN(n_actions).to(device)\nAMN_net = ENS_DQN(n_actions).to(device)\nexpert_net = torch.load(\"models/dqn_expert_breakout_model\", map_location=device)\nAMN_net.apply(AMN_net.init_weights)\nexpert_net.eval()\n# optimizer = optim.Adam(AMN_net.parameters(), lr=LR, eps=1.5e-4)\noptimizer = optim.Adam(AMN_net.parameters(), lr=LR, eps=1.5e-4)",
"/home/tony/anaconda3/envs/rl/lib/python3.8/site-packages/torch/serialization.py:658: SourceChangeWarning: source code of class 'torch.nn.modules.conv.Conv2d' has changed. you can retrieve the original source code by accessing the object's source attribute or set `torch.nn.Module.dump_patches = True` and use the patch tool to revert the changes.\n warnings.warn(msg, SourceChangeWarning)\n/home/tony/anaconda3/envs/rl/lib/python3.8/site-packages/torch/serialization.py:658: SourceChangeWarning: source code of class 'torch.nn.modules.linear.Linear' has changed. you can retrieve the original source code by accessing the object's source attribute or set `torch.nn.Module.dump_patches = True` and use the patch tool to revert the changes.\n warnings.warn(msg, SourceChangeWarning)\n"
],
[
"memory = BatchBALDReplayMemoryForEnsDQN(NOT_LABELLED_CAPACITY, LABELLED_CAPACITY, [5,h,w], n_actions, AMN_net, device=device)\naction_selector = ActionSelector(EPS, EPS, AMN_net, 1, n_actions, device)",
"_____no_output_____"
],
[
"steps_done = 0\nwriter = SummaryWriter(f'runs/{NAME}')",
"_____no_output_____"
],
[
"q = deque(maxlen=5)\ndone=True\neps = 0\nepisode_len = 0\nnum_labels = 0",
"_____no_output_____"
],
[
"progressive = tqdm(range(NUM_STEPS), total=NUM_STEPS, ncols=400, leave=False, unit='b')\nfor step in progressive:\n if done:\n env.reset()\n sum_reward = 0\n episode_len = 0\n img, _, _, _ = env.step(1) # BREAKOUT specific !!!\n for i in range(10): # no-op\n n_frame, _, _, _ = env.step(0)\n n_frame = fp(n_frame)\n q.append(n_frame)\n \n # Select and perform an action\n state = torch.cat(list(q))[1:].unsqueeze(0)\n action, eps = action_selector.select_action(state)\n n_frame, reward, done, info = env.step(action)\n n_frame = fp(n_frame)\n\n # 5 frame as memory\n q.append(n_frame)\n memory.push(torch.cat(list(q)).unsqueeze(0), action, reward, done) # here the n_frame means next frame from the previous time step\n episode_len += 1\n\n # Perform one step of the optimization (on the target network)\n if step % NOT_LABELLED_CAPACITY == 0 and step > 0:\n num_labels += memory.label_sample(int(PERCENTAGE * NOT_LABELLED_CAPACITY),1000,batch_size=BATCH_SIZE);\n loss = 0\n for _ in range(TRAINING_ITER):\n loss += AMN_optimization_ensemble(AMN_net, expert_net, optimizer, memory, batch_size=BATCH_SIZE, \n device=device)\n loss /= TRAINING_ITER\n writer.add_scalar('Performance/loss', loss, num_labels)\n \n if step % 10000 == 0 and step > 0:\n evaluated_reward = evaluate(step, AMN_net, device, env_raw, n_actions, eps=0.05, num_episode=15)\n writer.add_scalar('Performance/reward_vs_label', evaluated_reward, num_labels)\n writer.add_scalar('Performance/reward_vs_step', evaluated_reward, step)\n \n evaluated_reward_expert = evaluate(step, expert_net, device, env_raw, n_actions, eps=0.05, num_episode=15)\n writer.add_scalar('Performance/reward_expert_vs_step', evaluated_reward_expert, step)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7233e7a57a6e6cbc94294b27aa51e633824553e | 244,176 | ipynb | Jupyter Notebook | Code/.ipynb_checkpoints/20210505_Calibration_arena_movement-checkpoint.ipynb | Fabalinks/Rearing_analysis | 7663fe789f60463066f2f6cf29cb14cbe5344b8e | [
"Apache-2.0"
] | 1 | 2022-01-03T08:28:43.000Z | 2022-01-03T08:28:43.000Z | Code/.ipynb_checkpoints/20210505_Calibration_arena_movement-checkpoint.ipynb | Fabalinks/Rearing_analysis | 7663fe789f60463066f2f6cf29cb14cbe5344b8e | [
"Apache-2.0"
] | null | null | null | Code/.ipynb_checkpoints/20210505_Calibration_arena_movement-checkpoint.ipynb | Fabalinks/Rearing_analysis | 7663fe789f60463066f2f6cf29cb14cbe5344b8e | [
"Apache-2.0"
] | null | null | null | 174.038489 | 88,668 | 0.837973 | [
[
[
"### This is designed to get a nice graph of arena movement and difference left to right movemnt and the affect on the rigid body \n",
"_____no_output_____"
],
[
"\n#### Load data ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom csv import reader\nfrom pylab import *\nimport pandas as pd\n\nroot = 'C:/Users/Fabian/Desktop/Analysis/Round3_FS03_FS06'\n\ndata = 'C:/Users/Fabian/Desktop/Analysis/Round3_FS03_FS06/Data'\n\nfigures = 'C:/Users/Fabian/Desktop/Analysis/Round3_FS03_FS06/Figures/'\n\n",
"_____no_output_____"
],
[
"Arena_movement = pd.read_csv(data + '/Calibration/Take 2021-05-03 04.40.09 PM.csv',low_memory=False,header =2 )",
"_____no_output_____"
],
[
"Arena_movement.head(10)",
"_____no_output_____"
],
[
"Arena_movement.index",
"_____no_output_____"
],
[
"Arena_movement.values",
"_____no_output_____"
],
[
"Arena_movement.head(10)",
"_____no_output_____"
]
],
[
[
"#### Arena moves only along the Z axis ",
"_____no_output_____"
],
[
"## Create an appropriate pandas series for graphing named appropriately ignoring nan and as float round the time to 2 decimals (series was an object)",
"_____no_output_____"
]
],
[
[
"resolution = 1\nindex = '[3::resolution]'\ntime = Arena_movement['Unnamed: 1'][3:].astype(float).round(decimals=2).rename('Time(s)')\n\nX = Arena_movement['Arena.4'][3:].astype(float)\nY= Arena_movement ['Arena.5'][3:].astype(float)\nZ= Arena_movement ['Arena.6'][3:].astype(float).rename('Arena position')\nderivative = Arena_movement ['Arena.6'][3:].astype(float).rename('Arena position').diff()\nFrame = Arena_movement ['Unnamed: 0'][3:].astype(float)\n\ndf = pd.merge(time,Z, right_index = True,left_index = True)\n\n# setting first name as index column\n#df.set_index([\"Unnamed: 1\"], inplace = True,append = True, drop = True)\n \n# resetting index\n#df.reset_index(inplace = True)\ndf\n\ndf.head(10)\n",
"_____no_output_____"
],
[
"df.plot(y=\"Arena position\",x='Time(s)')\nplt.ylabel('Position (m)')\n\nplt.savefig('%sArena_movement.png' %(figures), dpi = 200)\n",
"_____no_output_____"
]
],
[
[
"### Conlcusion: First movement is always a bit off - different starting location - after it seems to adjust ",
"_____no_output_____"
],
[
"## Compute and Graph the derivative of the movement",
"_____no_output_____"
]
],
[
[
"derivative.plot()\nplt.title( 'derivative of movement')\nplt.xlabel('frame number')\n\nplt.savefig('%sArena_movement_derivative.png' %(figures), dpi = 200)",
"_____no_output_____"
]
],
[
[
"### Conclusion: It takes about 3 seconds to speed up and slown down ( when pullign can get a bit stuck) is also visible on the acceleration profile \n",
"_____no_output_____"
],
[
"### Show individual oscilation ",
"_____no_output_____"
]
],
[
[
"osc = df[2900:3300]\nosc2 = df[4100:4700]\nosc3 = df[5300:5700]\nosc4 = df[6500:7100]",
"_____no_output_____"
],
[
"osc.plot(y=\"Arena position\",x='Time(s)')\nplt.xticks()\n",
"_____no_output_____"
],
[
"osc3.plot(y=\"Arena position\",x='Time(s)')\nplt.xticks()",
"_____no_output_____"
],
[
"osc2.plot(y=\"Arena position\",x='Time(s)')\nplt.xticks()",
"_____no_output_____"
],
[
"osc4.plot(y=\"Arena position\",x='Time(s)')\nplt.savefig('%sArena_movement_individual.png' %(figures), dpi = 200)\n",
"_____no_output_____"
],
[
"fig, axes = plt.subplots(nrows=2, ncols=2 ,dpi = 200)\n\n\nosc4.plot(y=\"Arena position\",x='Time(s)',subplots=True,ax=axes[0,0],sharey = True)\nosc3.plot(y=\"Arena position\",x='Time(s)',subplots=True,ax=axes[0,1])\nosc2.plot(y=\"Arena position\",x='Time(s)',subplots=True,ax=axes[1,0])\nosc.plot(y=\"Arena position\",x='Time(s)',subplots=True,ax=axes[1,1])\n\naxes[0,0].set_title('Forward', fontsize=10)\naxes[0,1].set_title('Backwards', fontsize=10)\naxes[0,0].set_ylabel('Position (m)')\naxes[1,0].set_ylabel('Position (m)')\naxes[0,1].legend(loc='upper left',prop={'size': 6})\naxes[0,0].legend(loc='upper right',prop={'size': 6})\naxes[1,1].legend(loc='upper left',prop={'size': 6})\naxes[1,0].legend(loc='upper right',prop={'size': 6})\n\nplt.savefig('%sArena_movement_Oscialtions.png' %(figures), dpi = 200)",
"_____no_output_____"
]
],
[
[
"### Conclusion: Arena is faster in one way - taking 3 seconds versus 2.5 on the way back due to the push and pull diferences. - would need to hook up the second actuator ",
"_____no_output_____"
],
[
"### Now find the indexes and compare lenghts from second oscialtion on ",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
e72346937167bc22f8d2c4a3a0aefe8b25ad3264 | 300,113 | ipynb | Jupyter Notebook | examples/compare_vector_and_scalar_ps.ipynb | astrofle/groundhog | 4fd4aed570cb816e70fb26593b48b60302251cb9 | [
"BSD-3-Clause"
] | null | null | null | examples/compare_vector_and_scalar_ps.ipynb | astrofle/groundhog | 4fd4aed570cb816e70fb26593b48b60302251cb9 | [
"BSD-3-Clause"
] | null | null | null | examples/compare_vector_and_scalar_ps.ipynb | astrofle/groundhog | 4fd4aed570cb816e70fb26593b48b60302251cb9 | [
"BSD-3-Clause"
] | null | null | null | 253.046374 | 249,835 | 0.886146 | [
[
[
"Example showing how to calibrate position switched data using vector and scalar approaches.",
"_____no_output_____"
]
],
[
[
"%matplotlib notebook",
"_____no_output_____"
],
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom astropy.convolution import convolve\nfrom astropy.convolution import Gaussian1DKernel\n\nfrom groundhog import datared\nfrom groundhog import sd_fits_io",
"_____no_output_____"
],
[
"# Data selection parameters.\nscan = 6\nifnum = 0\nplnum = 1\nintnum = None\nsdfits_file = '../groundhog/tests/data/TGBT20A_506_01.raw.vegas.A.fits'",
"_____no_output_____"
]
],
[
[
"We load the SDFITS file containing position switched observations and flag 50% of the channels at the edges (25% on each edge).",
"_____no_output_____"
]
],
[
[
"sdfits = sd_fits_io.read_sdfits(sdfits_file)\nsdfits.remove_edge_chans(frac=0.5)",
"_____no_output_____"
]
],
[
[
"Next, we calibrate the position switched scans using the scalar, `method='gbtidl'`, and vector, `method='vector'`, approaches.",
"_____no_output_____"
]
],
[
[
"tsou_s = datared.get_ps(sdfits, scan, ifnum=ifnum, intnum=intnum, plnum=plnum, method='gbtidl')\ntsou_v = datared.get_ps(sdfits, scan, ifnum=ifnum, intnum=intnum, plnum=plnum, method='vector', avgf_min=1e4)",
"_____no_output_____"
]
],
[
[
"We extract the frequency information for our scan.",
"_____no_output_____"
]
],
[
[
"scan = sdfits.get_scans(scan, ifnum=ifnum, intnum=intnum, plnum=plnum)\nfreq = scan.freq[0]",
"_____no_output_____"
]
],
[
[
"And smooth the spectra using a Gaussian kernel with $\\sigma=10$ channels.",
"_____no_output_____"
]
],
[
[
"gauss = Gaussian1DKernel(stddev=10)\ntsou_s_smo = convolve(tsou_s, gauss)\ntsou_v_smo = convolve(tsou_v, gauss)",
"_____no_output_____"
]
],
[
[
"Finally, we plot and compare the results from the two methods.",
"_____no_output_____"
]
],
[
[
"fig = plt.figure(dpi=150)\n\nax = fig.add_subplot(211)\nax.plot(freq.to('GHz'), tsou_v_smo*1e3, c='g', label='vector')\nax.plot(freq.to('GHz'), tsou_s_smo*1e3, c='purple', alpha=0.5, label='scalar')\nax.set_ylabel(r'$T_{\\rm{a}}$ (mK)')\nax.text(0.1, 0.9, '{0:.5f} K'.format(tsou_v_smo[:8000].std()), transform=ax.transAxes, c='g')\nax.text(0.1, 0.8, '{0:.5f} K'.format(tsou_s_smo[:8000].std()), transform=ax.transAxes, c='purple')\nax.minorticks_on()\nax.tick_params('both', direction='in', which='both',\n bottom=True, top=True, left=True, right=True, \n labelbottom=False,\n zorder=20)\nax.legend()\n\nax = fig.add_subplot(212)\nax.plot(freq.to('GHz'), (tsou_v_smo - tsou_s_smo)*1e3, c='k', label='vector-scalar')\nax.set_xlabel('Frequency (GHz)')\nax.set_ylabel(r'$T_{\\rm{a}}$ (mK)')\nax.minorticks_on()\nax.tick_params('both', direction='in', which='both',\n bottom=True, top=True, left=True, right=True, zorder=20)\nax.legend()\n\n#plt.savefig('vec_vs_sca.png',\n# bbox_inches='tight', \n# pad_inches=0.06)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7235750a4aaea5a426b6451742bf64d42d97feb | 34,148 | ipynb | Jupyter Notebook | EQE512-Week05-Lecture.ipynb | ahmetanildindar/EQE512-Matrix-Methods-In-Structural-Analysis | 971b2fc496f834ed7ca7999cf312a9becf53d8ed | [
"MIT"
] | 6 | 2020-10-12T09:11:17.000Z | 2021-10-09T05:12:31.000Z | EQE512-Week05-Lecture.ipynb | ahmetanildindar/EQE512-Matrix-Methods-In-Structural-Analysis | 971b2fc496f834ed7ca7999cf312a9becf53d8ed | [
"MIT"
] | null | null | null | EQE512-Week05-Lecture.ipynb | ahmetanildindar/EQE512-Matrix-Methods-In-Structural-Analysis | 971b2fc496f834ed7ca7999cf312a9becf53d8ed | [
"MIT"
] | 1 | 2021-11-12T06:20:54.000Z | 2021-11-12T06:20:54.000Z | 26.267692 | 7,536 | 0.541086 | [
[
[
"EQE512 MATRIX METHODS IN STRUCTURAL ANALYSIS \n\n---\n<h3 align=\"center\">Week 05 - Visualization of the Parametric Analysis Computations </h3> \n<h4 align=\"center\">Dr. Ahmet Anıl Dindar ([email protected])</h3> \n<h4 align=\"center\">2020 Fall </h4> \n\n---",
"_____no_output_____"
],
[
"\n**This week :** \n\n1. Matrix Definition\n\n2. Matrix in Python\n\n3. Matrix Calculations ; \n\n 3.1. Summation\n \n 3.2. Subtraction\n \n 3.3. Multiplication \n \n 3.3.1. Dot product\n \n 3.3.2. Cross product\n\n 3.4. Division\n \n 3.5. Inversion\n \n 3.6. Transpose\n \n 3.7. Determinant \n \n4. Matrix creation\n\n 4.1. Zero, one\n \n 4.2. Identity matrix\n \n 4.3. Diagonal matrix\n \n5. Mass matrix\n\n6. Stiffness matrix (how to create in a loop?)\n\n7. Visualization\n\n---\n",
"_____no_output_____"
],
[
"# Matrix Definition\n\n_A matrix is a collection of numbers arranged into a fixed number of rows and columns. Usually the numbers are real numbers._",
"_____no_output_____"
],
[
"# Matrix in Python\n\nMatrix is defined and processed in Numpy module in Python. The variable type is _array_ in Numpy. \n\nDo not use currently available \"matrix\" class because it is deprecated.\n",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\na = np.array([[1, 2, 4], [4,5,6] , [7,8,9]])\n\nprint(a)\n\nb = np.array([[1, 2, 3], \n [1, 1, 1] , \n [2, 3, 4]])\n\nprint(b)",
"[[1 2 4]\n [4 5 6]\n [7 8 9]]\n[[1 2 3]\n [1 1 1]\n [2 3 4]]\n"
],
[
"type(a)",
"_____no_output_____"
],
[
"b[2,2]",
"_____no_output_____"
]
],
[
[
"# Matrix Calculations\n\nThe fundamentals of Matrix operations",
"_____no_output_____"
],
[
"## Summation",
"_____no_output_____"
]
],
[
[
"a + b",
"_____no_output_____"
]
],
[
[
"## Subtraction",
"_____no_output_____"
]
],
[
[
"a - b",
"_____no_output_____"
]
],
[
[
"## Multiplication",
"_____no_output_____"
]
],
[
[
"print( a)",
"[[1 2 4]\n [4 5 6]\n [7 8 9]]\n"
],
[
"print(b) ",
"[[1 2 3]\n [1 1 1]\n [2 3 4]]\n"
],
[
"a*b",
"_____no_output_____"
]
],
[
[
"### Dot product",
"_____no_output_____"
]
],
[
[
"np.dot(a,b)",
"_____no_output_____"
]
],
[
[
"### Cross product",
"_____no_output_____"
]
],
[
[
"a*b",
"_____no_output_____"
]
],
[
[
"## Divison",
"_____no_output_____"
]
],
[
[
"print(a)\nprint(\"-------\")\nprint(b)",
"[[1 2 4]\n [4 5 6]\n [7 8 9]]\n-------\n[[1 2 3]\n [1 1 1]\n [2 3 4]]\n"
],
[
"a/b",
"_____no_output_____"
],
[
"np.divide(a,b)\n\n\n\n\n\n\n\n\n\n\n\n",
"_____no_output_____"
],
[
"np.",
"_____no_output_____"
]
],
[
[
"## Inversion",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
],
[
"a_inve = np.linalg.inv( a )",
"_____no_output_____"
],
[
"a_inve",
"_____no_output_____"
],
[
"# multiply the matrix of a by a_inve\n\noutput = np.dot( a , a_inve)\n\nprint(output)",
"[[ 1.0000000e+00 0.0000000e+00 -4.4408921e-16]\n [ 0.0000000e+00 1.0000000e+00 0.0000000e+00]\n [ 0.0000000e+00 0.0000000e+00 1.0000000e+00]]\n"
]
],
[
[
"## Transpose",
"_____no_output_____"
]
],
[
[
"a",
"_____no_output_____"
],
[
"a_transpose = np.transpose(a)\n\nprint(a_transpose)",
"[[1 4 7]\n [2 5 8]\n [4 6 9]]\n"
]
],
[
[
"## Determinant",
"_____no_output_____"
]
],
[
[
"np.linalg.det( a)",
"_____no_output_____"
]
],
[
[
"# Matrix Creation",
"_____no_output_____"
],
[
"## Special Matrix",
"_____no_output_____"
]
],
[
[
"zero_matrix = np.zeros( (4, 4))\n\nprint( zero_matrix )",
"[[0. 0. 0. 0.]\n [0. 0. 0. 0.]\n [0. 0. 0. 0.]\n [0. 0. 0. 0.]]\n"
],
[
"one_matrix = np.ones( (4,5))\n\nprint( one_matrix)",
"[[1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1.]]\n"
],
[
"999 * np.ones((4,4))\n\n\n\n\n",
"_____no_output_____"
]
],
[
[
"space \"allocation\" is important for matrix methods",
"_____no_output_____"
],
[
"## Identity matrix",
"_____no_output_____"
]
],
[
[
"id_matrix = np.eye(4)\n\nprint( id_matrix)",
"[[1. 0. 0. 0.]\n [0. 1. 0. 0.]\n [0. 0. 1. 0.]\n [0. 0. 0. 1.]]\n"
],
[
"9 * id_matrix ",
"_____no_output_____"
]
],
[
[
"## Diagonal matrix",
"_____no_output_____"
]
],
[
[
"diag_matrix = np.diag( [1,2,3,4])\n\nprint(diag_matrix)",
"[[1 0 0 0]\n [0 2 0 0]\n [0 0 3 0]\n [0 0 0 4]]\n"
]
],
[
[
"# Mass Matrix",
"_____no_output_____"
]
],
[
[
"mass = np.diag([100,100,100])\nprint(mass)",
"[[100 0 0]\n [ 0 100 0]\n [ 0 0 100]]\n"
],
[
"mass2 = 100 * np.eye(4)\nmass2",
"_____no_output_____"
],
[
"mass3 = np.diag( [100 for item in range(4)])\nmass3",
"_____no_output_____"
]
],
[
[
"# Stiffness matrix (how to create in a loop?)",
"_____no_output_____"
]
],
[
[
"# MEMBER STIFNESS\nEI = 100\nh = 3\nk = 12* EI /(3**3)\nprint(k)",
"44.44444444444444\n"
],
[
"# STORY STIFFNES\nk_story= 2 * k\nprint(k_story)",
"88.88888888888889\n"
],
[
"k1 = k_story\nk2 = k_story\nk3 = k_story",
"_____no_output_____"
],
[
"# SYSTEM STIFFNESS MATRIX\n\nK = np.array( [[k1+k2 , -k1 ,0 ], \n [-k1 , k2+k3 , -k2] , \n [0 , -k2 , k3]])\nprint(K)",
"[[177.77777778 -88.88888889 0. ]\n [-88.88888889 177.77777778 -88.88888889]\n [ 0. -88.88888889 88.88888889]]\n"
]
],
[
[
"---",
"_____no_output_____"
]
],
[
[
"# APPROACH 2\nk_stories = [ k1 , k2 , k3]\nk_stories",
"_____no_output_____"
],
[
"K_system = np.eye(3)\nK_system",
"_____no_output_____"
],
[
"for i in range(3):\n for j in range(3):\n if i == j : \n K_system[i,j]= k_stories[i] + k_stories[j]\n elif i - j == 1 or j - i == 1:\n K_system[i,j]= -1* k_stories[i]\n else: \n K_system[i,j] = 0\nK_system[2,2] = k_stories[-1]",
"_____no_output_____"
],
[
"K_system",
"_____no_output_____"
]
],
[
[
"---\n\nWhat if I have 5 stories building with different stiffnesses at each story?",
"_____no_output_____"
]
],
[
[
"k_stories_2 =[10,20,30,40,50,10,20,40]\nk_stories_2 = [ np.random.randint(10,20) for item in range(10) ] \nprint( k_stories_2)\nno_story = len(k_stories_2)\nprint(no_story)",
"[18, 10, 13, 15, 17, 18, 18, 12, 17, 10]\n10\n"
],
[
"K_system = np.zeros( (no_story, no_story))\nK_system",
"_____no_output_____"
],
[
"K_system = np.zeros( (no_story, no_story))\nfor i in range(no_story-1):\n for j in range( no_story):\n if i == j : \n K_system[i,j]= k_stories_2[i] + k_stories_2[i+1]\n elif i - j == 1 :\n K_system[i,j]= -1* k_stories_2[j]\n elif j-i == 1:\n K_system[i,j]= -1* k_stories_2[i]\n \n else: \n K_system[i,j] = 0\n\nK_system[no_story-1,no_story-1] = k_stories_2[-1]\nK_system[no_story-1,no_story-2] = -1*k_stories_2[-2]\n\nK_system",
"_____no_output_____"
],
[
"temp_eye = np.dot( K_system, np.linalg.inv( K_system))\nprint ( temp_eye )",
"[[ 1.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00]\n [-5.55111512e-16 1.00000000e+00 -1.11022302e-16 -2.22044605e-16\n -5.55111512e-17 0.00000000e+00 -2.77555756e-17 -6.93889390e-18\n 5.55111512e-17 5.55111512e-17]\n [ 2.22044605e-16 2.22044605e-16 1.00000000e+00 2.22044605e-16\n 1.11022302e-16 5.55111512e-17 5.55111512e-17 6.93889390e-18\n 0.00000000e+00 0.00000000e+00]\n [ 0.00000000e+00 -5.55111512e-17 -2.22044605e-16 1.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 1.11022302e-16]\n [ 0.00000000e+00 1.66533454e-16 0.00000000e+00 -1.11022302e-16\n 1.00000000e+00 2.22044605e-16 1.11022302e-16 0.00000000e+00\n 0.00000000e+00 -4.44089210e-16]\n [ 8.32667268e-17 -1.11022302e-16 1.66533454e-16 2.22044605e-16\n -2.22044605e-16 1.00000000e+00 2.22044605e-16 2.77555756e-17\n 0.00000000e+00 0.00000000e+00]\n [ 2.77555756e-17 1.66533454e-16 3.46944695e-17 5.55111512e-17\n 4.44089210e-16 3.60822483e-16 1.00000000e+00 4.44089210e-16\n 0.00000000e+00 0.00000000e+00]\n [ 4.16333634e-17 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 2.22044605e-16 1.00000000e+00\n 0.00000000e+00 0.00000000e+00]\n [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 1.00000000e+00 4.44089210e-16]\n [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 -5.55111512e-17\n 0.00000000e+00 -1.11022302e-16 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 1.00000000e+00]]\n"
]
],
[
[
"# Visualization _(New Section !)_\n\nLet's visualize the lateral forces of the MDOF system made of columns",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"plt.plot( temp_eye , \"*\")",
"_____no_output_____"
]
],
[
[
"---\n\n**NEXT WEEK**\n\n<table >\n<tr>\n<td>\n<img src=\"http://worshiphousemedia.s3.amazonaws.com/images/main/s/st/bnt/st/seeyounextweek1.jpg\" >\n</td>\n<td align=\"left\"><strong style=\"font-size: 20px;\">\nThe topics for the next week \n<br><br>\n\n1- Assignment : Not this week\n<br><br>\n2- \"Displacement and Force Method in Structural Analysis\"\n<br>\n</td>\n</tr>\n</table>",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
e723580ab46d1a2ed3a19c278cbe18a82974f924 | 156,003 | ipynb | Jupyter Notebook | Untitled.ipynb | algo-circle/Ntt-phase-2 | faa4fc28c7eb6bfb11a38e5abe2130df7d30b8d4 | [
"MIT"
] | null | null | null | Untitled.ipynb | algo-circle/Ntt-phase-2 | faa4fc28c7eb6bfb11a38e5abe2130df7d30b8d4 | [
"MIT"
] | null | null | null | Untitled.ipynb | algo-circle/Ntt-phase-2 | faa4fc28c7eb6bfb11a38e5abe2130df7d30b8d4 | [
"MIT"
] | null | null | null | 38.95206 | 93 | 0.289135 | [
[
[
"import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"os.chdir(r\"datasets/\")\nsubd= pd.read_csv(\"sub-division_rainfall_act_dep_1901-2015.csv\")\nsouth_pen= pd.read_csv('south_pen-India_rainfall_act_dep_1901_2016.csv')",
"_____no_output_____"
],
[
"south_pen.shape",
"_____no_output_____"
],
[
"south_pen.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 116 entries, 0 to 115\nData columns (total 11 columns):\nYEAR 116 non-null int64\nActual Rainfall: JUN 116 non-null float64\nActual Rainfall: JUL 116 non-null float64\nActual Rainfall: AUG 116 non-null float64\nActual Rainfall: SEPT 116 non-null float64\nActual Rainfall: JUN-SEPT 116 non-null float64\nDeparture Percentage: JUN 116 non-null float64\nDeparture Percentage: JUL 116 non-null float64\nDeparture Percentage: AUG 116 non-null float64\nDeparture Percentage: SEP 116 non-null float64\nDeparture Percentage: JUN-SEPT 116 non-null float64\ndtypes: float64(10), int64(1)\nmemory usage: 10.0 KB\n"
],
[
"south_pen",
"_____no_output_____"
],
[
"subd.shape",
"_____no_output_____"
],
[
"subd.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 12456 entries, 0 to 12455\nData columns (total 20 columns):\nSUBDIVISION 12456 non-null object\nYEAR 12456 non-null object\nParameter 12456 non-null object\nJAN 12428 non-null float64\nFEB 12435 non-null float64\nMAR 12433 non-null float64\nAPR 12441 non-null float64\nMAY 12440 non-null float64\nJUN 12446 non-null float64\nJUL 12442 non-null float64\nAUG 12448 non-null float64\nSEP 12443 non-null float64\nOCT 12429 non-null float64\nNOV 12393 non-null float64\nDEC 12397 non-null float64\nANNUAL 8288 non-null float64\nJF 8324 non-null float64\nMAM 8319 non-null float64\nJJAS 8320 non-null float64\nOND 8311 non-null float64\ndtypes: float64(17), object(3)\nmemory usage: 1.9+ MB\n"
],
[
"sg= subd.groupby('SUBDIVISION')",
"_____no_output_____"
],
[
"sg.describe()",
"_____no_output_____"
],
[
"subd.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 12456 entries, 0 to 12455\nData columns (total 20 columns):\nSUBDIVISION 12456 non-null object\nYEAR 12456 non-null object\nParameter 12456 non-null object\nJAN 12428 non-null float64\nFEB 12435 non-null float64\nMAR 12433 non-null float64\nAPR 12441 non-null float64\nMAY 12440 non-null float64\nJUN 12446 non-null float64\nJUL 12442 non-null float64\nAUG 12448 non-null float64\nSEP 12443 non-null float64\nOCT 12429 non-null float64\nNOV 12393 non-null float64\nDEC 12397 non-null float64\nANNUAL 8288 non-null float64\nJF 8324 non-null float64\nMAM 8319 non-null float64\nJJAS 8320 non-null float64\nOND 8311 non-null float64\ndtypes: float64(17), object(3)\nmemory usage: 1.9+ MB\n"
],
[
"subd.isnull().sum()",
"_____no_output_____"
],
[
"subd.drop(['ANNUAL','JF', 'MAM', 'JJAS', 'OND'], axis=1)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7235f82a571c4082e1d30cf9105d9a33c2642a8 | 303,185 | ipynb | Jupyter Notebook | MP1_02142020.ipynb | anirudh217sharma/fall2019 | 47bda9b2cb20e3e0cbf7466d92d237ec83a79002 | [
"BSD-3-Clause"
] | null | null | null | MP1_02142020.ipynb | anirudh217sharma/fall2019 | 47bda9b2cb20e3e0cbf7466d92d237ec83a79002 | [
"BSD-3-Clause"
] | null | null | null | MP1_02142020.ipynb | anirudh217sharma/fall2019 | 47bda9b2cb20e3e0cbf7466d92d237ec83a79002 | [
"BSD-3-Clause"
] | null | null | null | 106.792885 | 44,172 | 0.814133 | [
[
[
"<a href=\"https://colab.research.google.com/github/anirudh217sharma/fall2019/blob/master/MP1_02142020.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Mini Project 1 - CS498 Data Science and Analytics",
"_____no_output_____"
],
[
"<b>Group Members: Aniruddha Sharma (ashar29), Anunay Sharma (anunays2), Badrinarayanan Rajasekaran (br17)</b>",
"_____no_output_____"
]
],
[
[
"#If you need to change the directory, then we use the os package\nimport os \nos.chdir ('C:\\\\Users\\\\Anunay\\\\Documents\\\\CS 498\\\\MP\\\\MP1\\\\')",
"_____no_output_____"
],
[
"#Import all the necessary packages for this analysis\n\nimport pandas as pd\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nfrom scipy import stats\nimport seaborn as sns\n%matplotlib inline",
"_____no_output_____"
],
[
"# Upload data file from your local drive\n\nfrom google.colab import files\n\nuploaded = files.upload()",
"_____no_output_____"
],
[
"df_diseng = pd.read_csv(\"mp1_av_disengagements.csv\") #pd.read_csv to import the notebook\ndf_diseng.head() #Displays the top n rows of the dataset",
"_____no_output_____"
],
[
"uploaded = files.upload()",
"_____no_output_____"
],
[
"df_miles = pd.read_csv('mp1_av_totalmiles.csv')\ndf_miles.head()",
"_____no_output_____"
]
],
[
[
"# 2. Summarize the following information",
"_____no_output_____"
],
[
"<b>a. Total number of AV disengagements over the entire duration of available data</b>",
"_____no_output_____"
]
],
[
[
"print(f'Total number of AV disengagements over the entire duration of available data are {df_miles[\"total number of disengagements\"].sum(axis = 0)}') ",
"Total number of AV disengagements over the entire duration of available data are 1024\n"
]
],
[
[
"<b> b. Number of unique months that have recorded AV disengagements</b>",
"_____no_output_____"
]
],
[
[
"df_diseng['month']= df_diseng['Month'].apply(lambda x:x.split('-')[1]) #Split the data so that month and the date are apart\ndf_diseng['month'].nunique() #Count the unique months now\nprint(f'Number of unique months that have recorded AV disengagements are {df_diseng[\"month\"].nunique()}')",
"Number of unique months that have recorded AV disengagements are 12\n"
]
],
[
[
"<b> c. List of unique locations of AV disengagements</b>",
"_____no_output_____"
]
],
[
[
"print(f'There are {df_diseng[\"Location\"].nunique()} locations namely {list(df_diseng[\"Location\"].unique())[0]} and {list(df_diseng[\"Location\"].unique())[1]}') ",
"There are 2 locations namely urban-street and highway\n"
]
],
[
[
"<b>d. Number of unique causes for AV disengagements</b>",
"_____no_output_____"
]
],
[
[
"print(f'Number of unique causes for AV disengagements are {df_diseng[\"Cause\"].nunique()}')",
"Number of unique causes for AV disengagements are 10\n"
]
],
[
[
"<b>e) Columns with missing values in the dataset</b>",
"_____no_output_____"
],
[
"Lets visualize the missing values in the datasets through a missing map",
"_____no_output_____"
],
[
"<b>Disengagements dataset</b>",
"_____no_output_____"
]
],
[
[
"#We create a heatmap which distinguishes the columns with missing values\nsns.heatmap(df_diseng.isnull(), cbar=False)\nplt.title(\"Missing map of Disengagement data\")",
"_____no_output_____"
]
],
[
[
"We can see above that the only column which has missing values is <b>Reaction time</b>\nLets see how many of null values are actually there",
"_____no_output_____"
]
],
[
[
"print(f'The number of missing values in the reaction time column are {len(df_diseng[df_diseng[\"ReactionTime\"].isnull()])}')",
"The number of missing values in the reaction time column are 532\n"
]
],
[
[
"<b>Total miles dataset</b>",
"_____no_output_____"
]
],
[
[
"sns.heatmap(df_miles.isnull(), cbar=False)\nplt.title(\"Missing map of Total miles data\")",
"_____no_output_____"
]
],
[
[
"\nWe can see above that there are no column which has missing values in this dataset",
"_____no_output_____"
],
[
"<b>3) Plot a pie chart for the causes of AV disengagement. Based on the pie-chart, list the top 2 leading causes of disengagement?</b>",
"_____no_output_____"
]
],
[
[
"cause = df_diseng[\"Cause\"].value_counts() #Counts the occurences of different causes of disengagement\ncause\nplt.pie(cause, labels=cause.keys(),autopct = '%0.1f%%', shadow = True,radius =1) #produces the piechart using matplotlib\nplt.title(\"Causes of AV disengagement\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"From the above pie chart we can see that <b>Unwanted Driver discomfort</b> and <b>Recklessly behaving agent</b> are the two leading causes of disengagements",
"_____no_output_____"
],
[
"<b> 4. Visualize the trend of disengagement/mile over time with monthly granularity. \nHow would you describe the trend? Are AVs maturing over time?</b>",
"_____no_output_____"
]
],
[
[
"df1=df_miles.groupby(['Month']).sum()[['total number of disengagements','miles driven in autonomous mode']]\ndf1=df1.reset_index(0)\ndf1['month']= df1['Month'].apply(lambda x:x.split('-')[1]) #Splits the column to get the month and date separately\ndf1[\"month\"] = pd.to_datetime(df1.month, format='%b', errors='coerce').dt.month #Converts the column into date\ndf1['year']= df1['Month'].apply(lambda x:x.split('-')[0]) #Splits the column to get the month and date separately\n\ndf1['disengagement/mile']=df1['total number of disengagements']/df1['miles driven in autonomous mode']\ndf1 = df1.sort_values(by=[\"year\",\"month\"],ascending=True)\ndf1['date']=df1['Month'].apply(lambda x:x.split('-')[1])+\"-\"+df1['year'].astype(str)",
"_____no_output_____"
],
[
"#We leverage matplotlib section to plot a line to understand the trend over months\nplt.plot(df1['date'],df1['disengagement/mile'],'#8B008B',alpha=0.5,lw=1, ls='-', marker='o', markersize=8, markerfacecolor=\"yellow\",markeredgecolor='black')\nplt.xlabel('Months')\nplt.ylabel('Disengagement/Mile')\nplt.title('Disengagement/Mile Across Months')\nplt.show()\n#plt.xticks(['Jan','Feb','Mar','Apr','May','June','July','Aug','Sep','Oct','Nov','Dec'])",
"_____no_output_____"
]
],
[
[
"<b>The trend of disengagement/mile decreases over the course of time. We observe occassional peaks in disengagements but overall the trend is declining. Thus we can say that the AVs appear to have matured over time. It has the highest disengagement per mile in the month of September 2014 and lowest being November 2015</b>",
"_____no_output_____"
],
[
"## TASK 1",
"_____no_output_____"
],
[
"<b>1. What do the following distributions signify about samples drawn from it \n a. Gaussian distribution \n b. Exponential distribution \n c. Weibull distribution</b>",
"_____no_output_____"
],
[
"<b>Regardless of the type of distribution, ths sample distribution depends on the sample size taken from the population. For instance, when we take n=10 from any of these distributions, it looks very disconnected with mean and variance being different from the original distribution. As the sample size increases, the distribution resembles close to the parent distribution and mean of the sample converges towards the mean of the entire population (Central Limit Theorem)<br>\n\nReferences:\n1. https://amsi.org.au/ESA_Senior_Years/SeniorTopic4/4_md/SeniorTopic4b.html#content_6\n2. https://amsi.org.au/ESA_Senior_Years/SeniorTopic4/4b/4b_2content_7.html#content_8\n</b>",
"_____no_output_____"
],
[
"<b>2. Distribution of Reaction Time<b>",
"_____no_output_____"
]
],
[
[
"sns.distplot(df_diseng['ReactionTime'].dropna(), hist = False, kde = True,rug=True,fit=stats.weibull_min, #Displays the probability density of the distribution which can be above 1\n kde_kws = {'shade': True, 'linewidth': 3}) \nplt.xlabel('Reaction Time', fontsize=12)\nplt.ylabel('Probability Density', fontsize=12)\nplt.title('Distribution of Reaction Time', fontsize=14)",
"_____no_output_____"
]
],
[
[
"<b>Distribution of Reaction time removing the extreme values(>4) for better visualization</b>",
"_____no_output_____"
]
],
[
[
" df_diseng2 = df_diseng[df_diseng['ReactionTime']<=4]\n\nsns.distplot(df_diseng2['ReactionTime'], hist = False, kde = True,rug=True,fit=stats.weibull_min,\n kde_kws = {'shade': True, 'linewidth': 3})\nplt.title('Distribution of Reaction Time ', fontsize=14)\nplt.xlabel('Reaction Time', fontsize=12)\nplt.ylabel('Probability density', fontsize=12)",
"_____no_output_____"
]
],
[
[
"<b>The reaction time follows a weibull distribution. The distribution signifies that most of the drivers having a reaction time of 1-2s post which there is a very less population.\n<br> \nReferences:<br>\nhttps://www.itl.nist.gov/div898/handbook/eda/section3/eda3668.htm </b>",
"_____no_output_____"
],
[
"<b>3a. Average Reaction for entire duration of the dataset</b>",
"_____no_output_____"
]
],
[
[
"df_diseng.groupby('Location').mean()",
"_____no_output_____"
]
],
[
[
"<b>4. Perform a hypothesis testing at a 0.05 significance level</b>",
"_____no_output_____"
],
[
"Assumptions: \nFrom the given question, we have the mean of both the populations (AV and Non AV cars)\nSince no additional information is given, we assume that both the population has constant variance.\n\nNull hypothesis :The average reaction time for humans in Non AV cars is same as AV cars\n\nAlternative hypothesis : The average reaction time for humans in Non AV cars is different from AV cars\n\n",
"_____no_output_____"
]
],
[
[
"from scipy import stats\n###We assume both the population have constant variance\n#se - standard deviation of the population\nse = df_diseng['ReactionTime'].std() /np.sqrt(len(df_diseng['ReactionTime']))\n\nMean_of_NON_AV=1.09\nMean_of_AV=df_diseng['ReactionTime'].mean()\n#t=x-u/se\nttest=(Mean_of_NON_AV-Mean_of_AV)/se \nprint(round(ttest,3))",
"3.028\n"
],
[
"# degrees of freedom\ndf = len(df_diseng['ReactionTime'])-1\n\nfrom scipy.stats import t\nalpha=0.05 #Significance level given in the question\ncv = t.ppf(1.0 - alpha, df)\np = (1 - t.cdf(abs(ttest), df)) * 2\nif p<0.05:\n print(\"We reject the Null Hypothesis : The average reaction time for humans in Non AV cars is different as AV cars\")\nelse:\n print(\"We fail to reject the Null Hypothesis :The average reaction time for humans in Non AV cars same as AV cars\")\n",
"We reject the Null Hypothesis : The average reaction time for humans in Non AV cars is different as AV cars\n"
]
],
[
[
"<b> 5. Plot the probability distribution of disengagements/mile with monthly granularity</b>",
"_____no_output_____"
]
],
[
[
"sns.distplot(df1['disengagement/mile'], hist = True, kde = True, fit=stats.norm,\n kde_kws = {'shade': True, 'linewidth': 3})\nplt.title('Distribution of #disengagement/mile ', fontsize=14)\nplt.xlabel('#disengagement/mile', fontsize=12)\nplt.ylabel('Probability density', fontsize=12)",
"_____no_output_____"
]
],
[
[
"<b>The above figure follows more or less a normal distribution (Except that it has a local peak due to data). An additional support to normality are the tails of the distribution which look symmetric unlike a skewed distribution</b>",
"_____no_output_____"
],
[
"# TASK 2 ",
"_____no_output_____"
],
[
" Assumptions :\n1. There can be at most one disengagement in a mile\n2. A day can be either clear or cloudy, but not both. The probability of a day being clear in California is 72% \n3. The AV is equally likely to drive on a cloudy day as on a clear day.",
"_____no_output_____"
],
[
"<b>a.)<b> ",
"_____no_output_____"
],
[
"The assumption on maximum number of disengagements in a mile allows us to treat the occurrence of a disengagement in a mile as a random variable with a <b>Bernoulli<b> distribution",
"_____no_output_____"
],
[
"<b>b.) probability of disengagement per mile on a cloudy day.</b> ",
"_____no_output_____"
],
[
"Let ,\nBased on assumption 2 we have,\n\nProbability of a day being clear in california be denoted as <b>P(Clear)=0.72</b>\n \nProbability of a day being clear in california be denoted as <b>P(Cloudy)=0.28</b>\n \nProbability of a disengagement/mile in california be denoted as <b>P(DM)</b>\n \nWe have to find : <b>P(DM | cloudy)</b>\n\n <b>P(DM | cloudy) = [P(cloudy | DM) * P(DM)] / P(Cloudy) - using bayes theorem</b>\n \n Calculating: P(cloudy | DM) , let it be x \n\n",
"_____no_output_____"
]
],
[
[
"x = len(df_diseng[df_diseng['Weather']=='cloudy']) /len(df_diseng)\nprint('Probability: ', x)",
"Probability: 0.8154296875\n"
]
],
[
[
"<b>P(cloudy/DM) = 0.82 </b>",
"_____no_output_____"
],
[
"Calculating : P(DM) , let it be y",
"_____no_output_____"
]
],
[
[
"y=df_miles['total number of disengagements'].sum()/df_miles['miles driven in autonomous mode'].sum()",
"_____no_output_____"
]
],
[
[
"Calculating : P(DM) , let it be y",
"_____no_output_____"
]
],
[
[
"y=df_miles['total number of disengagements'].sum()/df_miles['miles driven in autonomous mode'].sum()",
"_____no_output_____"
]
],
[
[
"<b> P(DM) = 0.002026803687040926 </b>",
"_____no_output_____"
],
[
"<b>P(DM | cloudy) =[ 0.8154296875 * 0.002026803687040926 ] / 0.28</b>\n\n<b>P(DM | cloudy) = 0.005903</b>\n\n",
"_____no_output_____"
],
[
"<b>probability of disengagement per mile on a cloudy day is 0.0059<b>",
"_____no_output_____"
],
[
"<b> c.) probability of disengagement per mile on a cloudy day.</b>",
"_____no_output_____"
],
[
"We have to find :<b> P(DM | clear) </b>\n\n<b>P(DM | clear) = [P(clear | DM) * P(DM)] / P(Clear)</b> - using bayes theorem\n\nCalculating: P(clear | DM) , let it be x\n\n\n",
"_____no_output_____"
]
],
[
[
"x = len(df_diseng[df_diseng['Weather']=='clear']) /len(df_diseng)",
"_____no_output_____"
]
],
[
[
"P(DM) will be same as part a)",
"_____no_output_____"
],
[
"<b>P(DM) = 0.002026803687040926</b>\n\n<b>P(DM | clear) =[ 0.1845703125 * 0.002026803687040926 ] / 0.72</b>\n\n<b>P(DM | clear)= 0.00052</b>\n",
"_____no_output_____"
],
[
"<b>probability of disengagement per mile on a cloudy day is 0.00052<b>\n",
"_____no_output_____"
],
[
"<b> d.) probability of automatic disengagement per mile on a cloudy day.</b>",
"_____no_output_____"
],
[
"<b>Probability of a automatic disengagement/mile in california be denoted as P(ADM)</b>\n\n<b> P(ADM | Cloudy) = [P(Cloudy | ADM) * P(ADM)] / P(Cloudy) </b>\n\nCalculating: P(cloudy | ADM) , let it be x\n",
"_____no_output_____"
]
],
[
[
"x=len(df_diseng[(df_diseng['Weather']=='cloudy') & (df_diseng['TypeOfTrigger']=='automatic')]) / len(df_diseng[df_diseng['TypeOfTrigger']=='automatic'])",
"_____no_output_____"
]
],
[
[
"Calculating: P(cloudy | ADM) , let it be x",
"_____no_output_____"
],
[
"<b>P(cloudy/ADM) = 0.8052738336713996 </b>",
"_____no_output_____"
],
[
"Calculating : P(ADM) , let it be y",
"_____no_output_____"
]
],
[
[
"y=df_miles['number of automatic disengagements'].sum()/df_miles['miles driven in autonomous mode'].sum()",
"_____no_output_____"
]
],
[
[
"<b>P(ADM)= 0.0009757951344835708 </b>",
"_____no_output_____"
],
[
"<b>P(ADM | cloudy) =[ 0.8052738336713996 * 0.0009757951344835708 ] / 0.28</b>",
"_____no_output_____"
],
[
"<b>P(ADM | cloudy) = 0.002806</b>",
"_____no_output_____"
],
[
"<b>probability of automatic disengagement per mile on a cloudy day is 0.0028<b>\n",
"_____no_output_____"
],
[
"<b>probability of automatic disengagement per mile on a clear day.</b>",
"_____no_output_____"
],
[
"<b> P(ADM | Clear) = [P(Clear | ADM) * P(ADM)] / P(Clear) </b>",
"_____no_output_____"
],
[
"Calculating: P(cloudy/ADM) , let it be x",
"_____no_output_____"
]
],
[
[
"x=len(df_diseng[(df_diseng['Weather']=='clear') & (df_diseng['TypeOfTrigger']=='automatic')]) / len(df_diseng[df_diseng['TypeOfTrigger']=='automatic'])",
"_____no_output_____"
]
],
[
[
"<b>P(clear | ADM) = 0.1947261663286004 </b>",
"_____no_output_____"
],
[
"We have P(ADM) calculated above",
"_____no_output_____"
],
[
"<b>P(ADM)= 0.0009757951344835708 </b>",
"_____no_output_____"
],
[
"<b> P(ADM | Clear) = [x * 0.0009757951344835708] / 0.72",
"_____no_output_____"
],
[
"<b> P(ADM | Clear) = 0.000264 </b>",
"_____no_output_____"
],
[
"<b>e.) How likely is it that in 12000 miles, there are 150 or more disengagements under cloudy conditions? </b>",
"_____no_output_____"
],
[
"<b>The above distribution can be represented as a binomial distribution which can then be approximated to a normal distribution \nusing Central Limit Theorem</b>",
"_____no_output_____"
],
[
"<b> The normal distribution will have mean = n * p and standard deviation = sqrt(np(1-p)) , where n is the number of trials \nand p is probability of success</b>\n\n<b>Given n =12000 , p= 0.005903</b> from the data\n ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats as stats\nimport math\nimport scipy\n\nmu = (12000*0.005903)\nvariance = (12000*0.005903) * (1-0.005903)\nsigma = math.sqrt(variance)\nx = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)\nplt.plot(x, stats.norm.pdf(x, mu, sigma))\nplt.show()\n\nx=150 ##given \nz = ( x - mu ) / sigma\np_values = scipy.stats.norm.sf(abs(z))\np_values",
"_____no_output_____"
]
],
[
[
"<b>2.) a.) </b>",
"_____no_output_____"
],
[
"<b>Normal distribution represents an approximate representation of the data in the hypotheses test </b>",
"_____no_output_____"
]
],
[
[
"# DO NOT EXECUTE THIS CELL IN COLAB. LET IT BE GUYS!\n# import matplotlib.pyplot as plt\n# import matplotlib.image as mpimg\n# img=mpimg.imread('Normal_dist.PNG')\n# imgplot = plt.imshow(img)",
"_____no_output_____"
]
],
[
[
"The application of the normal distribution comes from assessing data points in terms of the standard deviation. We can determine how anomalous a data point is based on how many standard deviations it is from the mean. The normal distribution has the following helpful properties:\n68% of data is within ± 1 standard deviations from the mean\n95% of data is within ± 2 standard deviations from the mean\n99.7% of data is within ± 3 standard deviations from the mean\n\nReference -https://towardsdatascience.com/statistical-significance-hypothesis-testing-the-normal-curve-and-p-values-93274fa32687",
"_____no_output_____"
],
[
"<b>b.)</b>",
"_____no_output_____"
],
[
"<b>It is not necessary that rejecting the NULL hypothesis means accepting the alternate hypothesis. \nIt depends on the formulation of the experiment and a relationship may exist between 2 phenonmena that is not identified\nby the experiment\n\nFor example, there can be a set of hypothesis such as:\n\nH0: u1=u2\n\nHA: u1 > u2\n\nThere is a solution of u1 < u2 outside the scope of this hypothesis which might be left out as a part of this experiment</b>\n",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"<b> 3.) At a 0.05 significance level, test the following hypothesis: The AV has more disengagements (automatic and manual) on cloudy days than clear days. Based on the result of the hypothesis test, what can you conclude about the impact of weather conditions on AV safety? [Hint: Use a Z-test for testing this hypothesis]. </b>",
"_____no_output_____"
]
],
[
[
"Null Hypothesis : The AV on cloudy days has same disengagement on clear days",
"_____no_output_____"
]
],
[
[
"<b> Null Hypothesis : The AV on cloudy days has same disengagement on clear days</b>",
"_____no_output_____"
],
[
"<b> Alternative Hypothesis : The AV has more disengagement on cloudy days than clear days </b>",
"_____no_output_____"
]
],
[
[
"import math as m\n\nNumber_of_cloudy_disengagements=835\nNumber_of_clear_disengagements=189\n\nProb_cloudy_day=0.28\nProb_clear_day=(1-0.28)\n\nMean_cloudy_disengagements= 835*0.28\nstd_cloudy_disengagements= m.sqrt(835*0.28*0.72)\nMean_clear_disengagements= 189*0.72\nstd_clear_disengagements= m.sqrt(835*0.72*0.28)\n\nz=(Mean_cloudy_disengagements-Mean_clear_disengagements)/m.sqrt(Mean_cloudy_disengagements**2/835+Mean_clear_disengagements**2/189)\nz",
"_____no_output_____"
],
[
"from scipy.stats import t\ndf=Number_of_cloudy_disengagements+Number_of_clear_disengagements-1\nalpha=0.05#Significance level given in the question\ncv = t.ppf(1.0 - alpha, df)\np = (1 - t.cdf(abs(z), df)) * 2\nif p<0.05:\n print(\"We reject the Null Hypothesis : The AV on cloudy days has same disengagement on clear days\")\nelse:\n print(\"We fail to reject the Null Hypothesis : The AV has more disengagement on cloudy days than clear days\")",
"We reject the Null Hypothesis : The AV on cloudy days has same disengagement on clear days\n"
]
],
[
[
"<b>4. Conditional probability on reaction time</b>\n\n<b>Conditional Probability : P(Dm | Cloudy)=P(Dm,Cloudy | P(C)</b>",
"_____no_output_____"
]
],
[
[
"Prob1= len(df_diseng[(df_diseng['ReactionTime']>0.6) & (df_diseng['TypeOfTrigger']=='automatic') & (df_diseng['Weather']=='cloudy')])/len(df_diseng[(df_diseng['TypeOfTrigger']=='automatic') & (df_diseng['Weather']=='cloudy')])\nprint(\"The Probability of disengagement per mile on a cloudy day is {}\".format(round(Prob1,2)))",
"The Probability of disengagement per mile on a cloudy day is 0.47\n"
]
],
[
[
"<b>Conditional Probability : P(Dm | Clear)=P(Dm,Clear)/P(Clear)</b>",
"_____no_output_____"
]
],
[
[
"Prob2= len(df_diseng[(df_diseng['ReactionTime']>0.9) & (df_diseng['TypeOfTrigger']=='automatic') & (df_diseng['Weather']=='clear')])/len(df_diseng[(df_diseng['TypeOfTrigger']=='automatic') & (df_diseng['Weather']=='clear')])\nprint(\"The Probability of disengagement per mile on a cloudy day is {}\".format(round(Prob2,2)))",
"The Probability of disengagement per mile on a cloudy day is 0.28\n"
]
],
[
[
"<b>5. Probability on Accident per mile</b>",
"_____no_output_____"
],
[
"<b>Theorem of total probability would be <br>\nP(accident per mile)=P(Dm | Cloudy)*P(Cloudy) + P(Dm | clear)*P(clear)</b>",
"_____no_output_____"
]
],
[
[
"Prob3 = Prob1*0.28+Prob2*0.72\nprint(\"The Probability of Accident per mile on a cloudy day is {}\".format(round(Prob3,2)))",
"The Probability of Accident per mile on a cloudy day is 0.34\n"
]
],
[
[
"<b>6. The probability of a human driver causing a car accident is 2x10-6 [4]. How do AVs compare to human drivers?<br>\nJustify your conclusion and explain its consequences </b>",
"_____no_output_____"
],
[
"<b>The probability of human driver causing a car accident is 2*10^-4 while the probability of AV for the same comes to be 0.34. There is a bigger risk associated with AV's as they can't be trained with all the possible scenarios of accident that happens in the real life.\n\nOn the other hand, the humans react to any known/unknown signs of danger and their sudden response would to avoid accidents and mitigate the impact\n\nTraining the system with lesser data and of low variance can result in high probability of fatalities happening in the road. The system needs to be trained with different conditions like the weather, road and cities ",
"_____no_output_____"
],
[
"<b>7. KS Test</b>",
"_____no_output_____"
],
[
"Initially, we need to formulate the hypothesis for this test\nH0: Both the samples (clear and cloudy) from the same distribution\nHA: Both the samples (clear and cloudy) doesn't from the same distribution ",
"_____no_output_____"
]
],
[
[
"from scipy import stats\n\nReaction_time_cloudy=df_diseng[(df_diseng['Weather']=='cloudy')]['ReactionTime']\nReaction_time_clear=df_diseng[(df_diseng['Weather']=='clear')]['ReactionTime']\n\nstats.ks_2samp(Reaction_time_cloudy, Reaction_time_clear)\n",
"_____no_output_____"
]
],
[
[
"<b>\nThe given significance level is 0.1 (alpha) From the ks test, we get the P value as 0.7\n\nDecision rule:\nIf pvalue < alpha, then we reject the NULL hypothesis<br>\nelse we fail to reject the NULL hypothesis or accept the alternate hypothesis<br>\n\nHere 0.7>0.1,so we fail to reject the NULL hypothesis i.e. both the samples come from the same distribution <br>\n\nWe can conclude that the weather be it cloudy or clear doesn't have any impact on the disengagement reaction time.</b>",
"_____no_output_____"
],
[
"<b>Task 3</b>",
"_____no_output_____"
],
[
"<b>1. Modify your pandas data frame to include a ‘Class’ column</b>",
"_____no_output_____"
]
],
[
[
"df_diseng.loc[df_diseng['Cause'].isin ([\"Incorrect behavior prediction of others\",\n \"Recklessly behaving agent\",\n \"Unwanted Driver Discomfort\"]),'class'] = 'Controller'\ndf_diseng.loc[df_diseng['Cause'].isin ([\"Adverse road surface conditions\",\n \"Emergency Vehicle\",\n \"Position Estimation Failure\",\n \"Incorrect Traffic Light Detection\"]),'class'] = 'Perception System'\n\ndf_diseng.loc[df_diseng['Cause'].isin ([\"System Tuning and Calibration\",\n \"Hardware Fault\",\n \"Software Froze\"]),'class'] = 'Computer System'\n ",
"_____no_output_____"
]
],
[
[
"<b>Split the data randomly into training and testing (80-20 split). Use the fields ‘Location’, ‘Weather’, and ‘TypeOfTrigger’ as features and use ‘Class’ as assigned in the previous question as the label</b>",
"_____no_output_____"
]
],
[
[
"from sklearn import preprocessing\n#creating labelEncoder\nle = preprocessing.LabelEncoder()\n# Converting string labels into numbers.\ndf_diseng['Location_encoded']=le.fit_transform(df_diseng['Location'])\ndf_diseng['Weather_encoded']=le.fit_transform(df_diseng['Weather'])\ndf_diseng['TypeOfTrigger_encoded']=le.fit_transform(df_diseng['TypeOfTrigger'])\ndf_diseng['class_encoded']=le.fit_transform(df_diseng['class'])\n",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nX=df_diseng[['Location_encoded','Weather_encoded','TypeOfTrigger_encoded']]\ny=df_diseng[['class_encoded']]",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=101) \n",
"_____no_output_____"
]
],
[
[
"<b>3. Using the training dataset, create a NB model to identify the cause of disengagement based on the features ‘Location’, ‘Weather’, and ‘TypeOfTrigger’. Show the conditional probability tables from the training dataset ",
"_____no_output_____"
]
],
[
[
"#Import Gaussian Naive Bayes model\nfrom sklearn.naive_bayes import GaussianNB\n\n#Create a Gaussian Classifier\ngnb = GaussianNB()\n\n#Train the model using the training sets\nmodel=gnb.fit(X_train, y_train)\n\n##Making predictions based on the test set\ny_pred=model.predict(X_test) ",
"/usr/local/lib/python3.6/dist-packages/sklearn/naive_bayes.py:206: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n"
],
[
"",
"_____no_output_____"
]
],
[
[
"<b> 4.) Calculating the accuracy of the model using the confusion matrix and classification report </b>",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import classification_report,confusion_matrix\ncm=confusion_matrix(y_test,y_pred)\ncr=classification_report(y_test,y_pred)\nprint(cr) ###classification report \nprint(cm) ###confusion matrix",
" precision recall f1-score support\n\n 0 0.98 0.68 0.80 62\n 1 0.67 0.79 0.73 67\n 2 0.71 0.78 0.74 76\n\n accuracy 0.75 205\n macro avg 0.79 0.75 0.76 205\nweighted avg 0.78 0.75 0.75 205\n\n[[42 9 11]\n [ 1 53 13]\n [ 0 17 59]]\n"
],
[
"accuracy =cm.diagonal().sum() / cm.sum()\nprint(f\"accuracy of the model with the validation set approach came to be {round(accuracy,4) *100} %\")",
"accuracy of the model with the validation set approach came to be 75.12 %\n"
]
],
[
[
"<b> 5.) Performing cross validation to get a better estimate of the accuracy </b>",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import KFold, cross_val_score\nk_fold =KFold(n_splits=5, shuffle=False, random_state=42)\nclf = GaussianNB()\nprint(cross_val_score(clf, X, y, cv=k_fold, n_jobs=1))\nCV_accuracy=cross_val_score(clf, X, y, cv=k_fold, n_jobs=1)",
"[0.42439024 0.50731707 0.83902439 0.42439024 0.74019608]\n"
],
[
"from math import *\nCV_accuracy_average=np.mean(CV_accuracy)*100\nprint(f'CV_accuracy_average : {CV_accuracy_average}')",
"CV_accuracy_average : 58.70636059301769\n"
],
[
"random_state=[None , 101 , 42 ,1 ,10 ]\naccuracy_list=[]\ndef cross_validation(random_state,accuracy_list):\n \"\"\"\n Summary line : This function will do cross validation using 20% data as test set and 80% data as training set\n using different random seeds \n \n Parameters: \n arg1 : random_state : A list containing different random state values\n arg2 : accuracy_list : an empty list which will hold 5 different accuracies for all the models \n \n Returns: \n average accuracy of all the models\n \n \"\"\"\n \n for num in random_state:\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=num) \n from sklearn.naive_bayes import GaussianNB\n\n #Create a Gaussian Classifier\n gnb = GaussianNB()\n\n #Train the model using the training sets\n model=gnb.fit(X_train, y_train)\n y_pred=model.predict(X_test)\n from sklearn.metrics import confusion_matrix\n cm=confusion_matrix(y_test,y_pred)\n accuracy =cm.diagonal().sum() / cm.sum()\n accuracy_list.append(accuracy)\n return (np.mean(accuracy_list)*100) \n\ncross_validation(random_state,accuracy_list)\n \n ",
"/usr/local/lib/python3.6/dist-packages/sklearn/naive_bayes.py:206: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n/usr/local/lib/python3.6/dist-packages/sklearn/naive_bayes.py:206: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n/usr/local/lib/python3.6/dist-packages/sklearn/naive_bayes.py:206: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n/usr/local/lib/python3.6/dist-packages/sklearn/naive_bayes.py:206: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n/usr/local/lib/python3.6/dist-packages/sklearn/naive_bayes.py:206: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n"
]
],
[
[
" **6.) Is the NB model doing better than chance? Explain.**",
"_____no_output_____"
],
[
"\nYes, the NB model is performing better than chance. The model predictions were nearly <b>75 % </b> correct for the test data set when we used the <b> validation set approach </b>. We further validated this accuracy by performing k-fold cross validation approach (using Sklearn library and manually coding the k-fold CV). In both the cases the minimum average accuracy we achieved was nearly <b>58% (accuracy range: 58% - 64%).</b> By randomly guessing, we can have at max 50% correct predictions, which is lower than the accuracy achieved by the NB model. ",
"_____no_output_____"
],
[
"<b> 7.) What are the assumptions in NB in the context of this problem? Are the assumptions realistic? Explain. </b>",
"_____no_output_____"
],
[
"**Assumption:**\n\nNaive Bayes assumes that the features are class conditionally independent (independent given/conditioning on the class) which may not always hold in a real-world problem. Here we have three classes: Perception System, Controller, and Computer System; which we assume to be independent. \n\n**For an AV to perform safely, it is important for all three classes to show congruity, and thus are inter-dependent.**\nFor example, disengagement could result due to reckless behaving agent. However, the root cause could be software malfunction, which failed to process input from perception system (position estimation failure) and thus controller behaves in an unwanted manner.\nWe believe that we could have achieved better accuracy had the assumptions been more realistic. \n",
"_____no_output_____"
],
[
"<b> 8) Based on your answer to part 7, comment on whether any improvements can be gained in classification accuracy. If yes, how? </b>",
"_____no_output_____"
],
[
"Yes, there are dfferent approaches we can use to improve the accuracy of the model some of which are as follows : \n\n1.) As the assumption of the naive bayes may not be applicable in context of this problem , one way to improve the model accuracy is to use a different classfication process like <b> Linear Discriminant Analysis , Quadratic Discriminant Analysis , Multi class logistic regression. </b>\n\n2.) <b>Bayesian Networks</b> do not assume class independence and hence could have been a better choice for this problem and thus might have produced a higher accuracy.\n\n3.) <b> Ensemble models</b> which inloves combining multiple models to improve the accuracy using <b>bagging and boosting</b>. This ensembling can improve the predictive performance more than any single model.\n\n4.) Here we have a quite small dataset ,a general appraoch which can increase the accuracy is collecting more data as training a model on a more diverse dataset which has more variablity can result in a better machine learning model. ",
"_____no_output_____"
]
],
[
[
"",
"_____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",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
e7237495fc008125cfdf24eb5fbaca5cf5ae4f2a | 6,375 | ipynb | Jupyter Notebook | materiales_repaso/10-Python_08-Control_de_flujo_en_programas.ipynb | RicardoLegac/notebooks-DataScience | 212245bb52d255393c57b8cddc20224de910e81e | [
"MIT"
] | null | null | null | materiales_repaso/10-Python_08-Control_de_flujo_en_programas.ipynb | RicardoLegac/notebooks-DataScience | 212245bb52d255393c57b8cddc20224de910e81e | [
"MIT"
] | null | null | null | materiales_repaso/10-Python_08-Control_de_flujo_en_programas.ipynb | RicardoLegac/notebooks-DataScience | 212245bb52d255393c57b8cddc20224de910e81e | [
"MIT"
] | 1 | 2021-07-26T16:10:10.000Z | 2021-07-26T16:10:10.000Z | 22.29021 | 429 | 0.511686 | [
[
[
"# Control de Flujo en los programas",
"_____no_output_____"
],
[
"## Usando while",
"_____no_output_____"
],
[
"A continuación se presentan algunos programas cortos en Python. Responde cual es la salida de cada programa. Intenta responder las preguntas sin ejecutar el código.\n\n¿Qué imprimen estos loops simples?",
"_____no_output_____"
]
],
[
[
"# Primer loop\nnum = 0 \nwhile num <= 5: \n print(num) \n num += 1 \n\nprint(\"Fuera del loop\") \nprint(num)",
"_____no_output_____"
],
[
"# Segundo loop\nnumeroDeLoops = 0 \nnumeroDeMazanas = 2 \nwhile numeroDeLoops < 10: \n numeroDeMazanas *= 2 \n numeroDeMazanas += numeroDeLoops \n numeroDeLoops -= 1 \n \nprint(\"Number of apples: \" + str(numeroDeMazanas))",
"_____no_output_____"
],
[
"# Tercer loop\nnum = 10 \nwhile num > 3: \n num -= 1 \n print(num)",
"_____no_output_____"
],
[
"# Cuarto loop\nnum = 10 \nwhile True: \n if num < 7: \n print('Romper el loop') \n break \n print(num) \n num -= 1 \n\nprint('Fuera del loop')",
"_____no_output_____"
],
[
"# Quinto loop\nnum = 100 \nwhile not False: \n if num < 0: \n break \n \nprint('num is: ' + str(num))",
"_____no_output_____"
]
],
[
[
"## Usando for",
"_____no_output_____"
],
[
"Convierta los siguientes resultados en códigos que usen un loop for",
"_____no_output_____"
],
[
"*Primer resultado*\n\n``2``\n\n``4``\n\n``6``\n\n``8``\n\n``\"Fin!\"``",
"_____no_output_____"
],
[
"*Segundo resultado*\n\n``\"Hola!\"``\n\n``10``\n\n``8``\n\n``6``\n\n``4``\n\n``2``",
"_____no_output_____"
],
[
"## Ejercicios usando for",
"_____no_output_____"
],
[
"1- Escribir un programa que cuente la cantidad de vocales contenidas en el string s. Por ejemplo. Si s = 'azcbobobegghakl', el programa debe imprimir Número de vocales: 5",
"_____no_output_____"
]
],
[
[
"# string\n",
"_____no_output_____"
]
],
[
[
"2- Ingresar un número por teclado y guardar en una lista su tabla de multiplicar hasta 10.\nObs. Para agregar un elemento a una lista de nombre ``L`` usar el metodo append, ``L.append``",
"_____no_output_____"
]
],
[
[
"# listas\n",
"_____no_output_____"
]
],
[
[
"### Diccionarios\n\nCrear un diccionario vacío ``vocales = {}``\n\nCrear un dicionario con valores ``vocales={'a':2, 'e':3, 'i':2, 'o':1}``\n\nAgregar un elemento al diccionario vocales ``vocales['u'] = 3`` \n\nEl método ``get(clave, valor)`` El primer argumento es la clave; el segundo argumento es el valor que debe devolver ``get`` en caso de que la clave no esté en el diccionario. \n\nEjemplo: ``vocales.get('b',0)`` retorna 0 por que 'b' no se encuentra en vocales",
"_____no_output_____"
],
[
"3- Escribir un programa que cuente el número de apariciones de cada letra contenida en el string s. Guarde el resultado en un diccionario, donde la clave es la letra y el valor la frecuencia de aparición.\nEjemplo: s='Mississippi' \ncuentaLetras = {'M': 1, 'i': 4, 's': 4, 'p': 2}",
"_____no_output_____"
]
],
[
[
"# Diccionario\ncuentaLetras = {}\nfor letra in \"Mississippi\":\n cuentaLetras[letra] = cuentaLetras.get(letra,0) + 1\n \nprint(cuentaLetras)",
"_____no_output_____"
]
],
[
[
"4- Escribir un programa que almacene el diccionario con los créditos de las asignaturas de un curso {'Matemáticas': 6, 'Física': 4, 'Química': 5} y después muestre por pantalla los créditos de cada asignatura en el formato <asignatura> tiene <créditos> créditos, donde <asignatura> es cada una de las asignaturas del curso, y <créditos> son sus créditos. Al final debe mostrar también el número total de créditos del curso.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e723770dd4f917a38c9e566841dbdecc0dd04009 | 21,165 | ipynb | Jupyter Notebook | text-classification/45.nested-lstm.ipynb | huseinzol05/Tensorflow-NLP-Models | 0741216aa8235e1228b3de7903cc36d73f8f2b45 | [
"MIT"
] | 1,705 | 2018-11-03T17:34:22.000Z | 2022-03-29T04:30:01.000Z | text-classification/45.nested-lstm.ipynb | eridgd/NLP-Models-Tensorflow | d46e746cd038f25e8ee2df434facbe12e31576a1 | [
"MIT"
] | 26 | 2019-03-16T17:23:00.000Z | 2021-10-08T08:06:09.000Z | text-classification/45.nested-lstm.ipynb | eridgd/NLP-Models-Tensorflow | d46e746cd038f25e8ee2df434facbe12e31576a1 | [
"MIT"
] | 705 | 2018-11-03T17:34:25.000Z | 2022-03-24T02:29:14.000Z | 44.464286 | 376 | 0.535648 | [
[
[
"from utils import *\nimport tensorflow as tf\nfrom sklearn.cross_validation import train_test_split\nimport time",
"/usr/local/lib/python3.5/dist-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n from ._conv import register_converters as _register_converters\n/usr/local/lib/python3.5/dist-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.\n \"This module will be removed in 0.20.\", DeprecationWarning)\n"
],
[
"trainset = sklearn.datasets.load_files(container_path = 'data', encoding = 'UTF-8')\ntrainset.data, trainset.target = separate_dataset(trainset,1.0)\nprint (trainset.target_names)\nprint (len(trainset.data))\nprint (len(trainset.target))",
"['negative', 'positive']\n10662\n10662\n"
],
[
"ONEHOT = np.zeros((len(trainset.data),len(trainset.target_names)))\nONEHOT[np.arange(len(trainset.data)),trainset.target] = 1.0\ntrain_X, test_X, train_Y, test_Y, train_onehot, test_onehot = train_test_split(trainset.data, \n trainset.target, \n ONEHOT, test_size = 0.2)",
"_____no_output_____"
],
[
"concat = ' '.join(trainset.data).split()\nvocabulary_size = len(list(set(concat)))\ndata, count, dictionary, rev_dictionary = build_dataset(concat, vocabulary_size)\nprint('vocab from size: %d'%(vocabulary_size))\nprint('Most common words', count[4:10])\nprint('Sample data', data[:10], [rev_dictionary[i] for i in data[:10]])",
"vocab from size: 20465\nMost common words [('the', 10129), ('a', 7312), ('and', 6199), ('of', 6063), ('to', 4233), ('is', 3378)]\nSample data [4, 668, 9, 2822, 8, 22, 4, 3424, 16369, 97] ['the', 'rock', 'is', 'destined', 'to', 'be', 'the', '21st', 'centurys', 'new']\n"
],
[
"GO = dictionary['GO']\nPAD = dictionary['PAD']\nEOS = dictionary['EOS']\nUNK = dictionary['UNK']",
"_____no_output_____"
],
[
"from tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import rnn_cell_impl\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.layers import base as base_layer\n\n_BIAS_VARIABLE_NAME = \"bias\"\n_WEIGHTS_VARIABLE_NAME = \"kernel\"\n\n\nclass NLSTMCell(rnn_cell_impl.RNNCell):\n def __init__(self, num_units, depth, forget_bias=1.0,\n state_is_tuple=True, use_peepholes=True,\n activation=None, gate_activation=None,\n cell_activation=None,\n initializer=None,\n input_gate_initializer=None,\n use_bias=True, reuse=None, name=None):\n \n super(NLSTMCell, self).__init__(_reuse=reuse, name=name)\n if not state_is_tuple:\n logging.warn(\"%s: Using a concatenated state is slower and will soon be \"\n \"deprecated. Use state_is_tuple=True.\", self)\n\n self.input_spec = base_layer.InputSpec(ndim=2)\n self._num_units = num_units\n self._forget_bias = forget_bias\n self._state_is_tuple = state_is_tuple\n self._use_peepholes = use_peepholes\n self._depth = depth\n self._activation = activation or math_ops.tanh\n self._gate_activation = gate_activation or math_ops.sigmoid\n self._cell_activation = cell_activation or array_ops.identity\n self._initializer = initializer or init_ops.orthogonal_initializer()\n self._input_gate_initializer = (input_gate_initializer \n or init_ops.glorot_normal_initializer())\n self._use_bias = use_bias\n self._kernels = None\n self._biases = None\n self.built = False\n\n @property\n def state_size(self):\n if self._state_is_tuple:\n return tuple([self._num_units] * (self.depth + 1))\n else:\n return self._num_units * (self.depth + 1)\n\n @property\n def output_size(self):\n return self._num_units\n\n @property\n def depth(self):\n return self._depth\n\n def build(self, inputs_shape):\n if inputs_shape[1].value is None:\n raise ValueError(\"Expected inputs.shape[-1] to be known, saw shape: %s\" % inputs_shape)\n\n input_depth = inputs_shape[1].value\n h_depth = self._num_units\n self._kernels = []\n if self._use_bias:\n self._biases = []\n\n if self._use_peepholes:\n self._peep_kernels = []\n for i in range(self.depth):\n if i == 0:\n input_kernel = self.add_variable(\"input_gate_kernel\",\n shape=[input_depth, 4 * self._num_units],\n initializer=self._input_gate_initializer)\n hidden_kernel = self.add_variable(\"hidden_gate_kernel\",\n shape=[h_depth, 4 * self._num_units],\n initializer=self._initializer)\n kernel = tf.concat([input_kernel, hidden_kernel],\n axis=0, name=\"kernel_0\")\n self._kernels.append(kernel)\n else:\n self._kernels.append(self.add_variable(\"kernel_{}\".format(i),\n shape=[2 * h_depth, 4 * self._num_units],\n initializer=self._initializer))\n if self._use_bias:\n self._biases.append(self.add_variable(\"bias_{}\".format(i),\n shape=[4 * self._num_units],\n initializer=init_ops.zeros_initializer(dtype=self.dtype)))\n if self._use_peepholes:\n self._peep_kernels.append(self.add_variable(\"peep_kernel_{}\".format(i),\n shape=[h_depth, 3 * self._num_units],\n initializer=self._initializer))\n\n self.built = True\n\n def _recurrence(self, inputs, hidden_state, cell_states, depth):\n\n sigmoid = math_ops.sigmoid\n one = constant_op.constant(1, dtype=dtypes.int32)\n c = cell_states[depth]\n h = hidden_state\n\n gate_inputs = math_ops.matmul(array_ops.concat([inputs, h], 1), self._kernels[depth])\n if self._use_bias:\n gate_inputs = nn_ops.bias_add(gate_inputs, self._biases[depth])\n if self._use_peepholes:\n peep_gate_inputs = math_ops.matmul(c, self._peep_kernels[depth])\n i_peep, f_peep, o_peep = array_ops.split(value=peep_gate_inputs, num_or_size_splits=3, axis=one)\n\n i, j, f, o = array_ops.split(value=gate_inputs, num_or_size_splits=4, axis=one)\n if self._use_peepholes:\n i += i_peep\n f += f_peep\n o += o_peep \n\n if self._use_peepholes:\n peep_gate_inputs = math_ops.matmul(c, self._peep_kernels[depth])\n i_peep, f_peep, o_peep = array_ops.split(value=peep_gate_inputs, num_or_size_splits=3, axis=one)\n i += i_peep\n f += f_peep\n o += o_peep \n\n add = math_ops.add\n multiply = math_ops.multiply\n\n if self._use_bias:\n forget_bias_tensor = constant_op.constant(self._forget_bias, dtype=f.dtype)\n f = add(f, forget_bias_tensor)\n\n inner_hidden = multiply(c, self._gate_activation(f))\n\n if depth == 0:\n inner_input = multiply(self._gate_activation(i), self._cell_activation(j))\n else:\n inner_input = multiply(self._gate_activation(i), self._activation(j))\n\n if depth == (self.depth - 1):\n new_c = add(inner_hidden, inner_input)\n new_cs = [new_c]\n else:\n new_c, new_cs = self._recurrence(inputs=inner_input,\n hidden_state=inner_hidden,\n cell_states=cell_states,\n depth=depth + 1)\n new_h = multiply(self._activation(new_c), self._gate_activation(o))\n new_cs = [new_h] + new_cs\n return new_h, new_cs\n\n def call(self, inputs, state):\n if not self._state_is_tuple:\n states = array_ops.split(state, self.depth + 1, axis=1)\n else:\n states = state\n hidden_state = states[0]\n cell_states = states[1:]\n outputs, next_state = self._recurrence(inputs, hidden_state, cell_states, 0)\n if self._state_is_tuple:\n next_state = tuple(next_state)\n else:\n next_state = array_ops.concat(next_state, axis=1)\n return outputs, next_state",
"_____no_output_____"
],
[
"class Model:\n def __init__(self, size_layer, embedded_size,\n dict_size, dimension_output, learning_rate, batch_size,\n timestamp, depth=1):\n self.X = tf.placeholder(tf.int32, [batch_size, maxlen])\n self.Y = tf.placeholder(tf.float32, [batch_size, dimension_output])\n encoder_embeddings = tf.Variable(tf.random_uniform([dict_size, embedded_size], -1, 1))\n encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n \n cell = NLSTMCell(size_layer, depth)\n init_state = cell.zero_state(batch_size, dtype=dtypes.float32)\n state = init_state\n outputs = []\n with tf.variable_scope(\"RNN\"):\n for time_step in range(timestamp):\n if time_step > 0:\n tf.get_variable_scope().reuse_variables()\n out, state = cell(encoder_embedded[:, time_step, :], state)\n outputs.append(out)\n outputs = tf.reshape(tf.concat(outputs,axis=1),[batch_size,timestamp,size_layer])\n W = tf.get_variable('w',shape=(size_layer, dimension_output),initializer=tf.orthogonal_initializer())\n b = tf.get_variable('b',shape=(dimension_output),initializer=tf.zeros_initializer())\n self.logits = tf.matmul(outputs[:, -1], W) + b\n self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = self.logits, labels = self.Y))\n self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n correct_pred = tf.equal(tf.argmax(self.logits, 1), tf.argmax(self.Y, 1))\n self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))",
"_____no_output_____"
],
[
"size_layer = 64\nembedded_size = 128\ndimension_output = len(trainset.target_names)\nlearning_rate = 1e-3\nmaxlen = 50\nbatch_size = 128",
"_____no_output_____"
],
[
"tf.reset_default_graph()\nsess = tf.InteractiveSession()\nmodel = Model(size_layer,embedded_size,vocabulary_size+4,\n dimension_output,learning_rate,\n batch_size,maxlen)\nsess.run(tf.global_variables_initializer())",
"_____no_output_____"
],
[
"EARLY_STOPPING, CURRENT_CHECKPOINT, CURRENT_ACC, EPOCH = 5, 0, 0, 0\nwhile True:\n lasttime = time.time()\n if CURRENT_CHECKPOINT == EARLY_STOPPING:\n print('break epoch:%d\\n'%(EPOCH))\n break\n \n train_acc, train_loss, test_acc, test_loss = 0, 0, 0, 0\n for i in range(0, (len(train_X) // batch_size) * batch_size, batch_size):\n batch_x = str_idx(train_X[i:i+batch_size],dictionary,maxlen)\n acc, loss, _ = sess.run([model.accuracy, model.cost, model.optimizer], \n feed_dict = {model.X : batch_x, model.Y : train_onehot[i:i+batch_size]})\n train_loss += loss\n train_acc += acc\n \n for i in range(0, (len(test_X) // batch_size) * batch_size, batch_size):\n batch_x = str_idx(test_X[i:i+batch_size],dictionary,maxlen)\n acc, loss = sess.run([model.accuracy, model.cost], \n feed_dict = {model.X : batch_x, model.Y : test_onehot[i:i+batch_size]})\n test_loss += loss\n test_acc += acc\n \n train_loss /= (len(train_X) // batch_size)\n train_acc /= (len(train_X) // batch_size)\n test_loss /= (len(test_X) // batch_size)\n test_acc /= (len(test_X) // batch_size)\n \n if test_acc > CURRENT_ACC:\n print('epoch: %d, pass acc: %f, current acc: %f'%(EPOCH,CURRENT_ACC, test_acc))\n CURRENT_ACC = test_acc\n CURRENT_CHECKPOINT = 0\n else:\n CURRENT_CHECKPOINT += 1\n \n print('time taken:', time.time()-lasttime)\n print('epoch: %d, training loss: %f, training acc: %f, valid loss: %f, valid acc: %f\\n'%(EPOCH,train_loss,\n train_acc,test_loss,\n test_acc))\n EPOCH += 1",
"epoch: 0, pass acc: 0.000000, current acc: 0.531738\ntime taken: 2.8110363483428955\nepoch: 0, training loss: 0.695090, training acc: 0.517756, valid loss: 0.689452, valid acc: 0.531738\n\nepoch: 1, pass acc: 0.531738, current acc: 0.592773\ntime taken: 2.0530991554260254\nepoch: 1, training loss: 0.668451, training acc: 0.598130, valid loss: 0.669185, valid acc: 0.592773\n\nepoch: 2, pass acc: 0.592773, current acc: 0.634766\ntime taken: 2.054539918899536\nepoch: 2, training loss: 0.594847, training acc: 0.699574, valid loss: 0.646298, valid acc: 0.634766\n\nepoch: 3, pass acc: 0.634766, current acc: 0.668945\ntime taken: 2.0540168285369873\nepoch: 3, training loss: 0.471607, training acc: 0.790365, valid loss: 0.666460, valid acc: 0.668945\n\nepoch: 4, pass acc: 0.668945, current acc: 0.698242\ntime taken: 2.0545835494995117\nepoch: 4, training loss: 0.345011, training acc: 0.862571, valid loss: 0.695080, valid acc: 0.698242\n\nepoch: 5, pass acc: 0.698242, current acc: 0.708984\ntime taken: 2.0536608695983887\nepoch: 5, training loss: 0.250333, training acc: 0.911340, valid loss: 0.695614, valid acc: 0.708984\n\nepoch: 6, pass acc: 0.708984, current acc: 0.719238\ntime taken: 2.05330491065979\nepoch: 6, training loss: 0.168091, training acc: 0.945668, valid loss: 0.761937, valid acc: 0.719238\n\nepoch: 7, pass acc: 0.719238, current acc: 0.720215\ntime taken: 2.0530500411987305\nepoch: 7, training loss: 0.111187, training acc: 0.968277, valid loss: 0.817810, valid acc: 0.720215\n\ntime taken: 2.050994873046875\nepoch: 8, training loss: 0.077725, training acc: 0.980114, valid loss: 0.883286, valid acc: 0.719238\n\ntime taken: 2.053058624267578\nepoch: 9, training loss: 0.056436, training acc: 0.986861, valid loss: 0.986419, valid acc: 0.713379\n\ntime taken: 2.0518455505371094\nepoch: 10, training loss: 0.041559, training acc: 0.991004, valid loss: 1.005594, valid acc: 0.717285\n\nepoch: 11, pass acc: 0.720215, current acc: 0.721191\ntime taken: 2.052720546722412\nepoch: 11, training loss: 0.032299, training acc: 0.993134, valid loss: 1.040796, valid acc: 0.721191\n\nepoch: 12, pass acc: 0.721191, current acc: 0.722656\ntime taken: 2.0508596897125244\nepoch: 12, training loss: 0.024856, training acc: 0.995028, valid loss: 1.161813, valid acc: 0.722656\n\ntime taken: 2.0544140338897705\nepoch: 13, training loss: 0.019435, training acc: 0.995975, valid loss: 1.237681, valid acc: 0.714355\n\ntime taken: 2.05448317527771\nepoch: 14, training loss: 0.012193, training acc: 0.997869, valid loss: 1.242486, valid acc: 0.713867\n\ntime taken: 2.0531187057495117\nepoch: 15, training loss: 0.008589, training acc: 0.998580, valid loss: 1.282168, valid acc: 0.721191\n\ntime taken: 2.054352045059204\nepoch: 16, training loss: 0.006250, training acc: 0.998935, valid loss: 1.329985, valid acc: 0.721680\n\ntime taken: 2.05053973197937\nepoch: 17, training loss: 0.004599, training acc: 0.999171, valid loss: 1.405500, valid acc: 0.721680\n\nbreak epoch:18\n\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7237ca8eb8438c772a8cb98ee20979458df33b9 | 6,685 | ipynb | Jupyter Notebook | Data_Preprocessing_final.ipynb | RohithYogi/Predict-Future-Sales | 86437d951053d3c22d65c580dfc890e9945a2ec1 | [
"MIT"
] | null | null | null | Data_Preprocessing_final.ipynb | RohithYogi/Predict-Future-Sales | 86437d951053d3c22d65c580dfc890e9945a2ec1 | [
"MIT"
] | null | null | null | Data_Preprocessing_final.ipynb | RohithYogi/Predict-Future-Sales | 86437d951053d3c22d65c580dfc890e9945a2ec1 | [
"MIT"
] | 1 | 2019-04-12T06:38:17.000Z | 2019-04-12T06:38:17.000Z | 24.221014 | 109 | 0.481975 | [
[
[
"import numpy as np\nimport pandas as pd \nimport os\nprint(os.listdir(\"../input\"))",
"['items.csv', 'shops.csv', 'test.csv', 'train.csv', 'item_categories.csv', 'sample_submission.csv']\n"
],
[
"import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport numpy.random as nr\nimport math\nfrom sklearn.linear_model import LinearRegression\nsns.set_style(\"ticks\", {\"xtick.major.size\": 10, \"ytick.major.size\": 10})\nplt.style.use('ggplot') ",
"_____no_output_____"
],
[
"train = pd.read_csv('../input/train.csv')\ntest = pd.read_csv('../input/test.csv')\nitems = pd.read_csv('../input/items.csv')\nshops = pd.read_csv('../input/shops.csv')\nitem_categories = pd.read_csv('../input/test.csv')",
"_____no_output_____"
],
[
"subset=['date','shop_id','item_id']\nprint(train.shape)\ntrain.drop_duplicates(subset,keep='first',inplace=True)\nprint(train.shape)",
"(2925849, 7)\n(2925823, 7)\n"
],
[
"print(train.head())\nprint (test.head())",
" date date_block_num shop_id item_id item_price item_cnt_day \\\n0 28.12.2014 23 25 12179 959.000000 1.0 \n1 23.04.2014 15 25 14042 149.000000 1.0 \n2 03.03.2014 14 12 11373 106.615385 13.0 \n3 08.12.2013 11 47 12107 599.000000 1.0 \n4 23.01.2015 24 29 3341 2599.000000 1.0 \n\n ID \n0 2317582 \n1 1576962 \n2 1547382 \n3 1255724 \n4 2372492 \n date date_block_num shop_id item_id item_price ID\n0 06.02.2015 25 31 11208 699.0 2472142\n1 21.11.2013 10 31 19525 149.0 1044690\n2 03.01.2015 24 42 16169 299.0 2367559\n3 18.07.2014 18 42 2737 199.0 1793501\n4 13.04.2014 15 2 15229 1199.0 1585639\n"
],
[
"print(train.shape)",
"(2925823, 7)\n"
],
[
"# train.hist('item_price')\n# train.hist('shop_id')\n# train.hist('item_cnt_day')\n# train.hist('item_id')\n# plt.figure(figsize=(10,14))\n# plt.show()",
"_____no_output_____"
],
[
"# print(train['item_price'].max())\n# plt.figure(figsize=(15,10))\n# plt.xlabel('price')\n# plt.ylabel('count')\n# # dates = check.date.apply(lambda x: x.strftime('%d/%m/%y'))\n# plt.scatter(train['item_price'],train['item_cnt_day'])\n# plt.show()",
"_____no_output_____"
],
[
"# plt.figure(figsize=(15,10))\n# plt.xlabel('ID')\n# plt.ylabel('count')\n# # dates = train.date.apply(lambda x: x.strftime('%d/%m/%y'))\n# plt.plot(train['item_id'],train['item_cnt_day'],'r.')\n# plt.show()",
"_____no_output_____"
],
[
"# plt.figure(figsize=(15,10))\n# plt.xlabel('ID')\n# plt.ylabel('price')\n# # dates = train.date.apply(lambda x: x.strftime('%d/%m/%y'))\n# plt.plot(train['item_id'],train['item_price'],'r.')\n# plt.show()",
"_____no_output_____"
],
[
"# plt.figure(figsize=(15,10))\n# plt.xlabel('date_block_num')\n# plt.ylabel('item_cnt_day')\n# # dates = train.date.apply(lambda x: x.strftime('%d/%m/%y'))\n# plt.plot(train['date_block_num'],train['item_cnt_day'],'r.')\n# plt.show()",
"_____no_output_____"
],
[
"train['item_id'].max()",
"_____no_output_____"
],
[
"# plt.plot(train[train['item_cnt_day']<0]['item_id'].value_counts().sort_index())\n# plt.show()",
"_____no_output_____"
],
[
"train['item_cnt_day']=train['item_cnt_day'].clip(0,1000)\nprint",
"_____no_output_____"
],
[
"train['item_price']=train['item_price'].clip(0,60000)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e72391bde557c9ddd50b58f7fd6d336dda0524d0 | 171,775 | ipynb | Jupyter Notebook | Data Compilation and EDA/Twitter Count Data.ipynb | phil510/nlp-crypto-project | e4a92b84eff8f58e7f4f1aeb365439ee20ce6e6b | [
"MIT"
] | 1 | 2021-10-07T20:25:49.000Z | 2021-10-07T20:25:49.000Z | Data Compilation and EDA/Twitter Count Data.ipynb | phil510/nlp-crypto-project | e4a92b84eff8f58e7f4f1aeb365439ee20ce6e6b | [
"MIT"
] | null | null | null | Data Compilation and EDA/Twitter Count Data.ipynb | phil510/nlp-crypto-project | e4a92b84eff8f58e7f4f1aeb365439ee20ce6e6b | [
"MIT"
] | null | null | null | 107.225343 | 114,516 | 0.763557 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e723966fb657c5b8e1937d8584dce4e3d76897d5 | 126,398 | ipynb | Jupyter Notebook | Time-series/timeseries-playground.ipynb | connor-john/RNN-pytorch | 001b551e13a38709a348e80f00f2e0a17705a7de | [
"MIT"
] | 1 | 2021-02-02T03:08:53.000Z | 2021-02-02T03:08:53.000Z | Time-series/timeseries-playground.ipynb | connor-john/RNN-pytorch | 001b551e13a38709a348e80f00f2e0a17705a7de | [
"MIT"
] | null | null | null | Time-series/timeseries-playground.ipynb | connor-john/RNN-pytorch | 001b551e13a38709a348e80f00f2e0a17705a7de | [
"MIT"
] | null | null | null | 183.718023 | 56,508 | 0.898424 | [
[
[
"## RNN Time Series Implementation",
"_____no_output_____"
]
],
[
[
"# Importing the Libraries\nimport torch\nimport torch.nn as nn\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()",
"_____no_output_____"
],
[
"# Data from Federal Reserve Economic Database (FRED)[https://fred.stlouisfed.org/]\nfilename = 'Data/Alcohol_sales.csv'",
"_____no_output_____"
],
[
"df = pd.read_csv(filename, index_col = 0, parse_dates = True)",
"_____no_output_____"
],
[
"df.head()\n# monthly increments",
"_____no_output_____"
],
[
"df = df.dropna()",
"_____no_output_____"
],
[
"len(df)",
"_____no_output_____"
],
[
"df.plot(figsize = (12, 4))\n# clear seasonality \n# general upward trend",
"_____no_output_____"
],
[
"y = df['S4248SM144NCEN'].values.astype(float)",
"_____no_output_____"
],
[
"# Using 1 year as a test size\ntest_size = 12",
"_____no_output_____"
],
[
"train = y[:-test_size]\ntest = y[-test_size:]",
"_____no_output_____"
],
[
"# Normalisation\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler(feature_range=(-1,1))\ntrain_norm = scaler.fit_transform(train.reshape(-1,1))",
"_____no_output_____"
],
[
"train_norm = torch.FloatTensor(train_norm).view(-1)",
"_____no_output_____"
],
[
"# Hyperparams\nseq_size = 12\nhidden_dim = 100\nlr = 0.001\nepochs = 100",
"_____no_output_____"
],
[
"# prepare data for LSTM\ndef prep_data(seq, ss):\n output = []\n l = len(seq)\n \n for i in range(l - ss):\n data = seq[i:i+ss]\n label = seq[i+ss:i+ss+1]\n output.append((data,label))\n \n return output",
"_____no_output_____"
],
[
"train_data = prep_data(train_norm, seq_size)",
"_____no_output_____"
],
[
"train_data[0]",
"_____no_output_____"
],
[
"# Model\nclass LSTM(nn.Module):\n def __init__(self, input_dim = 1, hidden_dim = hidden_dim, output_dim = 1):\n \n super().__init__()\n self.hidden_dim = hidden_dim\n \n self.lstm = nn.LSTM(input_dim, hidden_dim)\n self.fc1 = nn.Linear(hidden_dim, output_dim)\n \n self.hidden = (torch.zeros(1,1,hidden_dim), torch.zeros(1,1,hidden_dim))\n \n def forward(self, seq):\n \n lstm_out, self.hidden = self.lstm(seq.view(len(seq),1,-1), self.hidden)\n pred = self.fc1(lstm_out.view(len(seq), -1))\n \n return pred[-1]",
"_____no_output_____"
],
[
"# Initialise \ntorch.manual_seed(101)\nmodel = LSTM()\ncriterion = nn.MSELoss()\noptimizer = torch.optim.Adam(model.parameters(), lr = lr)",
"_____no_output_____"
],
[
"model",
"_____no_output_____"
],
[
"import time\nstart_time = time.time()\n\nfor i in range(epochs):\n for seq, y_train in train_data:\n \n optimizer.zero_grad()\n \n model.hidden = (torch.zeros(1,1,model.hidden_dim),torch.zeros(1,1,model.hidden_dim))\n \n y_pred = model(seq)\n \n loss = criterion(y_pred, y_train)\n loss.backward()\n optimizer.step()\n\n # training result\n print(f'Epoch: {i+1:2} | Loss: {loss.item():10.8f}')\n\n\ntotal_time = time.time() - start_time\nprint(f'Total time: {total_time}')",
"Epoch: 1 | Loss: 0.25310209\nEpoch: 2 | Loss: 0.37532014\nEpoch: 3 | Loss: 0.39027208\nEpoch: 4 | Loss: 0.34934691\nEpoch: 5 | Loss: 0.33085644\nEpoch: 6 | Loss: 0.33229983\nEpoch: 7 | Loss: 0.32670355\nEpoch: 8 | Loss: 0.32074136\nEpoch: 9 | Loss: 0.30653533\nEpoch: 10 | Loss: 0.29518044\nEpoch: 11 | Loss: 0.26934355\nEpoch: 12 | Loss: 0.25998515\nEpoch: 13 | Loss: 0.24665838\nEpoch: 14 | Loss: 0.22403999\nEpoch: 15 | Loss: 0.18602701\nEpoch: 16 | Loss: 0.18561199\nEpoch: 17 | Loss: 0.17209387\nEpoch: 18 | Loss: 0.25161543\nEpoch: 19 | Loss: 0.22557551\nEpoch: 20 | Loss: 0.17448561\nEpoch: 21 | Loss: 0.20235531\nEpoch: 22 | Loss: 0.20820044\nEpoch: 23 | Loss: 0.16648240\nEpoch: 24 | Loss: 0.17593351\nEpoch: 25 | Loss: 0.11984104\nEpoch: 26 | Loss: 0.09454037\nEpoch: 27 | Loss: 0.04441066\nEpoch: 28 | Loss: 0.07031668\nEpoch: 29 | Loss: 0.00536485\nEpoch: 30 | Loss: 0.10183812\nEpoch: 31 | Loss: 0.00055701\nEpoch: 32 | Loss: 0.01982624\nEpoch: 33 | Loss: 0.00999194\nEpoch: 34 | Loss: 0.02006591\nEpoch: 35 | Loss: 0.05408132\nEpoch: 36 | Loss: 0.01990136\nEpoch: 37 | Loss: 0.00079933\nEpoch: 38 | Loss: 0.00017501\nEpoch: 39 | Loss: 0.00509700\nEpoch: 40 | Loss: 0.00055661\nEpoch: 41 | Loss: 0.00275110\nEpoch: 42 | Loss: 0.00112076\nEpoch: 43 | Loss: 0.00168240\nEpoch: 44 | Loss: 0.00137513\nEpoch: 45 | Loss: 0.00187021\nEpoch: 46 | Loss: 0.00194726\nEpoch: 47 | Loss: 0.00224043\nEpoch: 48 | Loss: 0.00231688\nEpoch: 49 | Loss: 0.00264169\nEpoch: 50 | Loss: 0.00279988\nEpoch: 51 | Loss: 0.00279495\nEpoch: 52 | Loss: 0.00388771\nEpoch: 53 | Loss: 0.00483997\nEpoch: 54 | Loss: 0.00132214\nEpoch: 55 | Loss: 0.00239925\nEpoch: 56 | Loss: 0.00339044\nEpoch: 57 | Loss: 0.00194751\nEpoch: 58 | Loss: 0.00042605\nEpoch: 59 | Loss: 0.00085357\nEpoch: 60 | Loss: 0.00198053\nEpoch: 61 | Loss: 0.00145668\nEpoch: 62 | Loss: 0.00000073\nEpoch: 63 | Loss: 0.00004996\nEpoch: 64 | Loss: 0.00039795\nEpoch: 65 | Loss: 0.00129059\nEpoch: 66 | Loss: 0.00000590\nEpoch: 67 | Loss: 0.00026744\nEpoch: 68 | Loss: 0.00006398\nEpoch: 69 | Loss: 0.00007754\nEpoch: 70 | Loss: 0.00007493\nEpoch: 71 | Loss: 0.00006079\nEpoch: 72 | Loss: 0.00028319\nEpoch: 73 | Loss: 0.00147966\nEpoch: 74 | Loss: 0.00074516\nEpoch: 75 | Loss: 0.00050810\nEpoch: 76 | Loss: 0.00033451\nEpoch: 77 | Loss: 0.00195923\nEpoch: 78 | Loss: 0.00357065\nEpoch: 79 | Loss: 0.00416095\nEpoch: 80 | Loss: 0.00505571\nEpoch: 81 | Loss: 0.00405197\nEpoch: 82 | Loss: 0.00232818\nEpoch: 83 | Loss: 0.00337439\nEpoch: 84 | Loss: 0.00101866\nEpoch: 85 | Loss: 0.00402926\nEpoch: 86 | Loss: 0.00009946\nEpoch: 87 | Loss: 0.00426077\nEpoch: 88 | Loss: 0.00081407\nEpoch: 89 | Loss: 0.00069762\nEpoch: 90 | Loss: 0.00846574\nEpoch: 91 | Loss: 0.00219545\nEpoch: 92 | Loss: 0.00254774\nEpoch: 93 | Loss: 0.00002046\nEpoch: 94 | Loss: 0.00000065\nEpoch: 95 | Loss: 0.00136081\nEpoch: 96 | Loss: 0.00179724\nEpoch: 97 | Loss: 0.00030903\nEpoch: 98 | Loss: 0.00046421\nEpoch: 99 | Loss: 0.00032471\nEpoch: 100 | Loss: 0.00007281\nTotal time: 146.14146327972412\n"
],
[
"# Predictions\nfuture = 12\npreds = train_norm[-seq_size:].tolist()\n\nmodel.eval()\n\nfor i in range(future):\n seq = torch.FloatTensor(preds[-seq_size:])\n with torch.no_grad():\n model.hidden = (torch.zeros(1,1,model.hidden_dim),torch.zeros(1,1,model.hidden_dim))\n preds.append(model(seq).item())",
"_____no_output_____"
],
[
"preds[seq_size:]\n# prediction values normalised",
"_____no_output_____"
],
[
"true_preds = scaler.inverse_transform(np.array(preds[seq_size:]).reshape(-1,1))",
"_____no_output_____"
],
[
"true_preds",
"_____no_output_____"
],
[
"df['S4248SM144NCEN'][-12:]",
"_____no_output_____"
],
[
"x = np.arange('2018-02-01','2019-02-01', dtype = 'datetime64[M]')",
"_____no_output_____"
],
[
"# plot predicitons\nplt.figure(figsize=(12, 4))\nplt.title('Alcohol Sales')\nplt.ylabel('Sales (millions)')\nplt.grid(True)\nplt.autoscale(axis = 'x', tight = True)\nplt.plot(df['S4248SM144NCEN'])\nplt.plot(x, true_preds)\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e723bf447a3a64349a2535651038acc7aa9d80d4 | 2,717 | ipynb | Jupyter Notebook | notebooks/station_statistics.ipynb | avillasenorh/let-processing | 4d3a2f6d4fa98211e051343ce26a73586eff6f8e | [
"MIT"
] | null | null | null | notebooks/station_statistics.ipynb | avillasenorh/let-processing | 4d3a2f6d4fa98211e051343ce26a73586eff6f8e | [
"MIT"
] | null | null | null | notebooks/station_statistics.ipynb | avillasenorh/let-processing | 4d3a2f6d4fa98211e051343ce26a73586eff6f8e | [
"MIT"
] | null | null | null | 19.977941 | 111 | 0.529628 | [
[
[
"# Station statistics\n\nNotebook to read an earthquake bulletin in feather format and perform station statistics",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"Read feather file and load it into a pandas dataframe",
"_____no_output_____"
]
],
[
[
"df = pd.read_feather('ign.feather')",
"_____no_output_____"
]
],
[
[
"Select a station",
"_____no_output_____"
]
],
[
[
"station = 'MACI'\ndfs=df[df['station'] == station]\ndfs.head()",
"_____no_output_____"
]
],
[
[
"Plot residual as a function of epicentral distance",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots()\ndfs.plot(kind='scatter', x='distance', y='residual', ax=ax)\nax.set(title=station, xlabel='epicentral distance (km)', ylabel='residual (s)');",
"_____no_output_____"
]
],
[
[
"Plot epicenter map with earthquake color coded by P residual",
"_____no_output_____"
]
],
[
[
"dfs[dfs['phase'] == 'P'].plot(kind='scatter', x='longitude', y='latitude', c='depth');",
"_____no_output_____"
]
],
[
[
"Plot epicenter map with earthquake color coded by P residual",
"_____no_output_____"
]
],
[
[
"dfs[dfs['phase'] == 'P'].plot(kind='scatter', x='longitude', y='latitude', c='residual', cmap='seismic');",
"_____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"
]
] |
e723fb4da56a7c101eb3cda793cb5ca2abfc2460 | 4,221 | ipynb | Jupyter Notebook | install_quspin_by_miniconda.ipynb | ryuikaneko/google_colab_comp_phys | a2b677bf1b76ed8b0a77f91abe296ef59e63bff9 | [
"MIT"
] | 2 | 2020-08-30T16:02:22.000Z | 2021-04-19T03:29:02.000Z | install_quspin_by_miniconda.ipynb | ryuikaneko/google_colab_comp_phys | a2b677bf1b76ed8b0a77f91abe296ef59e63bff9 | [
"MIT"
] | null | null | null | install_quspin_by_miniconda.ipynb | ryuikaneko/google_colab_comp_phys | a2b677bf1b76ed8b0a77f91abe296ef59e63bff9 | [
"MIT"
] | null | null | null | 30.586957 | 148 | 0.511727 | [
[
[
"20201205\n\nPython version of google colaboratory is 3.8\n\nQuSpin works for python version <= 3.7\n\nNeed to activate older python each time to use QuSpin\n\nhttps://datascience.stackexchange.com/questions/75948/how-to-setup-and-run-conda-on-google-colab/75979#75979\n\nhttps://stackoverflow.com/questions/62610289/conda-activate-and-conda-init-fail-to-work-in-colab-as-per-june-2020\n\nhttps://github.com/weinbe58/QuSpin\n\nhttps://stackoverflow.com/questions/59330876/install-conda-package-to-google-colab\n\nhttps://stackoverflow.com/questions/53031430/conda-environment-in-google-colab-google-colaboratory\n\nhttps://github.com/weinbe58/QuSpin/issues/319\n\nhttps://github.com/weinbe58/QuSpin/issues/359\n\nhttps://github.com/conda/conda-build/issues/3938\n",
"_____no_output_____"
]
],
[
[
"# try to get the bare minimum to get a new conda env working\nconda_path = ''\ntry:\n conda_path = !which conda\nfinally:\n print('')\n\nif (len(conda_path) == 0):\n print('installing miniconda')\n !wget https://repo.continuum.io/miniconda/Miniconda3-4.5.4-Linux-x86_64.sh && bash Miniconda3-4.5.4-Linux-x86_64.sh -bfp /usr/local\n !conda update conda -y -q\n !source /usr/local/etc/profile.d/conda.sh\n !conda init \n !conda install -n root _license -y -q\nelse:\n print('found miniconda')\n\nconda_envs = !conda env list\nres = [i for i in conda_envs if 'test36' in i]\nif (len(res) == 0):\n print('not found test36 env', len(res))\n !conda create -y -q --name test36 python=3.6\nelse:\n print('found test36 env', len(res))\n",
"_____no_output_____"
],
[
"%%bash\nsource activate test36\n\npython\nimport sys\n# maybe only need this the first time we run this notebook\nsys.path.append('/usr/local/lib/python3.6/site-packages')\n\nprint(\"Python version\")\nprint(sys.version)\n",
"_____no_output_____"
],
[
"%%bash\nsource activate test36\n\nconda install -q -y -c weinbe58 quspin\nconda install -q -y matplotlib\n## downgrade numba to fix bug\n## https://github.com/weinbe58/QuSpin/issues/319\nconda install -q -y numba=0.48.0\n\n#wget https://raw.githubusercontent.com/weinbe58/QuSpin/master/examples/scripts/example0.py\n#python example0.py\n\nwget https://raw.githubusercontent.com/ryuikaneko/quspin_example/master/square__heisenberg__static/square_heisenberg.py\npython square_heisenberg.py > dat",
"_____no_output_____"
],
[
"!cat dat",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e723fe81d7621850054fd69d76c4f9eefb18cebb | 414,038 | ipynb | Jupyter Notebook | analysis/analyze_random_mpra_combined_logistic_regression.ipynb | 876lkj/APARENT | 5c8b9c038a46b129b5e0e5ce1453c4725b62322e | [
"MIT"
] | 20 | 2019-04-23T20:35:23.000Z | 2022-02-02T02:07:06.000Z | analysis/analyze_random_mpra_combined_logistic_regression.ipynb | lafleur1/aparentGenomeTesting | e945d36e63d207d23b1508a4d1b7e5f63d66e304 | [
"MIT"
] | 6 | 2019-10-14T16:35:00.000Z | 2021-03-24T17:55:07.000Z | analysis/analyze_random_mpra_combined_logistic_regression.ipynb | lafleur1/aparentGenomeTesting | e945d36e63d207d23b1508a4d1b7e5f63d66e304 | [
"MIT"
] | 11 | 2019-06-10T08:53:57.000Z | 2021-01-25T00:54:59.000Z | 855.450413 | 83,120 | 0.951775 | [
[
[
"import pandas as pd\n\nimport os\nimport pickle\nimport numpy as np\n\nimport scipy.sparse as sp\nimport scipy.io as spio\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\nimport isolearn.io as isoio\nimport isolearn.keras as iso\n\nimport scipy.optimize as spopt\nfrom scipy.stats import pearsonr\n\nfrom analyze_random_mpra_logistic_regression_helpers import *\n",
"Using TensorFlow backend.\n"
],
[
"#Load plasmid data\nplasmid_dict = isoio.load('../data/random_mpra_legacy/combined_library/processed_data_lifted/apa_plasmid_data_legacy')\ndf = plasmid_dict['plasmid_df']\n\n#Filter data on sublibrary TOMM5\nkeep_index = np.nonzero(df['library_index'].isin([2, 5, 8, 11, 20, 22]))[0]\ndf = df.iloc[keep_index].copy().reset_index(drop=True)\n\n#Filter on min read count\nkeep_index = np.nonzero(df['total_count'] >= 1)[0]\ndf = df.iloc[keep_index].copy().reset_index(drop=True)\n\nprint('n = ' + str(len(df)))\n",
"/home/johli/anaconda3/envs/aparent/lib/python3.6/site-packages/numpy/core/fromnumeric.py:56: FutureWarning: Series.nonzero() is deprecated and will be removed in a future version.Use Series.to_numpy().nonzero() instead\n return getattr(obj, method)(*args, **kwds)\n"
],
[
"#Generate training and test set indexes\ntest_set_size=8000 * 6\n\nplasmid_index = np.arange(len(df), dtype=np.int)\n\ntrain_index = plasmid_index[:-test_set_size]\ntest_index = plasmid_index[train_index.shape[0]:]\n\nprint('Training set size = ' + str(train_index.shape[0]))\nprint('Test set size = ' + str(test_index.shape[0]))",
"Training set size = 1946128\nTest set size = 48000\n"
],
[
"df = mask_constant_sequence_regions(df, add_padding=True)\ndf = align_on_cse(df)",
"_____no_output_____"
],
[
"#Initialize hexamer count data generator (separated by USE, CSE and DSE regions)\n\nhexamer_gens = {\n gen_id : iso.DataGenerator(\n idx,\n {\n 'df' : df\n },\n batch_size=len(idx),\n inputs = [\n {\n 'id' : 'use',\n 'source_type' : 'dataframe',\n 'source' : 'df',\n 'extractor' : lambda row, index: row['seq_var_aligned'][:46],\n 'encoder' : iso.NMerEncoder(n_mer_len=6, count_n_mers=True),\n 'sparse' : True,\n 'sparse_mode' : 'col'\n },\n {\n 'id' : 'cse',\n 'source_type' : 'dataframe',\n 'source' : 'df',\n 'extractor' : lambda row, index: row['seq_var_aligned'][50:56],\n 'encoder' : iso.NMerEncoder(n_mer_len=6, count_n_mers=True),\n 'sparse' : True,\n 'sparse_mode' : 'col'\n },\n {\n 'id' : 'dse',\n 'source_type' : 'dataframe',\n 'source' : 'df',\n 'extractor' : lambda row, index: row['seq_var_aligned'][59:99],\n 'encoder' : iso.NMerEncoder(n_mer_len=6, count_n_mers=True),\n 'sparse' : True,\n 'sparse_mode' : 'col'\n },\n {\n 'id' : 'fdse',\n 'source_type' : 'dataframe',\n 'source' : 'df',\n 'extractor' : lambda row, index: row['seq_var_aligned'][99:],\n 'encoder' : iso.NMerEncoder(n_mer_len=6, count_n_mers=True),\n 'sparse' : True,\n 'sparse_mode' : 'col'\n },\n {\n 'id' : 'lib',\n 'source_type' : 'dataframe',\n 'source' : 'df',\n 'extractor' : lambda row, index: row['library_index'],\n 'encoder' : iso.CategoricalEncoder(n_categories=36, categories=np.arange(36, dtype=np.int).tolist()),\n 'sparsify' : True\n },\n ],\n outputs = [\n {\n 'id' : 'proximal_usage',\n 'source_type' : 'dataframe',\n 'source' : 'df',\n 'extractor' : lambda row, index: row['proximal_count'] / row['total_count'],\n 'transformer' : lambda t: t\n }\n ],\n randomizers = [],\n shuffle = False,\n ) for gen_id, idx in [('train', train_index), ('test', test_index)]\n}",
"_____no_output_____"
],
[
"#Generate hexamer occurrence count matrices and corresponding isoform proportions\n\n[X_train_use, X_train_cse, X_train_dse, X_train_fdse, X_train_lib], y_train = hexamer_gens['train'][0]\ny_train = y_train[0]\n\n[X_test_use, X_test_cse, X_test_dse, X_test_fdse, X_test_lib], y_test = hexamer_gens['test'][0]\ny_test = y_test[0]",
"_____no_output_____"
],
[
"#Concatenate hexamer count matrices\n\nX_train = sp.csc_matrix(sp.hstack([X_train_lib, X_train_use, X_train_cse, X_train_dse, X_train_fdse]))\n\nX_test = sp.csc_matrix(sp.hstack([X_test_lib, X_test_use, X_test_cse, X_test_dse, X_test_fdse]))\n",
"_____no_output_____"
],
[
"print(\"Starting logistic n-mer regression...\")\n\nw_init = np.zeros(X_train.shape[1] + 1)\nlambda_penalty = 0\n\n(w_bundle, _, _) = spopt.fmin_l_bfgs_b(log_loss, w_init, fprime=log_loss_gradient, args=(X_train, y_train, lambda_penalty), maxiter = 200)\n\nprint(\"Regression finished.\")\n\n#Collect weights\nw_0 = w_bundle[0]\nw_L = w_bundle[1:1 + 36]\nw = w_bundle[1 + 36:]\n",
"_____no_output_____"
],
[
"#Store weights\ndata_version = 'all'\nmodel_version = '6mer_v_pasaligned_margin'\n\nw_bundle_no_lib = np.concatenate([np.array([w_0]), w], axis=0)\n\nnp.save('apa_regression_' + model_version + '_' + data_version + '_weights', w_bundle)\n\nstored_nmer_weights = {\n 'nmer' : [t[1] for t in sorted(hexamer_gens['train'].encoders['use'].encoder.decode_map.items(), key=lambda t: t[0])],\n 'use' : w[: 4096].tolist(),\n 'cse' : w[4096: 2 * 4096].tolist(),\n 'dse' : w[2 * 4096: 3 * 4096].tolist(),\n 'fdse' : w[3 * 4096: 4 * 4096].tolist(),\n}\n\nnmer_df = pd.DataFrame(stored_nmer_weights)\nnmer_df = nmer_df[['nmer', 'use', 'cse', 'dse', 'fdse']]\n\nnmer_df.to_csv('apa_regression_' + model_version + '_' + data_version + '_weights.csv', index=False, sep='\\t')",
"_____no_output_____"
],
[
"#Load weights\n#data_version = 'all'\n#model_version = '6mer_v_pasaligned_margin'\n#w_bundle = np.load('apa_regression_' + model_version + '_' + data_version + '_weights.npy')\n\n#Collect weights\n#w_0 = w_bundle[0]\n#w_L = w_bundle[1:1 + 36]\n#w = w_bundle[1 + 36:]",
"_____no_output_____"
],
[
"#Evaluate isoform logodds predictions on test set\n\ndef safe_log(x, minval=0.02):\n return np.log(x.clip(min=minval))\n\ny_test_pred = get_y_pred(X_test, np.concatenate([w_L, w]), w_0)\n\nfor lib in [2, 5, 8, 11, 20, 22] :\n\n keep_lib = np.nonzero(X_test_lib[:, lib] == 1)[0]\n y_test_pred_lib = y_test_pred[keep_lib]\n y_test_lib = y_test[keep_lib]\n\n #Compute Log Odds values\n keep_index = (y_test_lib < 0.99999)\n y_test_valid = y_test_lib[keep_index]\n y_test_pred_valid = y_test_pred_lib[keep_index]\n\n logodds_test = np.ravel(safe_log(y_test_valid / (1. - y_test_valid)))\n logodds_test_pred = np.ravel(safe_log(y_test_pred_valid / (1. - y_test_pred_valid)))\n\n r_val, p_val = pearsonr(logodds_test_pred, logodds_test)\n\n print(\"Test set R^2 = \" + str(round(r_val * r_val, 2)) + \", p = \" + str(p_val) + \", n = \" + str(y_test_pred_lib.shape[0]))\n\n #Plot test set scatter\n f = plt.figure(figsize=(5, 5))\n\n plt.scatter(logodds_test_pred, logodds_test, s = np.pi * (2 * np.ones(1))**2, alpha=0.05, color='black')\n min_x = max(np.min(logodds_test_pred), np.min(logodds_test))\n max_x = min(np.max(logodds_test_pred), np.max(logodds_test))\n min_y = max(np.min(logodds_test_pred), np.min(logodds_test))\n max_y = min(np.max(logodds_test_pred), np.max(logodds_test))\n plt.plot([min_x, max_x], [min_y, max_y], alpha=0.5, color='darkblue', linewidth=3)\n\n plt.xticks(fontsize=14)\n plt.yticks(fontsize=14)\n\n plt.xlabel('Pred Proximal Usage', fontsize=14)\n plt.ylabel('True Proximal Usage', fontsize=14)\n\n plt.axis([np.min(logodds_test_pred), np.max(logodds_test_pred), np.min(logodds_test), np.max(logodds_test)])\n\n plt.title('Sublibrary index ' + str(lib) + ' (R^2 = ' + str(round(r_val * r_val, 2)) + ', n = ' + str(y_test_pred_lib.shape[0]) + ')', fontsize=14)\n\n plt.tight_layout()\n plt.show()",
"Test set R^2 = 0.45, p = 0.0, n = 8000\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7240af62fc43208d6d66d04ebfc922574591861 | 98,351 | ipynb | Jupyter Notebook | models/ML Pipeline Preparation.ipynb | samyakjain3001/Disaster-Msg-Categorization | 333263a10432a30b05fa47f1b0ecaccee0e68924 | [
"MIT"
] | 1 | 2021-08-24T21:31:51.000Z | 2021-08-24T21:31:51.000Z | models/ML Pipeline Preparation.ipynb | samyakjain3001/Disaster-Msg-Categorization | 333263a10432a30b05fa47f1b0ecaccee0e68924 | [
"MIT"
] | null | null | null | models/ML Pipeline Preparation.ipynb | samyakjain3001/Disaster-Msg-Categorization | 333263a10432a30b05fa47f1b0ecaccee0e68924 | [
"MIT"
] | null | null | null | 59.211921 | 28,148 | 0.567102 | [
[
[
"# ML Pipeline Preparation\n### 1. Import libraries and load data from database.\n- Import Python libraries\n- Load dataset from database with [`read_sql_table`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_table.html)\n- Define feature and target variables X and Y",
"_____no_output_____"
]
],
[
[
"!pip install nltk\n!pip install plotly",
"_____no_output_____"
],
[
"import nltk\nnltk.download('punkt')\nnltk.download('wordnet')\nnltk.download('averaged_perceptron_tagger')",
"[nltk_data] Downloading package punkt to /home/samyakj/nltk_data...\n[nltk_data] Unzipping tokenizers/punkt.zip.\n[nltk_data] Downloading package wordnet to /home/samyakj/nltk_data...\n[nltk_data] Package wordnet is already up-to-date!\n[nltk_data] Downloading package averaged_perceptron_tagger to\n[nltk_data] /home/samyakj/nltk_data...\n[nltk_data] Package averaged_perceptron_tagger is already up-to-\n[nltk_data] date!\n"
],
[
"# import libraries\nimport numpy as np\nimport pandas as pd\npd.set_option('display.max_columns', 500)\n\nimport sys\nimport os\nimport re\nfrom sqlalchemy import create_engine\nimport pickle\n\nfrom scipy.stats import gmean\n# import relevant functions/modules from the sklearn\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import fbeta_score, make_scorer\nfrom sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom sklearn.base import BaseEstimator,TransformerMixin",
"_____no_output_____"
],
[
"# load data from database\ndatabase_filepath = \"../data/disaster_response_db.db\"\nengine = create_engine('sqlite:///' + database_filepath)\ntable_name = os.path.basename(database_filepath).replace(\".db\",\"\") + \"_table\"\ndf = pd.read_sql_table(table_name,engine)",
"_____no_output_____"
],
[
"df.describe()",
"_____no_output_____"
],
[
"df[df.death == 1].message[72]",
"_____no_output_____"
],
[
"df.iloc[:, 4:].sum().plot(kind=\"bar\")",
"_____no_output_____"
],
[
"#Remove child alone as it has all zeros only\ndf = df.drop(['child_alone'],axis=1)",
"_____no_output_____"
],
[
"df.groupby(\"related\").count()",
"_____no_output_____"
],
[
"# Given value 2 in the related field are neglible so it could be error. Replacing 2 with 1 to consider it a valid response.\n# Alternatively, we could have assumed it to be 0 also. In the absence of information I have gone with majority class.\ndf['related']=df['related'].map(lambda x: 1 if x == 2 else x)",
"_____no_output_____"
],
[
"# Extract X and y variables from the data for the modelling\nX = df['message']\ny = df.iloc[:,4:]",
"_____no_output_____"
]
],
[
[
"### 2. Tokenization function to process text data",
"_____no_output_____"
]
],
[
[
"def tokenize(text,url_place_holder_string=\"urlplaceholder\"):\n \"\"\"\n Tokenize the text function\n \n Arguments:\n text -> Text message which needs to be tokenized\n Output:\n clean_tokens -> List of tokens extracted from the provided text\n \"\"\"\n \n # Replace all urls with a urlplaceholder string\n url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\n \n # Extract all the urls from the provided text \n detected_urls = re.findall(url_regex, text)\n \n # Replace url with a url placeholder string\n for detected_url in detected_urls:\n text = text.replace(detected_url, url_place_holder_string)\n\n # Extract the word tokens from the provided text\n tokens = nltk.word_tokenize(text)\n \n #Lemmanitizer to remove inflectional and derivationally related forms of a word\n lemmatizer = nltk.WordNetLemmatizer()\n\n # List of clean tokens\n clean_tokens = [lemmatizer.lemmatize(w).lower().strip() for w in tokens]\n return clean_tokens",
"_____no_output_____"
],
[
"# Custom transformer which will extract the starting verb of a sentence\nclass StartingVerbExtractor(BaseEstimator, TransformerMixin):\n \"\"\"\n Starting Verb Extractor class\n \n This class extract the starting verb of a sentence,\n creating a new feature for the ML classifier\n \"\"\"\n\n def starting_verb(self, text):\n sentence_list = nltk.sent_tokenize(text)\n for sentence in sentence_list:\n pos_tags = nltk.pos_tag(tokenize(sentence))\n first_word, first_tag = pos_tags[0]\n if first_tag in ['VB', 'VBP'] or first_word == 'RT':\n return True\n return False\n\n # Given it is a tranformer we can return the self \n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n X_tagged = pd.Series(X).apply(self.starting_verb)\n return pd.DataFrame(X_tagged)",
"_____no_output_____"
]
],
[
[
"### 3. Machine learning pipeline\nThis machine pipeline should take in the `message` column as input and output classification results on the other 36 categories in the dataset. ",
"_____no_output_____"
]
],
[
[
"pipeline1 = Pipeline([\n ('features', FeatureUnion([\n\n ('text_pipeline', Pipeline([\n ('count_vectorizer', CountVectorizer(tokenizer=tokenize)),\n ('tfidf_transformer', TfidfTransformer())\n ]))\n \n ])),\n\n ('classifier', MultiOutputClassifier(AdaBoostClassifier()))\n ])\n\npipeline2 = Pipeline([\n ('features', FeatureUnion([\n\n ('text_pipeline', Pipeline([\n ('count_vectorizer', CountVectorizer(tokenizer=tokenize)),\n ('tfidf_transformer', TfidfTransformer())\n ])),\n\n ('starting_verb_transformer', StartingVerbExtractor())\n ])),\n\n ('classifier', MultiOutputClassifier(AdaBoostClassifier()))\n ])\n\n\n#pipeline = Pipeline(\n# [('count_vectorizer', CountVectorizer(tokenizer = tokenize)),\n# ('tfidf_transformer', TfidfTransformer()),\n# ('rf_classifier', RandomForestClassifier())\n# ])",
"_____no_output_____"
]
],
[
[
"### 4. Train pipeline\n- Split data into train and test sets\n- Train pipeline",
"_____no_output_____"
]
],
[
[
"X_train, X_test, y_train, y_test = train_test_split(X, y)\npipeline_fitted = pipeline1.fit(X_train, y_train)",
"_____no_output_____"
]
],
[
[
"### 5. Test model\nReport the f1 score, precision and recall for each output category of the dataset. You can do this by iterating through the columns and calling sklearn's `classification_report` on each.",
"_____no_output_____"
]
],
[
[
"y_prediction_train = pipeline_fitted.predict(X_train)\ny_prediction_test = pipeline_fitted.predict(X_test)\n\n# Print classification report on test data\nprint(classification_report(y_test.values, y_prediction_test, target_names=y.columns.values))",
" precision recall f1-score support\n\n related 0.82 0.94 0.88 5006\n request 0.78 0.52 0.63 1123\n offer 0.12 0.03 0.05 30\n aid_related 0.76 0.59 0.67 2704\n medical_help 0.64 0.24 0.35 537\n medical_products 0.64 0.30 0.40 352\n search_and_rescue 0.72 0.22 0.34 174\n security 0.33 0.07 0.11 118\n military 0.66 0.30 0.41 219\n water 0.70 0.65 0.68 409\n food 0.79 0.70 0.74 716\n shelter 0.76 0.55 0.64 529\n clothing 0.72 0.46 0.56 104\n money 0.48 0.25 0.33 142\n missing_people 0.58 0.16 0.25 93\n refugees 0.64 0.23 0.34 218\n death 0.74 0.42 0.54 313\n other_aid 0.51 0.13 0.21 863\ninfrastructure_related 0.43 0.10 0.16 439\n transport 0.78 0.20 0.32 318\n buildings 0.63 0.41 0.50 312\n electricity 0.65 0.26 0.37 133\n tools 0.33 0.09 0.14 34\n hospitals 0.26 0.07 0.12 67\n shops 0.00 0.00 0.00 33\n aid_centers 0.30 0.09 0.14 75\n other_infrastructure 0.43 0.08 0.13 308\n weather_related 0.85 0.66 0.74 1851\n floods 0.88 0.56 0.68 562\n storm 0.73 0.50 0.59 625\n fire 0.65 0.32 0.43 63\n earthquake 0.87 0.76 0.81 610\n cold 0.70 0.30 0.42 132\n other_weather 0.36 0.13 0.19 330\n direct_report 0.71 0.47 0.56 1260\n\n micro avg 0.77 0.58 0.66 20802\n macro avg 0.60 0.34 0.41 20802\n weighted avg 0.74 0.58 0.63 20802\n samples avg 0.64 0.50 0.51 20802\n\n"
],
[
"# Print classification report on training data\nprint('\\n',classification_report(y_train.values, y_prediction_train, target_names=y.columns.values))",
"\n precision recall f1-score support\n\n related 0.83 0.94 0.88 15088\n request 0.80 0.54 0.65 3351\n offer 0.55 0.14 0.22 88\n aid_related 0.77 0.61 0.68 8156\n medical_help 0.66 0.29 0.40 1547\n medical_products 0.71 0.34 0.46 961\n search_and_rescue 0.66 0.21 0.32 550\n security 0.47 0.07 0.13 353\n military 0.69 0.35 0.46 641\n water 0.78 0.66 0.71 1263\n food 0.81 0.71 0.75 2207\n shelter 0.81 0.55 0.66 1785\n clothing 0.77 0.45 0.57 301\n money 0.65 0.34 0.44 462\n missing_people 0.74 0.21 0.33 205\n refugees 0.63 0.26 0.36 657\n death 0.78 0.46 0.58 881\n other_aid 0.58 0.17 0.27 2583\ninfrastructure_related 0.52 0.11 0.19 1266\n transport 0.78 0.24 0.36 883\n buildings 0.72 0.44 0.55 1021\n electricity 0.65 0.33 0.44 399\n tools 0.57 0.10 0.18 125\n hospitals 0.46 0.12 0.19 216\n shops 0.54 0.08 0.14 87\n aid_centers 0.55 0.14 0.22 234\n other_infrastructure 0.45 0.10 0.16 843\n weather_related 0.86 0.67 0.75 5446\n floods 0.89 0.55 0.68 1593\n storm 0.78 0.55 0.64 1818\n fire 0.68 0.32 0.43 219\n earthquake 0.89 0.77 0.83 1845\n cold 0.71 0.37 0.49 398\n other_weather 0.60 0.20 0.30 1046\n direct_report 0.76 0.50 0.60 3815\n\n micro avg 0.80 0.60 0.68 62333\n macro avg 0.69 0.37 0.46 62333\n weighted avg 0.77 0.60 0.65 62333\n samples avg 0.65 0.52 0.53 62333\n\n"
]
],
[
[
"### 6. Improve model\nGrid search to find better parameters. ",
"_____no_output_____"
]
],
[
[
"# pipeline1.get_params().keys()\nparameters_grid = {'classifier__estimator__learning_rate': [0.01, 0.02, 0.05],\n 'classifier__estimator__n_estimators': [10, 20, 40]}\n\n#parameters_grid = {'classifier__estimator__n_estimators': [10, 20, 40]}\n\ncv = GridSearchCV(pipeline1, param_grid=parameters_grid, scoring='f1_micro', n_jobs=-1)\ncv.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# Get the prediction values from the grid search cross validator\ny_prediction_test = cv.predict(X_test)\ny_prediction_train = cv.predict(X_train)",
"_____no_output_____"
]
],
[
[
"### 7. Test model\nAccuracy, precision, and recall of the tuned model. \n",
"_____no_output_____"
]
],
[
[
"# Print classification report on test data\nprint(classification_report(y_test.values, y_prediction_test, target_names=y.columns.values))",
" precision recall f1-score support\n\n related 0.76 1.00 0.87 5006\n request 0.60 0.38 0.46 1094\n offer 0.00 0.00 0.00 29\n aid_related 0.80 0.19 0.31 2662\n medical_help 0.57 0.10 0.18 557\n medical_products 0.70 0.14 0.24 326\n search_and_rescue 0.62 0.19 0.29 167\n security 0.00 0.00 0.00 107\n military 0.25 0.01 0.01 190\n water 0.59 0.84 0.69 436\n food 0.78 0.69 0.73 715\n shelter 0.84 0.31 0.46 569\n clothing 1.00 0.01 0.02 100\n money 0.55 0.18 0.27 159\n missing_people 0.55 0.23 0.33 69\n refugees 0.75 0.01 0.03 207\n death 0.73 0.18 0.28 289\n other_aid 0.00 0.00 0.00 856\ninfrastructure_related 0.00 0.00 0.00 417\n transport 0.53 0.21 0.30 315\n buildings 0.00 0.00 0.00 305\n electricity 0.00 0.00 0.00 140\n tools 0.67 0.05 0.10 39\n hospitals 0.00 0.00 0.00 74\n shops 0.00 0.00 0.00 25\n aid_centers 0.00 0.00 0.00 71\n other_infrastructure 0.00 0.00 0.00 278\n weather_related 0.91 0.22 0.36 1823\n floods 0.91 0.35 0.50 541\n storm 0.77 0.26 0.39 597\n fire 0.51 0.37 0.43 73\n earthquake 0.88 0.63 0.74 630\n cold 0.70 0.19 0.30 139\n other_weather 0.64 0.14 0.23 346\n direct_report 0.63 0.38 0.47 1255\n\n micro avg 0.75 0.44 0.55 20606\n macro avg 0.49 0.21 0.26 20606\n weighted avg 0.66 0.44 0.47 20606\n samples avg 0.70 0.45 0.49 20606\n\n"
],
[
"# Print classification report on training data\nprint('\\n',classification_report(y_train.values, y_prediction_train, target_names=y.columns.values))",
"\n precision recall f1-score support\n\n related 0.77 1.00 0.87 15088\n request 0.61 0.38 0.47 3380\n offer 1.00 0.02 0.04 89\n aid_related 0.80 0.19 0.31 8198\n medical_help 0.66 0.12 0.20 1527\n medical_products 0.73 0.12 0.21 987\n search_and_rescue 0.64 0.19 0.29 557\n security 0.00 0.00 0.00 364\n military 0.33 0.00 0.00 670\n water 0.57 0.85 0.68 1236\n food 0.77 0.68 0.72 2208\n shelter 0.84 0.29 0.43 1745\n clothing 0.50 0.00 0.01 305\n money 0.56 0.16 0.24 445\n missing_people 0.71 0.27 0.39 229\n refugees 0.71 0.01 0.03 668\n death 0.76 0.16 0.26 905\n other_aid 0.00 0.00 0.00 2590\ninfrastructure_related 0.00 0.00 0.00 1288\n transport 0.60 0.26 0.36 886\n buildings 0.00 0.00 0.00 1028\n electricity 0.00 0.00 0.00 392\n tools 1.00 0.03 0.05 120\n hospitals 0.00 0.00 0.00 209\n shops 0.00 0.00 0.00 95\n aid_centers 0.00 0.00 0.00 238\n other_infrastructure 0.00 0.00 0.00 873\n weather_related 0.91 0.22 0.36 5474\n floods 0.92 0.33 0.49 1614\n storm 0.73 0.26 0.38 1846\n fire 0.51 0.42 0.46 209\n earthquake 0.90 0.66 0.76 1825\n cold 0.68 0.23 0.35 391\n other_weather 0.56 0.12 0.19 1030\n direct_report 0.63 0.39 0.48 3820\n\n micro avg 0.75 0.43 0.55 62529\n macro avg 0.53 0.21 0.26 62529\n weighted avg 0.67 0.43 0.46 62529\n samples avg 0.71 0.44 0.49 62529\n\n"
]
],
[
[
"### 8. Improving the model further:\n* other machine learning algorithms\n* add other features besides the TF-IDF",
"_____no_output_____"
]
],
[
[
"#cv.best_params_\n\n# pipeline2 which includes StartingVerbEstimator\nX_train, X_test, y_train, y_test = train_test_split(X, y)\npipeline_fitted = pipeline2.fit(X_train, y_train)\n\ny_prediction_train = pipeline_fitted.predict(X_train)\ny_prediction_test = pipeline_fitted.predict(X_test)\n\n# Print classification report on test data\nprint(classification_report(y_test.values, y_prediction_test, target_names=y.columns.values))",
" precision recall f1-score support\n\n related 0.83 0.94 0.88 5038\n request 0.80 0.53 0.64 1151\n offer 0.00 0.00 0.00 31\n aid_related 0.76 0.60 0.67 2710\n medical_help 0.56 0.21 0.30 528\n medical_products 0.68 0.35 0.46 332\n search_and_rescue 0.55 0.21 0.31 174\n security 0.37 0.11 0.17 102\n military 0.61 0.30 0.41 197\n water 0.74 0.66 0.70 436\n food 0.81 0.68 0.74 763\n shelter 0.77 0.55 0.64 562\n clothing 0.80 0.40 0.53 98\n money 0.50 0.25 0.33 137\n missing_people 0.39 0.14 0.20 66\n refugees 0.49 0.18 0.27 215\n death 0.75 0.41 0.53 297\n other_aid 0.51 0.13 0.20 854\ninfrastructure_related 0.47 0.09 0.15 418\n transport 0.62 0.23 0.34 313\n buildings 0.63 0.40 0.48 306\n electricity 0.59 0.26 0.36 134\n tools 0.14 0.03 0.04 38\n hospitals 0.19 0.05 0.07 64\n shops 0.00 0.00 0.00 24\n aid_centers 0.35 0.09 0.14 70\n other_infrastructure 0.36 0.07 0.12 290\n weather_related 0.85 0.64 0.73 1737\n floods 0.83 0.53 0.65 500\n storm 0.79 0.48 0.60 608\n fire 0.72 0.24 0.36 54\n earthquake 0.89 0.76 0.82 579\n cold 0.72 0.39 0.51 122\n other_weather 0.66 0.17 0.26 357\n direct_report 0.73 0.50 0.59 1268\n\n micro avg 0.78 0.58 0.66 20573\n macro avg 0.58 0.33 0.41 20573\n weighted avg 0.74 0.58 0.63 20573\n samples avg 0.64 0.51 0.52 20573\n\n"
],
[
"# Print classification report on training data\nprint('\\n',classification_report(y_train.values, y_prediction_train, target_names=y.columns.values))",
"\n precision recall f1-score support\n\n related 0.83 0.95 0.88 15056\n request 0.79 0.55 0.65 3323\n offer 0.62 0.11 0.19 87\n aid_related 0.77 0.60 0.68 8150\n medical_help 0.67 0.29 0.41 1556\n medical_products 0.71 0.35 0.47 981\n search_and_rescue 0.73 0.22 0.34 550\n security 0.46 0.08 0.14 369\n military 0.67 0.34 0.45 663\n water 0.77 0.68 0.72 1236\n food 0.82 0.69 0.75 2160\n shelter 0.80 0.55 0.65 1752\n clothing 0.77 0.45 0.57 307\n money 0.64 0.34 0.44 467\n missing_people 0.72 0.22 0.33 232\n refugees 0.66 0.26 0.38 660\n death 0.79 0.47 0.59 897\n other_aid 0.56 0.15 0.24 2592\ninfrastructure_related 0.51 0.13 0.20 1287\n transport 0.72 0.26 0.38 888\n buildings 0.72 0.43 0.54 1027\n electricity 0.67 0.33 0.44 398\n tools 0.71 0.08 0.15 121\n hospitals 0.44 0.12 0.19 219\n shops 0.50 0.07 0.13 96\n aid_centers 0.46 0.11 0.18 239\n other_infrastructure 0.49 0.12 0.19 861\n weather_related 0.86 0.67 0.75 5560\n floods 0.88 0.59 0.71 1655\n storm 0.80 0.49 0.60 1835\n fire 0.69 0.30 0.42 228\n earthquake 0.89 0.81 0.85 1876\n cold 0.77 0.39 0.52 408\n other_weather 0.57 0.17 0.27 1019\n direct_report 0.75 0.50 0.60 3807\n\n micro avg 0.79 0.60 0.68 62562\n macro avg 0.69 0.37 0.46 62562\n weighted avg 0.77 0.60 0.65 62562\n samples avg 0.66 0.52 0.53 62562\n\n"
]
],
[
[
"### 9. Export model as a pickle file",
"_____no_output_____"
]
],
[
[
"m = pickle.dumps('classifier.pkl')",
"_____no_output_____"
]
],
[
[
"### 10. Script\n`train_classifier.py` is the script that runs the steps above to create a database and export a model based on a new dataset specified by the user.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7241dbb86c0299e64dca178bd179527c0efba56 | 256,856 | ipynb | Jupyter Notebook | Fundamentals/2_Bloch_and_Q_Spheres.ipynb | Chasmiccoder/IBM-Quantum-Challenges | 49536987594cdb75220dde18bf2c5e69e58f3bc5 | [
"MIT"
] | null | null | null | Fundamentals/2_Bloch_and_Q_Spheres.ipynb | Chasmiccoder/IBM-Quantum-Challenges | 49536987594cdb75220dde18bf2c5e69e58f3bc5 | [
"MIT"
] | null | null | null | Fundamentals/2_Bloch_and_Q_Spheres.ipynb | Chasmiccoder/IBM-Quantum-Challenges | 49536987594cdb75220dde18bf2c5e69e58f3bc5 | [
"MIT"
] | null | null | null | 856.186667 | 49,018 | 0.95638 | [
[
[
"### Bloch Sphere vs. Q Sphere\n\nExploring the advantages and disadvantages of both Bloch Spheres and the Q-Spheres when\nit comes to visualizing qubits\n\n---\nDone as part of the NPTEL Course - Introduction to Quantum Computing: Quantum Algorithms and Qiskit\nhttps://onlinecourses.nptel.ac.in/noc21_cs103/preview",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\nfrom qiskit import QuantumCircuit, transpile, Aer, IBMQ, execute\nfrom qiskit.visualization import plot_state_qsphere, plot_bloch_multivector\nfrom ibm_quantum_widgets import *\nfrom qiskit.tools.jupyter import *\n\nprovider = IBMQ.load_account()\n\nprint(\"Process Complete!\")",
"ibmqfactory.load_account:WARNING:2021-09-06 15:55:18,633: Credentials are already in use. The existing account in the session will be replaced.\n"
],
[
"qc = QuantumCircuit(1)\n\nstatevector_simulator = Aer.get_backend('statevector_simulator')\n\nresult = execute(qc, statevector_simulator).result()\n\nstatevector_results = result.get_statevector(qc)\nplot_bloch_multivector(statevector_results)\n",
"/opt/conda/lib/python3.8/site-packages/qiskit/visualization/bloch.py:68: MatplotlibDeprecationWarning: \nThe M attribute was deprecated in Matplotlib 3.4 and will be removed two minor releases later. Use self.axes.M instead.\n x_s, y_s, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n"
],
[
"plot_state_qsphere(statevector_results)",
"/opt/conda/lib/python3.8/site-packages/qiskit/visualization/bloch.py:68: MatplotlibDeprecationWarning: \nThe M attribute was deprecated in Matplotlib 3.4 and will be removed two minor releases later. Use self.axes.M instead.\n x_s, y_s, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n"
],
[
"# Using the Pauli X Gate (NOT Gate) on the 0th qubit\nqc.x(0)\nresult = execute(qc, statevector_simulator).result()\nstatevector_results = result.get_statevector(qc)\n\nplot_bloch_multivector(statevector_results)\n",
"/opt/conda/lib/python3.8/site-packages/qiskit/visualization/bloch.py:68: MatplotlibDeprecationWarning: \nThe M attribute was deprecated in Matplotlib 3.4 and will be removed two minor releases later. Use self.axes.M instead.\n x_s, y_s, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n"
],
[
"plot_state_qsphere(statevector_results)",
"/opt/conda/lib/python3.8/site-packages/qiskit/visualization/bloch.py:68: MatplotlibDeprecationWarning: \nThe M attribute was deprecated in Matplotlib 3.4 and will be removed two minor releases later. Use self.axes.M instead.\n x_s, y_s, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n"
],
[
"# Setting up the 0th Qubit in Superposition\nqc.h(0)\n\nresult = execute(qc, statevector_simulator).result()\nstatevector_results = result.get_statevector(qc)\n\nplot_bloch_multivector(statevector_results) # Plots the |-> state \n",
"/opt/conda/lib/python3.8/site-packages/qiskit/visualization/bloch.py:68: MatplotlibDeprecationWarning: \nThe M attribute was deprecated in Matplotlib 3.4 and will be removed two minor releases later. Use self.axes.M instead.\n x_s, y_s, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n"
],
[
"plot_state_qsphere(statevector_results) # Plots the |-> state\n\n# Here we see a difference\n# Radius of the circle is a measure of that state's amplitude\n# In the Q Sphere, we can see the constituents of the superposition, which is helpful (linear combination of basis states)\n# Basis states - Longitudinal, Phase Shifts - Latitudinal\n# |0> is in phase, but |1> is out of phase by pi radians",
"/opt/conda/lib/python3.8/site-packages/qiskit/visualization/bloch.py:68: MatplotlibDeprecationWarning: \nThe M attribute was deprecated in Matplotlib 3.4 and will be removed two minor releases later. Use self.axes.M instead.\n x_s, y_s, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e72422bf0c23d7d2f9bfd838c5b63a9f53f5ac4a | 78,528 | ipynb | Jupyter Notebook | notebooks/.ipynb_checkpoints/KinematicsParticle-checkpoint.ipynb | ofgod2/Biomec-nica-y-Comtrol-de-Motor | 4fb332309e3aa648041f1db6c325d57014b2a1df | [
"CC-BY-4.0"
] | 2 | 2020-03-18T01:39:12.000Z | 2020-04-12T19:16:48.000Z | notebooks/.ipynb_checkpoints/KinematicsParticle-checkpoint.ipynb | erichuang2013/BMC | 18c08d9b581672fcf8e1132e37da2ee978f315dc | [
"CC-BY-4.0"
] | null | null | null | notebooks/.ipynb_checkpoints/KinematicsParticle-checkpoint.ipynb | erichuang2013/BMC | 18c08d9b581672fcf8e1132e37da2ee978f315dc | [
"CC-BY-4.0"
] | null | null | null | 93.597139 | 46,416 | 0.815964 | [
[
[
"# Kinematics of particle\n\n> Marcos Duarte, Renato Naville Watanabe \n> [Laboratory of Biomechanics and Motor Control](http://pesquisa.ufabc.edu.br/bmclab) \n> Federal University of ABC, Brazil",
"_____no_output_____"
],
[
"## Biomechanics & Mechanics\n\n**A good knowledge of Mechanics is a necessary condition, although not sufficient!, to master Biomechanics**\n\nFor this reason, we will review principles of Classical Mechanics in the context of Biomechanics. \n\nThe book [*Introduction to Statics and Dynamics*](http://ruina.tam.cornell.edu/Book/index.html) , written by Andy Ruina and Rudra Pratap, is an excellent reference (a rigorous and yet didactic presentation of Mechanics for undergraduate students) on Classical Mechanics and we will use this book as the main reference on Mechanics and Mathematics for this brief review. The preface and first chapter of the book are a good read on how someone should study Mechanics. You should read them!\n\nAs we argued in the notebook [Biomechanics](http://nbviewer.jupyter.org/github/demotu/BMC/blob/master/notebooks/Biomechanics.ipynb), we will start with a branch of Classical Mechanics that is simpler to measure its related quantities on biological systems, the Kinematics. \n\nThere are some relevant cases in the study of human movement where modeling the human body or one of its segments as a particle might be all we need to explore the phenomenon. The concept of kinematics of a particle, for instance, can be applied to study the performance in the 100-m race; to describe spatial and temporal characteristics of a movement pattern, and to conjecture about how voluntary movements are planned (the minimum jerk hypothesis). \n\nNow, let's review the concept of kinematics of a particle and later apply to the study of human movement.",
"_____no_output_____"
],
[
"## Kinematics\n\n**Kinematics** is the branch of Classical Mechanics that describes the motion of objects without consideration of the causes of motion ([Wikipedia](http://en.wikipedia.org/wiki/Kinematics)). \n\nKinematics of a particle is the description of the motion when the object is considered a particle. \n\nA particle as a physical object does not exist in nature; it is a simplification to understand the motion of a body or it is a conceptual definition such as the center of mass of a system of objects.",
"_____no_output_____"
],
[
"### Vectors in Kinematics\n\nSome mechanical quantities in Kinematics (position and its derivatives) are represented as vectors and others, such as time and distance, are scalars. \nA vector in Mechanics is a physical quantity with magnitude, direction, and satisfies some elementary vector arithmetic, whereas a scalar is a physical quantity that is fully expressed by a magnitude (a number) only. \n\nFor a review about scalars and vectors, see chapter 1 of [Ruina and Rudra's book](http://ruina.tam.cornell.edu/Book/index.html). \n\n For how to use Python to work with scalars and vectors, see the notebook [Scalar and Vector](http://nbviewer.jupyter.org/github/BMCLab/BMC/blob/master/notebooks/ScalarVector.ipynb).",
"_____no_output_____"
],
[
"## Position\n\nConsider a point in the three-dimensional Euclidean space described in a Cartesian coordinate system (see the notebook [Frame of reference](http://nbviewer.jupyter.org/github/demotu/BMC/blob/master/notebooks/ReferenceFrame.ipynb) for an introduction on coordinate systems in Mechanics and Biomechanics): \n<br>\n<figure><img src=\"./../images/vector3Dijk.png\" width=350/><figcaption><center><i>Figure. Representation of a point $\\mathbf{P}$ and its position vector $\\overrightarrow{\\mathbf{r}}$ in a Cartesian coordinate system. The versors <span class=\"notranslate\">$\\hat{\\mathbf{i}},\\, \\hat{\\mathbf{j}},\\, \\hat{\\mathbf{k}}\\,$ </span> form a basis for this coordinate system and are usually represented in the color sequence RGB (red, green, blue) for easier visualization.</i></center></figcaption></figure> ",
"_____no_output_____"
],
[
"The position of this point in space can be represented as a triple of values each representing the coordinate at each axis of the Cartesian coordinate system following the $ \\mathbf{X, Y, Z} $ convention order (which is omitted):\n\n<span class=\"notranslate\">\n\\begin{equation}\n(x,\\, y,\\, z)\n\\label{eq_xyz}\n\\end{equation}\n</span>",
"_____no_output_____"
],
[
"The position of a particle in space can also be represented by a vector in the Cartesian coordinate system, with the origin of the vector at the origin of the coordinate system and the tip of the vector at the point position:\n\n<span class=\"notranslate\">\n\\begin{equation}\n\\overrightarrow{\\mathbf{r}}(t) = x\\,\\hat{\\mathbf{i}} + y\\,\\hat{\\mathbf{j}} + z\\,\\hat{\\mathbf{k}}\n\\label{eq_rxyz}\n\\end{equation} \n</span>\n\nWhere <span class=\"notranslate\"> $\\hat{\\mathbf{i}},\\, \\hat{\\mathbf{j}},\\, \\hat{\\mathbf{k}}\\,$ </span> are unit vectors in the directions of the axes $ \\mathbf{X, Y, Z} $. \n\nFor a review on vectors, see the notebook [Scalar and vector](http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/ScalarVector.ipynb).",
"_____no_output_____"
],
[
"With this new notation, the coordinates of a point representing the position of a particle that vary with time would be expressed by the following position vector $\\overrightarrow{\\mathbf{r}}(t)$: \n\n<span class=\"notranslate\">\n\\begin{equation}\n\\overrightarrow{\\mathbf{r}}(t) = x(t)\\,\\hat{\\mathbf{i}} + y(t)\\,\\hat{\\mathbf{j}} + z(t)\\,\\hat{\\mathbf{k}}\n\\label{eq_rxyzijk}\n\\end{equation}\n</span>",
"_____no_output_____"
],
[
"A vector can also be represented in matrix form:\n\n<span class=\"notranslate\">\n\\begin{equation}\n\\overrightarrow{\\mathbf{r}}(t) = \\begin{bmatrix} x(t) \\\\y(t) \\\\z(t) \\end{bmatrix}\n\\label{eq_rxyzmatrix}\n\\end{equation}\n</span>",
"_____no_output_____"
],
[
"And the unit vectors in each Cartesian coordinate in matrix form are given by:\n\n<span class=\"notranslate\">\n\\begin{equation}\n\\hat{\\mathbf{i}} = \\begin{bmatrix}1\\\\0\\\\0 \\end{bmatrix},\\; \\hat{\\mathbf{j}} = \\begin{bmatrix}0\\\\1\\\\0 \\end{bmatrix},\\; \\hat{\\mathbf{k}} = \\begin{bmatrix} 0 \\\\ 0 \\\\ 1 \\end{bmatrix}\n\\label{eq_ijk}\n\\end{equation}\n</span>",
"_____no_output_____"
],
[
"## Basis\n\nIn [linear algebra](http://en.wikipedia.org/wiki/Linear_algebra), a set of unit linearly independent vectors as the three vectors above (orthogonal in the Euclidean space) that can represent any vector via [linear combination](http://en.wikipedia.org/wiki/Linear_combination) is called a basis. A basis is the foundation of creating a reference frame and we will study how to do that other time. ",
"_____no_output_____"
],
[
"## Displacement\n\nThe shortest distance between two positions of a particle. \n\nAs the difference between two vectors, displacement is also a vector quantity.\n\n<span class=\"notranslate\">\n\\begin{equation}\n\\mathbf{\\overrightarrow{d}} = \\mathbf{\\overrightarrow{r}_2} - \\mathbf{\\overrightarrow{r}_1}\n\\label{eq_distance}\n\\end{equation}\n</span>\n\n<figure><img src=\"./../images/displacement.png\" width=550/><figcaption><center><i>Figure. Representation of the displacement vector $\\mathbf{\\overrightarrow{d}}$ between two positions $\\mathbf{\\overrightarrow{r}_1}$ and $\\mathbf{\\overrightarrow{r}_2}$.</i></center></figcaption></figure> ",
"_____no_output_____"
],
[
"## Velocity\n\nVelocity is the rate (with respect to time) of change of the position of a particle. \n\nThe average velocity between two instants is:\n\n<span class=\"notranslate\">\n\\begin{equation}\n\\overrightarrow{\\mathbf{v}}(t) = \\frac{\\overrightarrow{\\mathbf{r}}(t_2)-\\overrightarrow{\\mathbf{r}}(t_1)}{t_2-t_1} = \\frac{\\Delta \\overrightarrow{\\mathbf{r}}}{\\Delta t}\n\\label{eq_velocity}\n\\end{equation}\n</span> \n\nThe instantaneous velocity of the particle is obtained when $\\Delta t$ approaches to zero, which from calculus is the first-order [derivative](http://en.wikipedia.org/wiki/Derivative) of the position vector:\n\n<span class=\"notranslate\">\n\\begin{equation}\n\\overrightarrow{\\mathbf{v}}(t) = \\lim_{\\Delta t \\to 0} \\frac{\\Delta \\overrightarrow{\\mathbf{r}}}{\\Delta t} = \\lim_{\\Delta t \\to 0} \\frac{\\overrightarrow{\\mathbf{r}}(t+\\Delta t)-\\overrightarrow{\\mathbf{r}}(t)}{\\Delta t} = \\frac{\\mathrm{d}\\overrightarrow{\\mathbf{r}}}{dt}\n\\label{eq_velocityderiv}\n\\end{equation}\n</span> \n\nFor the movement of a particle described with respect to an [inertial Frame of reference](http://nbviewer.jupyter.org/github/demotu/BMC/blob/master/notebooks/ReferenceFrame.ipynb), the derivative of a vector is obtained by differentiating each vector component of the Cartesian coordinates (since the base versors <span class=\"notranslate\"> $\\hat{\\mathbf{i}}, \\hat{\\mathbf{j}}, \\hat{\\mathbf{k}}$ </span> are constant): \n\n<span class=\"notranslate\">\n\\begin{equation}\n\\overrightarrow{\\mathbf{v}}(t) = \\frac{\\mathrm{d}\\overrightarrow{\\mathbf{r}}(t)}{dt} = \\frac{\\mathrm{d}x(t)}{\\mathrm{d}t}\\hat{\\mathbf{i}} + \\frac{\\mathrm{d}y(t)}{\\mathrm{d}t}\\hat{\\mathbf{j}} + \\frac{\\mathrm{d}z(t)}{\\mathrm{d}t}\\hat{\\mathbf{k}}\n\\label{eq_velocityderiv2}\n\\end{equation}\n</span>\n\nOr in matrix form (and using the Newton's notation for differentiation):\n\n<span class=\"notranslate\">\n\\begin{equation} \n\\overrightarrow{\\mathbf{v}}(t) = \\begin{bmatrix}\n\\dot x(t) \\\\\n\\dot y(t) \\\\\n\\dot z(t)\n\\end{bmatrix}\n\\label{eq_velocityderiv3}\n\\end{equation}\n</span>",
"_____no_output_____"
],
[
"## Acceleration \n\nAcceleration is the rate (with respect to time) of change of the velocity of a particle, which can also be given by the second-order rate of change of the position.\n\nThe average acceleration between two instants is:\n\n<span class=\"notranslate\">\n\\begin{equation}\n\\overrightarrow{\\mathbf{a}}(t) = \\frac{\\overrightarrow{\\mathbf{v}}(t_2)-\\overrightarrow{\\mathbf{v}}(t_1)}{t_2-t_1} = \\frac{\\Delta \\overrightarrow{\\mathbf{v}}}{\\Delta t}\n\\label{eq_acc}\n\\end{equation}\n</span>\n\nLikewise, instantaneous acceleration is the first-order derivative of the velocity or the second-order derivative of the position vector: \n\n<span class=\"notranslate\">\n\\begin{equation} \n\\overrightarrow{\\mathbf{a}}(t) = \\frac{\\mathrm{d}\\overrightarrow{\\mathbf{v}}(t)}{\\mathrm{d}t} = \\frac{\\mathrm{d}^2\\overrightarrow{\\mathbf{r}}(t)}{\\mathrm{d}t^2} = \\frac{\\mathrm{d}^2x(t)}{\\mathrm{d}t^2}\\hat{\\mathbf{i}} + \\frac{\\mathrm{d}^2y(t)}{\\mathrm{d}t^2}\\hat{\\mathbf{j}} + \\frac{\\mathrm{d}^2z(t)}{\\mathrm{d}t^2}\\hat{\\mathbf{k}}\n\\label{eq_accderiv}\n\\end{equation}\n</span>\n\nAnd in matrix form:\n\n<span class=\"notranslate\">\n\\begin{equation} \n\\mathbf{a}(t) = \\begin{bmatrix}\n\\ddot x(t) \\\\\n\\ddot y(t) \\\\\n\\ddot z(t)\n\\end{bmatrix}\n\\label{eq_accderiv2}\n\\end{equation}\n</span>",
"_____no_output_____"
],
[
"For curiosity, see [Notation for differentiation](https://en.wikipedia.org/wiki/Notation_for_differentiation) on the origin of the different notations for differentiation.\n\nWhen the base versors change in time, for instance when the basis is attached to a rotating frame or reference, the components of the vector’s derivative is not the derivatives of its components; we will also have to consider the derivative of the basis with respect to time.",
"_____no_output_____"
],
[
"## The antiderivative\n\nAs the acceleration is the derivative of the velocity which is the derivative of position, the inverse mathematical operation is the [antiderivative](http://en.wikipedia.org/wiki/Antiderivative) (or integral):\n\n<span class=\"notranslate\">\n\\begin{equation} \n\\begin{array}{l l}\n\\mathbf{r}(t) = \\mathbf{r}_0 + \\int \\mathbf{v}(t) \\:\\mathrm{d}t \\\\\n\\mathbf{v}(t) = \\mathbf{v}_0 + \\int \\mathbf{a}(t) \\:\\mathrm{d}t \n\\end{array}\n\\label{eq_antiderivative}\n\\end{equation}\n</span>",
"_____no_output_____"
],
[
"**This part of the kinematics is presented in chapter 12, pages 605-620, of the [Ruina and Rudra's book](http://ruina.tam.cornell.edu/Book/index.html).** ",
"_____no_output_____"
],
[
"## Some cases of motion of a particle\n\nTo deduce some trivial cases of motion of a particle (at rest, at constant speed, and at constant acceleration), we can start from the equation for its position and differentiate it to obtain expressions for the velocity and acceleration or the inverse approach, start with the equation for acceleration, and then integrate it to obtain the velocity and position of the particle. Both approachs are valid in Mechanics. For the present case, it probaly makes more sense to start with the expression for acceleration.\n\n#### Particle at rest\n\n<span class=\"notranslate\">\n\\begin{equation} \n\\begin{array}{l l}\n\\overrightarrow{\\mathbf{a}}(t) = 0 \\\\\n\\overrightarrow{\\mathbf{v}}(t) = 0 \\\\\n\\overrightarrow{\\mathbf{r}}(t) = \\overrightarrow{\\mathbf{r}}_0\n\\end{array}\n\\label{eq_rest}\n\\end{equation}\n</span>",
"_____no_output_____"
],
[
"#### Particle at constant speed\n\n<span class=\"notranslate\">\n\\begin{equation} \n\\begin{array}{l l}\n\\overrightarrow{\\mathbf{a}}(t) = 0 \\\\\n\\overrightarrow{\\mathbf{v}}(t) = \\overrightarrow{\\mathbf{v}}_0 \\\\\n\\overrightarrow{\\mathbf{r}}(t) = \\overrightarrow{\\mathbf{r}}_0 + \\overrightarrow{\\mathbf{v}}_0t\n\\end{array}\n\\label{eq_constantspeed}\n\\end{equation}\n</span>",
"_____no_output_____"
],
[
"#### Particle at constant acceleration\n\n<span class=\"notranslate\">\n\\begin{equation} \n\\begin{array}{l l}\n\\overrightarrow{\\mathbf{a}}(t) = \\overrightarrow{\\mathbf{a}}_0 \\\\\n\\overrightarrow{\\mathbf{v}}(t) = \\overrightarrow{\\mathbf{v}}_0 + \\overrightarrow{\\mathbf{a}}_0t \\\\\n\\overrightarrow{\\mathbf{r}}(t) = \\overrightarrow{\\mathbf{r}}_0 + \\overrightarrow{\\mathbf{v}}_0t + \n\\frac{1}{2}\\overrightarrow{\\mathbf{a}}_0 t^2 \n\\end{array}\n\\label{eq_constantacceleration}\n\\end{equation}\n</span>",
"_____no_output_____"
],
[
"### Visual representation of these cases",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nsns.set_context(\"notebook\", font_scale=1.2, rc={\"lines.linewidth\": 2, \"lines.markersize\": 10})",
"_____no_output_____"
],
[
"t = np.arange(0, 2.0, 0.02)\nr0 = 1; v0 = 2; a0 = 4\n\nplt.rc('axes', labelsize=14, titlesize=14) \nplt.rc('xtick', labelsize=10)\nplt.rc('ytick', labelsize=10) \nf, axarr = plt.subplots(3, 3, sharex = True, sharey = True, figsize=(14,7))\nplt.suptitle('Scalar kinematics of a particle', fontsize=20);\n\ntones = np.ones(np.size(t))\n\naxarr[0, 0].set_title('at rest', fontsize=14);\naxarr[0, 0].plot(t, r0*tones, 'g', linewidth=4, label='$r(t)=1$')\naxarr[1, 0].plot(t, 0*tones, 'b', linewidth=4, label='$v(t)=0$')\naxarr[2, 0].plot(t, 0*tones, 'r', linewidth=4, label='$a(t)=0$')\naxarr[0, 0].set_ylabel('r(t) [m]')\naxarr[1, 0].set_ylabel('v(t) [m/s]')\naxarr[2, 0].set_ylabel('a(t) [m/s$^2$]')\n\naxarr[0, 1].set_title('at constant speed');\naxarr[0, 1].plot(t, r0*tones+v0*t, 'g', linewidth=4, label='$r(t)=1+2t$')\naxarr[1, 1].plot(t, v0*tones, 'b', linewidth=4, label='$v(t)=2$')\naxarr[2, 1].plot(t, 0*tones, 'r', linewidth=4, label='$a(t)=0$')\n\naxarr[0, 2].set_title('at constant acceleration');\naxarr[0, 2].plot(t, r0*tones+v0*t+1/2.*a0*t**2,'g', linewidth=4,\n label='$r(t)=1+2t+\\\\frac{1}{2}4t^2$')\naxarr[1, 2].plot(t, v0*tones+a0*t, 'b', linewidth=4,\n label='$v(t)=2+4t$')\naxarr[2, 2].plot(t, a0*tones, 'r', linewidth=4,\n label='$a(t)=4$')\n\nfor i in range(3): \n axarr[2, i].set_xlabel('Time [s]');\n for j in range(3):\n axarr[i,j].set_ylim((-.2, 10))\n axarr[i,j].legend(loc = 'upper left', frameon=True, framealpha = 0.9, fontsize=16)\n \nplt.subplots_adjust(hspace=0.09, wspace=0.07)",
"_____no_output_____"
]
],
[
[
"## Symbolic programming\n\nWe can use [Sympy](http://www.sympy.org/en/index.html), a Python library for symbolic mathematics, to deduce the expressions for the cases of motion of a particle we just visualized. \nLet's show how to integrate with Sympy for the case of particle with constant acceleration:",
"_____no_output_____"
]
],
[
[
"from sympy import Symbol, integrate, init_printing\ninit_printing(use_latex='mathjax')\n\nt = Symbol('t', real=True, positive=True)\ng = Symbol('g', real=True, positive=True)\nv0 = Symbol('v0', real=True, positive=True, constant = True)\nr0 = Symbol('r0', real=True, positive=True, constant = True)",
"_____no_output_____"
],
[
"v = integrate(g, t) + v0 # a constant has to be added\nv",
"_____no_output_____"
],
[
"r = integrate(v, t) + r0 # a constant has to be added\nr",
"_____no_output_____"
]
],
[
[
"## Kinematics of human movement",
"_____no_output_____"
],
[
"### Kinematics of the 100-m race\n\nAn example where the analysis of some aspects of the human body movement can be reduced to the analysis of a particle is the study of the Biomechanics of the 100-m race. \n\nA technical report with the kinematic data for the 100-m world record by Usain Bolt can be downloaded from the [website for Research Projects](http://www.iaaf.org/development/research) from the International Association of Athletics Federations. \n[Here is a direct link for that report](http://www.iaaf.org/download/download?filename=76ade5f9-75a0-4fda-b9bf-1b30be6f60d2.pdf&urlSlug=1-biomechanics-report-wc-berlin-2009-sprint). In particular, the following table shows the data for the three medalists in that race: \n<br>\n<figure><img src=\"./../images/Berlin2009_100m.png\" width=700 alt=\"partial times of the 100m-race at Berlin 2009\"/><figcaption><center><i>Figure. Data from the three medalists of the 100-m dash in Berlin, 2009 (<a href=\"http://www.iaaf.org/download/download?filename=76ade5f9-75a0-4fda-b9bf-1b30be6f60d2.pdf&urlSlug=1-biomechanics-report-wc-berlin-2009-sprint)\">IAAF report</a>).</i></center></figcaption></figure>\n\nThe column **RT** in the table above refers to the reaction time of each athlete. The IAAF has a very strict rule about reaction time: any athlete with a reaction time less than 100 ms is disqualified from the competition! See the website [Reaction Times and Sprint False Starts](http://condellpark.com/kd/reactiontime.htm) for a discussion about this rule.\n\nYou can measure your own reaction time in a simple way visiting this website: [http://www.humanbenchmark.com/tests/reactiontime](http://www.humanbenchmark.com/tests/reactiontime).\n\nThe article [A Kinematics Analysis Of Three Best 100 M Performances Ever](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3661886/) by Krzysztof and Mero presents a detailed kinematic analysis of 100-m races. ",
"_____no_output_____"
],
[
"### Spatial and temporal characteristics of a movement pattern\n\nSee the notebook [Spatial and temporal characteristics](http://nbviewer.jupyter.org/github/demotu/BMC/blob/master/notebooks/SpatialTemporalCharacteristcs.ipynb) about how the simple measurement of spatial and temporal kinematic variables can be very useful to describe the human gait.",
"_____no_output_____"
],
[
"### The minimum jerk hypothesis\n\nSee the notebook [The minimum jerk hypothesis](http://nbviewer.jupyter.org/github/demotu/BMC/blob/master/notebooks/MinimumJerkHypothesis.ipynb) about the conjecture that movements are performed (organized) with the smoothest trajectory possible.",
"_____no_output_____"
],
[
"## Problems\n\n1. Read the preface and first chapter of the [Ruina and Rudra's book](http://ruina.tam.cornell.edu/Book/index.html) about how someone should study Mechanics. \n\n2. Consider the data for the three medalists of the 100-m dash in Berlin, 2009, shown previously. \n a. Calculate the average velocity and acceleration. \n b. Plot the graphs for the displacement, velocity, and acceleration versus time. \n c. Plot the graphs velocity and acceleration versus partial distance (every 20m). \n d. Calculate the average velocity and average acceleration and the instants and values of the peak velocity and peak acceleration. \n\n3. The article \"Biomechanical Analysis of the Sprint and Hurdles Events at the 2009 IAAF World Championships in Athletics\" by Graubner and Nixdorf lists the 10-m split times for the three medalists of the 100-m dash in Berlin, 2009: \n<br>\n<figure><img src=\"./../images/Berlin2009_100m_10.png\" width=600 alt=\"partial times of the 100m-race at Berlin 2009\"/></figure> \n\n a. Repeat the same calculations performed in problem 2 and compare the results. \n\n4. A body attached to a spring has its position (in cm) described by the equation $x(t) = 2\\sin(4\\pi t + \\pi/4)$. \n a. Calculate the equation for the body velocity and acceleration. \n b. Plot the position, velocity, and acceleration in the interval [0, 1] s. \n \n5. There are some nice free software that can be used for the kinematic analysis of human motion. Some of them are: [Kinovea](http://www.kinovea.org/), [Tracker](http://www.cabrillo.edu/~dbrown/tracker/), and [SkillSpector](http://video4coach.com/index.php?option=com_content&task=view&id=13&Itemid=45). Visit their websites and explore these software to understand in which biomechanical applications they could be used. \n\n6. (Sample 12.1 of Ruina and Rudra's book) The position vector of a particle is given as a functions time:<span class=\"notranslate\"> $\\overrightarrow{\\mathbf{r}}(t) = (C_1+C_2t+C_3t^2)\\hat{\\mathbf{i}}+C_4t\\,\\hat{\\mathbf{j}}$ </span>. Where $C_1=1m, C_2=3m/s,C_3=1m/s^2, C_4=2m/s$. \n a. Find the position, velocity, and acceleration of the particle at $t=2s$. \n b. Find the change in the position of the particle between $t=2s$ and $t=3s$. \n\n7. From Ruina and Rudra's book, solve the problems **12.1.1** to **12.1.14**. ",
"_____no_output_____"
],
[
"## References\n\n- Graubner R, Nixdorf E (2011) [Biomechanical Analysis of the Sprint and Hurdles Events at the 2009 IAAF World Championships in Athletics ](http://www.meathathletics.ie/devathletes/pdf/Biomechanics%20of%20Sprints.pdf). [New Studies in Athletics](http://www.iaaf.org/development/new-studies-in-athletics), 1/2, 19-53.\n- Krzysztof M, Antti Mero A (2013) [A Kinematics Analysis Of Three Best 100 M Performances Ever](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3661886/). Journal of Human Kinetics, 36, 149–160.\n- [Research Projects](http://www.iaaf.org/development/research) from the International Association of Athletics Federations. \n- Ruina A, Rudra P (2019) [Introduction to Statics and Dynamics](http://ruina.tam.cornell.edu/Book/index.html). Oxford University Press. ",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7243200576e7e5dc72888c4085aeee60f325446 | 38,696 | ipynb | Jupyter Notebook | SimTools/ORF_SimulatorDemo.ipynb | ShepherdCode/Soars2021 | ab4f304eaa09e52d260152397a6c53d7a05457da | [
"MIT"
] | 1 | 2021-08-16T14:49:04.000Z | 2021-08-16T14:49:04.000Z | SimTools/ORF_SimulatorDemo.ipynb | ShepherdCode/Soars2021 | ab4f304eaa09e52d260152397a6c53d7a05457da | [
"MIT"
] | null | null | null | SimTools/ORF_SimulatorDemo.ipynb | ShepherdCode/Soars2021 | ab4f304eaa09e52d260152397a6c53d7a05457da | [
"MIT"
] | null | null | null | 168.243478 | 6,884 | 0.903763 | [
[
[
"import sys\n#TO install mathplotlib if it isnt installed before. \n!{sys.executable} -m pip install --user matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\n",
"Requirement already satisfied: matplotlib in c:\\users\\samon\\appdata\\roaming\\python\\python38\\site-packages (3.4.2)\nRequirement already satisfied: pillow>=6.2.0 in c:\\users\\samon\\appdata\\roaming\\python\\python38\\site-packages (from matplotlib) (8.2.0)\nRequirement already satisfied: python-dateutil>=2.7 in c:\\users\\samon\\appdata\\local\\programs\\python\\python38-32\\lib\\site-packages (from matplotlib) (2.8.1)\nRequirement already satisfied: pyparsing>=2.2.1 in c:\\users\\samon\\appdata\\local\\programs\\python\\python38-32\\lib\\site-packages (from matplotlib) (2.4.7)\nRequirement already satisfied: numpy>=1.16 in c:\\users\\samon\\appdata\\local\\programs\\python\\python38-32\\lib\\site-packages (from matplotlib) (1.20.3)\nRequirement already satisfied: cycler>=0.10 in c:\\users\\samon\\appdata\\roaming\\python\\python38\\site-packages (from matplotlib) (0.10.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\samon\\appdata\\roaming\\python\\python38\\site-packages (from matplotlib) (1.3.1)\nRequirement already satisfied: six in c:\\users\\samon\\appdata\\local\\programs\\python\\python38-32\\lib\\site-packages (from cycler>=0.10->matplotlib) (1.16.0)"
],
[
"DATAPATH='data/' # must end in \"/\"\nsys.path.append(\"..\") # append parent dir in order to use sibling dirs\n\nfrom SimTools.ORF_eliminator import *\nfrom SimTools.RNA_gen import *\nfrom SimTools.RNA_describe import *",
"_____no_output_____"
],
[
"NO_OF_SEQUENCES = 5\nBASES = ['A', 'C', 'T', 'G']",
"_____no_output_____"
],
[
"describer = ORF_RE()",
"_____no_output_____"
]
],
[
[
"Firstly, lets generate a random sequence which will have equal possibility of occorance of \n['A', 'C', 'T', 'G']. We will use Professor Miller's RNA_gen.py class to generate one of them. ",
"_____no_output_____"
]
],
[
[
"generator = Collection_Generator()\nlist_of_random_sequence = generator.get_sequences(NO_OF_SEQUENCES)\nlist_of_bases = []\n\nfor list in list_of_random_sequence:\n number_bases = describer.get_number_bases(list)\n list_of_bases.append(number_bases)\n ",
"_____no_output_____"
],
[
"eliminator = ORF_eliminator()\nlist_of_bases_noORF=[]\nfor list in list_of_random_sequence:\n rna = eliminator.eliminate_ORF(list)\n number_bases_noORF = describer.get_number_bases(rna)\n list_of_bases_noORF.append(number_bases_noORF)\n ",
"_____no_output_____"
],
[
"counter =0\nwhile (counter<NO_OF_SEQUENCES):\n data1 = list_of_bases[counter]\n data2 = list_of_bases_noORF[counter]\n width = 0.3\n plt.bar(np.arange(len(data1)), data1, width=width)\n plt.bar(np.arange(len(data2))+ width, data2, width=width)\n plt.xlabel(BASES)\n \n \n plt.show()\n counter+=1",
"_____no_output_____"
]
]
] | [
"code",
"raw",
"code"
] | [
[
"code",
"code",
"code",
"code"
],
[
"raw"
],
[
"code",
"code",
"code"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.