hexsha
stringlengths
40
40
size
int64
6
14.9M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
6
260
max_stars_repo_name
stringlengths
6
119
max_stars_repo_head_hexsha
stringlengths
40
41
max_stars_repo_licenses
list
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
6
260
max_issues_repo_name
stringlengths
6
119
max_issues_repo_head_hexsha
stringlengths
40
41
max_issues_repo_licenses
list
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
6
260
max_forks_repo_name
stringlengths
6
119
max_forks_repo_head_hexsha
stringlengths
40
41
max_forks_repo_licenses
list
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2
1.04M
max_line_length
int64
2
11.2M
alphanum_fraction
float64
0
1
cells
list
cell_types
list
cell_type_groups
list
cb64bfecec894c03278e42c180f6582126870496
15,790
ipynb
Jupyter Notebook
sample-input/tutorials/8-Processing.ipynb
cjosey/PINSPEC
8c4bed18097c1461b7271c1b68af6dc6f1c78806
[ "MIT" ]
1
2020-10-14T14:32:25.000Z
2020-10-14T14:32:25.000Z
sample-input/tutorials/8-Processing.ipynb
cjosey/PINSPEC
8c4bed18097c1461b7271c1b68af6dc6f1c78806
[ "MIT" ]
null
null
null
sample-input/tutorials/8-Processing.ipynb
cjosey/PINSPEC
8c4bed18097c1461b7271c1b68af6dc6f1c78806
[ "MIT" ]
null
null
null
33.312236
394
0.585624
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb64e1db613f57cd2eb9f3b57dfa1d40a92816e2
47,084
ipynb
Jupyter Notebook
utils/TuneThoseGains.ipynb
davh565/StateSpaceControl
2d633110d54ea67bb3c3b7ccc79a621851c94c0c
[ "MIT" ]
52
2017-05-01T15:20:39.000Z
2022-03-23T01:47:27.000Z
utils/TuneThoseGains.ipynb
davh565/StateSpaceControl
2d633110d54ea67bb3c3b7ccc79a621851c94c0c
[ "MIT" ]
6
2017-05-10T15:17:03.000Z
2020-01-09T04:57:41.000Z
utils/TuneThoseGains.ipynb
davh565/StateSpaceControl
2d633110d54ea67bb3c3b7ccc79a621851c94c0c
[ "MIT" ]
19
2017-03-23T17:29:39.000Z
2022-03-23T01:47:59.000Z
99.333333
9,642
0.805412
[ [ [ "%matplotlib inline\nimport control\nfrom control.matlab import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef pole_plot(poles, title='Pole Map'):\n plt.title(title)\n plt.scatter(np.real(poles), np.imag(poles), s=50, marker='x')\n\n plt.axhline(y=0, color='black');\n plt.axvline(x=0, color='black');\n plt.xlabel('Re');\n plt.ylabel('Im');", "_____no_output_____" ] ], [ [ "# Tune Those Gains!\n\nState space control requires that you fill in up to three gain matrices (K, L & I), each potentially containing a number of elements. Given the heurism that goes into selecting PID gains (of which there are only three) tuning a state space controller can seem a bit daunting. Fortunately, the state space control framework includes a formal way to calculate gains to arrive at what is called a Linear Quadratic Regulator as well as a Linear Quadratic Estimator. \n\nThe goal of this notebook will be to walk you through the steps necessary to formulate the gains for an LQR and LQE. Once we've arrived at some acceptable gains, you can cut and paste them directly into your arduino sketch and start controlling some cool, complex dynamic systems with hopefully less guesswork and gain tweaking than if you were use a PID controller.\n\nWe'll be working from the model for the cart pole system from the examples folder. This system has multiple outputs and is inherently unstable so it's a nice way of showing the power of state space control. Having said that, **this analysis can apply to any state space model**, so to adapt it your system, just modify the system matricies ($A,B,C,D$) and the and cost function weighting matrices ($ Q_{ctrl}, R_{ctrl}, Q_{est}, R_{est} $ ) and rerun the notebook.\n\n## Cart Pole\n\nYou can find the details on the system modelling for the inverted pendulum [here](http://ctms.engin.umich.edu/CTMS/index.php?example=InvertedPendulum&section=SystemModeling) but by way of a quick introduction, the physical system consists of a pendulum mounted on top of a moving cart shown below. The cart is fitted with two sensors that measure the angle of the stick and the displacement of the cart. The cart also has an actuator to apply a horizontal force on the cart to drive it forwards and backwards. The aim of the controller is to manipulate the force on the cart in order to balance the stick upright.\n\n![output](http://ctms.engin.umich.edu/CTMS/Content/InvertedPendulum/System/Modeling/figures/pendulum.png)\n\nThe state for this system is defined as:\n\n\\begin{equation}\n\\mathbf{x} = [ cart \\;displacement, \\; cart \\;velocity, \\; stick \\;angle, \\; stick \\;angular\\; velocity ]^T\n\\end{equation}\n\nand the state space model that describes this system is as follows:", "_____no_output_____" ] ], [ [ "A = [[0.0, 1.0, 0.0, 0.0 ],\n [0.0, -0.18, 2.68, 0.0 ],\n [0.00, 0.00, 0.00, 1.00],\n [0.00, -0.45, 31.21, 0.00]]\n\nB = [[0.00],\n [1.82],\n [0.00],\n [4.55]]\n\nC = [[1, 0, 0, 0],[0,0,1,0]]\n\nD = [[0],[0]]", "_____no_output_____" ] ], [ [ "## Take a look at the Open Loop System Poles\n\nTo get an idea of how this system behaves before we add any feedback control we can look at the poles of the open loop (uncontrolled) system. Poles are the roots of a characteristic equation derived from the system model. They're often complex numbers (having a real and an imaginary component) and are useful in understanding how the output of a system will respond to changes in its input.\n\nThere's quite a bit of interesting information that can be gleaned from looking at system poles but for now we'll focus on stability; which is determined by the pole with the largest real component (the x-axis in the plot below). If a system has any poles with positive real components then that system will be inherently unstable (i.e some or all of the state will shoot off to infinity if the system is left to its own devices).\n\nThe inverted pendulum has a pole at Re(+5.56) which makes sense when you consider that if the stick is stood up on its end and let go it'd fall over (obviously it'd stop short of infinity when it hits the side of the cart, but this isn't taken into account by the model). Using a feedback controller we'll move this pole over to the left of the imaginary axis in the plot below and in so doing, stabilise the system.", "_____no_output_____" ] ], [ [ "plant = ss(A, B, C, D)\nopen_loop_poles = pole(plant)\n\nprint '\\nThe poles of the open loop system are:\\n'\nprint open_loop_poles\n\npole_plot(open_loop_poles, 'Open Loop Poles')", "\nThe poles of the open loop system are:\n\n[ 5.56778052 -5.60644672 -0.14133379 0. ]\n" ] ], [ [ "# Design a Control Law\n\nWith a model defined, we can get started on calculating the gain matrix K (the control law) which determines the control input necessary to regulate the system state to $ \\boldsymbol{0} $ (all zeros, you might want to control it to other set points but to do so just requires offsetting the control law which can be calculated on the arduino).", "_____no_output_____" ], [ "## Check for Controllability\n\nFor it to be possible to control a system defined by a given state space model, that model needs to be controllable. Being controllable simply means that the available set of control inputs are capable of driving the entire state to a desired set point. If there's a part of the system that is totally decoupled from the actuators that are manipulated by the controller then a system won't be controllable.\n\nA system is controllable if the rank of the controllability matrix is the same as the number of states in the system model.", "_____no_output_____" ] ], [ [ "controllability = ctrb(A, B)\n\nprint 'The controllability matrix is:\\n'\nprint controllability \n\nif np.linalg.matrix_rank(controllability) == np.array(B).shape[0]:\n print '\\nThe system is controllable!'\nelse:\n print '\\nThe system is not controllable, double-check your modelling and that you entered the system matrices correctly'", "The controllability matrix is:\n\n[[ 0. 1.82 -0.3276 12.252968 ]\n [ 1.82 -0.3276 12.252968 -4.40045424]\n [ 0. 4.55 -0.819 142.15292 ]\n [ 4.55 -0.819 142.15292 -31.0748256 ]]\n\nThe system is controllable!\n" ] ], [ [ "## Fill out the Quadratic Cost Function\n\nAssuming the system is controllable, we can get started on calculating the control gains. The approach we take here is to calculate a Linear Quadratic Regulator. An LQR is basically a control law (K matrix) that minimises the quadratic cost function:\n\n\\begin{equation}\nJ = \\int_0^\\infty (\\boldsymbol{x}' Q \\boldsymbol{x} + \\boldsymbol{u}' R \\boldsymbol{u})\\; dt\n\\end{equation}\n\nThe best way to think about this cost function is to realise that whenever we switch on the state space controller, it'll expend some amount of control effort to bring the state to $ \\boldsymbol{0} $ (all zeros). Ideally it'll do that as quickly and with as little overshoot as possible. We can represent that with the expression $ \\int_0^\\infty \\boldsymbol{x}' \\;\\boldsymbol{x} \\; dt $. Similarly it's probably a good idea to keep the control effort to a minimum such that the controller is energy efficient and doesn't damage the system with overly aggressive control inputs. This total control effort can be represented with $ \\int_0^\\infty \\boldsymbol{u}' \\;\\boldsymbol{u} \\; dt $.\n\nInevitably, there'll be some parts of the state and some control inputs that we care about minimising more than others. To reflect that in the cost function we specify two matrices; $ Q $ and $ R $\n\n$ Q_{ctrl} \\in \\mathbf{R}^{X \\;\\times\\; X} $ is the state weight matrix; the elements on its diagonal represent how important it is to tighly control the corresponding state element (as in Q[0,0] corresponds to x[0]).\n\n$ R_{ctrl} \\in \\mathbf{R}^{U \\;\\times\\; U} $ is the input weight matrix; the elements on its diagonal represent how important it is to minimise the use of the corresponding control input (as in R[0,0] corresponds to u[0]).", "_____no_output_____" ] ], [ [ "Q_ctrl = [[5000, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 100, 0],\n [0, 0, 0, 0]]\n\nR_ctrl = [1]", "_____no_output_____" ] ], [ [ "## Calculate the Gain Matrix for a Linear Quadratic Regulator\n\nWith a cost function defined, the cell below will calculate the gain matrix K for an LQR. Bear in mind it usually takes a bit of tweaking of the cost function to arrive at a good K matrix. Also note that it's the relative value of each weight that's important, not their absolute values. You can multiply both $ Q_{ctrl} $ and $ R_{ctrl} $ by 1e20 and you'll still wind up with the same gains.\n\nTo guide your tweaking it's helpful to see the effect that different weightings have on the closed loop system poles. Remember that the further the dominant pole (largest real component) is to the left of the Im axis, the more stable your system will be. That said, don't get carried away and set ridiculously high gains; your actual system might not behave in exactly the same way as the model and an overly aggressive controller might just end up destabilising the system under realistic conditions.", "_____no_output_____" ] ], [ [ "K, _, _ = lqr(A, B, Q_ctrl, R_ctrl)\n\nprint 'The control gain is:\\n'\nprint 'K = ', K\n\nplant_w_full_state_feedback = ss(A,\n B,\n np.identity(plant.states),\n np.zeros([plant.states, plant.inputs]))\n\ncontroller = ss(np.zeros([plant.states, plant.states]),\n np.zeros([plant.states, plant.states]), \n np.zeros([plant.inputs, plant.states]), \n K)\n\nclosed_loop_system = feedback(plant_w_full_state_feedback, controller)\nclosed_loop_poles = pole(closed_loop_system)\n\nprint '\\nThe poles of the closed loop system are:\\n'\nprint closed_loop_poles\n\npole_plot(closed_loop_poles, 'Closed Loop Poles')", "The control gain is:\n\nK = [[ -70.71067812 -37.8232881 105.51674899 20.91640966]]\n\nThe poles of the closed loop system are:\n\n[-8.49551966+7.93193591j -8.49551966-7.93193591j -4.76012015+0.83113826j\n -4.76012015-0.83113826j]\n" ] ], [ [ "# Design an Estimator\n\nIf you're lucky enough to be able to directly observe the system's entire state (in which case the $ C $ matrix will be an identity matrix) then you're done!\n\nThis obviously isn't the case for the cart pole since given our sensors we aren't able to directly observe the cart velocity or the stick angular velocity (we can differentiate the sensor readings ofcourse, but doing so is a bad idea if the sensors are even a little bit noisy). Because of this, we'll need to introduce an estimator into the feedback controller to reconstruct those parts of the state based on our sensor readings $ \\mathbf{y} $. \n\nThere's a nice duality between the estimator and the controller so the basic approach we take to calculate the estimator gain ($ L $ matrix) are very similar those for the control law above.", "_____no_output_____" ], [ "## Check for Observability\n\nObservability tells us whether the sensors we've attached to our system (as defined by the C matrix) are sufficient to derive an estimate of the state to feed into our control law. If for example, a part of the state was completely decoupled from all of the sensor measurements we take, then the system won't be observable and it'll be impossible to estimate and ultimately, to control.\n\nSimilar to controllability, a system is observable if the rank of the observability matrix is the same as the number of states in the model.", "_____no_output_____" ] ], [ [ "observability = obsv(A, C)\n\nprint 'The observability matrix is:\\n'\nprint observability \n\nif np.linalg.matrix_rank(observability) == plant.states:\n print '\\nThe system is observable!'\nelse:\n print '\\nThe system is not observable, double-check your modelling and that you entered the matrices correctly'", "The observability matrix is:\n\n[[ 1. 0. 0. 0. ]\n [ 0. 0. 1. 0. ]\n [ 0. 1. 0. 0. ]\n [ 0. 0. 0. 1. ]\n [ 0. -0.18 2.68 0. ]\n [ 0. -0.45 31.21 0. ]\n [ 0. 0.0324 -0.4824 2.68 ]\n [ 0. 0.081 -1.206 31.21 ]]\n\nThe system is observable!\n" ] ], [ [ "## Fill out the Noise Covariance Matrices\n\nTo calculate the estimator gain L, we can use the same algorithm as that used to calculate the control law. Again we define two matrices, $ Q $ and $ R $ however in this case their interpretations are slightly different.\n\n$ Q_{est} \\in \\mathbf{R}^{X \\;\\times\\; X} $ is referred to as the process noise covariance, it represents the accuracy of the state space model in being able to predict the next state based on the last state and the control input. It's assumed that the actual system is subject to some unknown noise which throws out the estimate of the state and in cases where that noise is very high, it's best to rely more heavily on the sensor readings.\n\n$ R_{est} \\in \\mathbf{R}^{Y \\;\\times\\; Y} $ is referred to as the sensor noise covariance, it represents the accuracy of the sensor readings in being able to observe the state. Here again, it's assumed that the actual sensors are subject to some unknown noise which throws out their measurements. In cases where this noise is very high, it's best to be less reliant on sensor readings.", "_____no_output_____" ] ], [ [ "Q_est = [[100, 0, 0, 0 ],\n [0, 1000, 0, 0 ],\n [0, 0, 100, 0 ],\n [0, 0, 0, 10000]]\n\nR_est = [[1,0],[0,1]]", "_____no_output_____" ] ], [ [ "## Calculate the Gain Matrix for a Linear Quadratic Estimator (aka Kalman Filter)\n\nIdeally, the estimator's covariance matrices can be calculated empirically using data collected from the system's actual sensors and its model. Doing so is a bit outside of the scope of this notebook, so instead we can just tweak the noise values to come up with an estimator that converges on the actual state with a reasonable settling time based on the closed loop poles.", "_____no_output_____" ] ], [ [ "L, _, _ = lqr(np.array(A).T, np.array(C).T, Q_est, R_est)\nL = L.T\n\nprint 'The estimator gain is:\\n'\nprint 'L = ', L\n\ncontroller_w_estimator = ss(A - np.matmul(B , K) - np.matmul(L , C), \n L,\n K,\n np.zeros([plant.inputs, plant.outputs]))\n\nclosed_loop_system_w_estimator = feedback(plant, controller_w_estimator)\nclosed_loop_estimator_poles = pole(closed_loop_system_w_estimator)\n\nprint '\\nThe poles of the closed loop system are:\\n'\nprint closed_loop_estimator_poles\n\npole_plot(closed_loop_estimator_poles, 'Closed Loop Poles with Estimation')", "The estimator gain is:\n\nL = [[ 1.26107241e+01 2.09181219e-02]\n [ 2.95153993e+01 2.33679588e+00]\n [ 2.09181219e-02 1.92861410e+01]\n [ -1.66957337e+00 1.35977837e+02]]\n\nThe poles of the closed loop system are:\n\n[-8.49551966+7.93193591j -8.49551966-7.93193591j -9.63985153+3.42895407j\n -9.63985153-3.42895407j -9.41774474+0.j -4.76012015+0.83113826j\n -4.76012015-0.83113826j -3.37941729+0.j ]\n" ] ], [ [ "# And You're Done!\n\nCongratulations! You've tuned an LQR and an LQE to suit your system model and you can now cut and paste the gains into your arduino sketch. \n\n## Coming soon, Integral Gain selection!", "_____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", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cb64e54b959a72553b8a37c8e9125782c478404c
20,464
ipynb
Jupyter Notebook
workshop/lessons/02_intro_pymatgen/kittiphong-pymatgen.ipynb
kittiphong-am/workshop
251f338b26e07fcd15a58c48040ea4cab947d2f6
[ "BSD-3-Clause" ]
null
null
null
workshop/lessons/02_intro_pymatgen/kittiphong-pymatgen.ipynb
kittiphong-am/workshop
251f338b26e07fcd15a58c48040ea4cab947d2f6
[ "BSD-3-Clause" ]
null
null
null
workshop/lessons/02_intro_pymatgen/kittiphong-pymatgen.ipynb
kittiphong-am/workshop
251f338b26e07fcd15a58c48040ea4cab947d2f6
[ "BSD-3-Clause" ]
null
null
null
24.132075
1,087
0.482799
[ [ [ "import pymatgen.core", "_____no_output_____" ], [ "print(pymatgen.core.__version__)", "2022.0.8\n" ], [ "print(pymatgen.core.__file__)", "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pymatgen/core/__init__.py\n" ], [ "import sys\nprint(sys.version)", "3.9.5 (v3.9.5:0a7dcbdb13, May 3 2021, 13:17:02) \n[Clang 6.0 (clang-600.0.57)]\n" ], [ "from pymatgen.core import Molecule", "_____no_output_____" ], [ "Molecule", "_____no_output_____" ], [ "c_monox = Molecule([\"C\",\"O\"], [[0.0, 0.0, 0.0], [0.0, 0.0, 1.2]])\nprint(c_monox)", "Full Formula (C1 O1)\nReduced Formula: CO\nCharge = 0.0, Spin Mult = 1\nSites (2)\n0 C 0.000000 0.000000 0.000000\n1 O 0.000000 0.000000 1.200000\n" ], [ "oh_minus = Molecule([\"O\", \"H\"], [[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]], charge=-1)\nprint(oh_minus)", "Full Formula (H1 O1)\nReduced Formula: H2O2\nCharge = -1, Spin Mult = 1\nSites (2)\n0 O 0.000000 0.000000 0.000000\n1 H 0.000000 0.000000 1.000000\n" ], [ "water = Molecule.from_file(\"water.xyz\")\nprint(water)", "Full Formula (H2 O1)\nReduced Formula: H2O\nCharge = 0, Spin Mult = 1\nSites (3)\n0 O -0.070000 -0.026960 -0.095240\n1 H 0.919330 -0.015310 -0.054070\n2 H -0.359290 0.231000 0.816010\n" ], [ "methane = Molecule.from_file(\"methane.xyz\")\nprint(methane)", "Full Formula (H4 C1)\nReduced Formula: H4C\nCharge = 0, Spin Mult = 1\nSites (5)\n0 C 0.000000 0.000000 -0.000000\n1 H -0.363330 -0.513830 0.889980\n2 H 1.090000 0.000000 0.000000\n3 H -0.363330 1.027660 0.000000\n4 H -0.363330 -0.513830 -0.889980\n" ], [ "furan = Molecule.from_file(\"furan.xyz\")\nprint(furan)", "Full Formula (H8 C4 O1)\nReduced Formula: H8C4O\nCharge = 0, Spin Mult = 1\nSites (13)\n0 C -0.402040 1.374890 -0.070860\n1 O 0.031180 0.046800 0.242780\n2 C 1.357290 -0.141010 -0.266300\n3 C 1.805370 1.140980 -0.991960\n4 C 0.503460 1.922920 -1.183860\n5 H -0.328440 1.995270 0.825650\n6 H -1.444090 1.349820 -0.394240\n7 H 2.038200 -0.379780 0.553240\n8 H 1.339210 -0.985330 -0.958090\n9 H 2.503850 1.706720 -0.368680\n10 H 2.282590 0.916460 -1.949400\n11 H 0.660120 3.000300 -1.084620\n12 H 0.070620 1.711640 -2.165470\n" ], [ "benzene = Molecule.from_file(\"benzene.xyz\")\nprint(benzene)", "Full Formula (H6 C6)\nReduced Formula: HC\nCharge = 0, Spin Mult = 1\nSites (12)\n0 C -0.713080 1.203780 0.000000\n1 C -0.009040 -0.015660 0.000000\n2 C 1.399040 -0.015660 0.000000\n3 C 2.103080 1.203780 0.000000\n4 C 1.399040 2.423210 -0.000000\n5 C -0.009040 2.423210 -0.000000\n6 H -1.735510 1.203780 -0.000000\n7 H -0.520250 -0.901110 -0.000000\n8 H 1.910250 -0.901110 -0.000000\n9 H 3.125510 1.203780 -0.000000\n10 H 1.910250 3.308660 0.000000\n11 H -0.520250 3.308660 0.000000\n" ], [ "print(c_monox.cart_coords)", "[[0. 0. 0. ]\n [0. 0. 1.2]]\n" ], [ "print(c_monox.center_of_mass)", "[0. 0. 0.68544132]\n" ], [ "c_monox.set_charge_and_spin(charge=1)\nprint(c_monox)", "Full Formula (C1 O1)\nReduced Formula: CO\nCharge = 1, Spin Mult = 2\nSites (2)\n0 C 0.000000 0.000000 0.000000\n1 O 0.000000 0.000000 1.200000\n" ], [ "len(c_monox)", "_____no_output_____" ], [ "print(c_monox[0])", "[0. 0. 0.] C\n" ], [ "c_monox[0] = \"O\"\nc_monox[1] = \"C\"\nprint(c_monox)", "Full Formula (C1 O1)\nReduced Formula: CO\nCharge = 1, Spin Mult = 2\nSites (2)\n0 O 0.000000 0.000000 0.000000\n1 C 0.000000 0.000000 1.200000\n" ], [ "site0 = c_monox[0]", "_____no_output_____" ], [ "site0.coords", "_____no_output_____" ], [ "site0.specie", "_____no_output_____" ], [ "from pymatgen.core import Element, Composition\nfrom pymatgen.core.periodic_table import Specie", "_____no_output_____" ], [ "carbon = Element('C')", "_____no_output_____" ], [ "carbon.average_ionic_radius", "_____no_output_____" ], [ "o_ion = Specie('O', oxidation_state=-2)\no_ion", "_____no_output_____" ], [ "o_ion.oxi_state", "_____no_output_____" ], [ "o_ion.atomic_mass", "_____no_output_____" ], [ "Specie.from_string('O2-')", "_____no_output_____" ], [ "comp = Composition({'Au': 0.5, 'Cu': 0.5})", "_____no_output_____" ], [ "print(\"formula\", comp.alphabetical_formula)\nprint(\"chemical system\", comp.chemical_system)", "formula Au0.5 Cu0.5\nchemical system Au-Cu\n" ], [ "H_rad = Element('H').atomic_radius\nC_rad = Element('C').atomic_radius\nN_rad = Element('N').atomic_radius\nHC_bond_dist = H_rad + C_rad\nCN_bond_dist = C_rad + N_rad\nH_pos = 0\nC_pos = H_pos + HC_bond_dist\nN_pos = C_pos + CN_bond_dist\nhcn = Molecule(['H','C','N'], [[H_pos, 0, 0], [C_pos, 0, 0],[N_pos, 0, 0]])\nprint(hcn)", "Full Formula (H1 C1 N1)\nReduced Formula: HCN\nCharge = 0.0, Spin Mult = 1\nSites (3)\n0 H 0.000000 0.000000 0.000000\n1 C 0.950000 0.000000 0.000000\n2 N 2.300000 0.000000 0.000000\n" ], [ "from pymatgen.core.lattice import Lattice\nfrom pymatgen.core.structure import Structure", "_____no_output_____" ], [ "my_lattice = Lattice([[5, 0, 0], [0, 5, 0], [0, 0, 5]])", "_____no_output_____" ], [ "print(my_lattice)", "5.000000 0.000000 0.000000\n0.000000 5.000000 0.000000\n0.000000 0.000000 5.000000\n" ], [ "my_lattice_2 = Lattice.from_parameters(5, 5, 5, 90, 90, 90)\nprint(my_lattice_2)", "5.000000 0.000000 0.000000\n-0.000000 5.000000 0.000000\n0.000000 0.000000 5.000000\n" ], [ "my_lattice_3 = Lattice.cubic(5)\nprint(my_lattice_3)", "5.000000 0.000000 0.000000\n0.000000 5.000000 0.000000\n0.000000 0.000000 5.000000\n" ], [ "my_lattice == my_lattice_2 == my_lattice_3", "_____no_output_____" ], [ "bcc_fe = Structure(Lattice.cubic(2.8), [\"Fe\", \"Fe\"], [[0, 0, 0], [0.5, 0.5, 0.5]])\nprint(bcc_fe)", "Full Formula (Fe2)\nReduced Formula: Fe\nabc : 2.800000 2.800000 2.800000\nangles: 90.000000 90.000000 90.000000\nSites (2)\n # SP a b c\n--- ---- --- --- ---\n 0 Fe 0 0 0\n 1 Fe 0.5 0.5 0.5\n" ], [ "bcc_fe_from_cart = Structure(Lattice.cubic(2.8), [\"Fe\", \"Fe\"], [[0, 0, 0], [1.4, 1.4, 1.4]],\n coords_are_cartesian=True)\nprint(bcc_fe_from_cart)", "Full Formula (Fe2)\nReduced Formula: Fe\nabc : 2.800000 2.800000 2.800000\nangles: 90.000000 90.000000 90.000000\nSites (2)\n # SP a b c\n--- ---- --- --- ---\n 0 Fe 0 0 0\n 1 Fe 0.5 0.5 0.5\n" ], [ "bcc_fe == bcc_fe_from_cart", "_____no_output_____" ], [ "bcc_fe.volume", "_____no_output_____" ], [ "bcc_fe = Structure.from_spacegroup(\"Im-3m\", Lattice.cubic(2.8), [\"Fe\"], [[0, 0, 0]])\nprint(bcc_fe)", "Full Formula (Fe2)\nReduced Formula: Fe\nabc : 2.800000 2.800000 2.800000\nangles: 90.000000 90.000000 90.000000\nSites (2)\n # SP a b c\n--- ---- --- --- ---\n 0 Fe 0 0 0\n 1 Fe 0.5 0.5 0.5\n" ], [ "nacl = Structure.from_spacegroup(\"Fm-3m\", Lattice.cubic(5.692), [\"Na+\", \"Cl-\"],\n [[0, 0, 0], [0.5, 0.5, 0.5]])\nprint(nacl)", "Full Formula (Na4 Cl4)\nReduced Formula: NaCl\nabc : 5.692000 5.692000 5.692000\nangles: 90.000000 90.000000 90.000000\nSites (8)\n # SP a b c\n--- ---- --- --- ---\n 0 Na+ 0 0 0\n 1 Na+ 0 0.5 0.5\n 2 Na+ 0.5 0 0.5\n 3 Na+ 0.5 0.5 0\n 4 Cl- 0.5 0.5 0.5\n 5 Cl- 0.5 0 0\n 6 Cl- 0 0.5 0\n 7 Cl- 0 0 0.5\n" ], [ "nacl.get_space_group_info()", "_____no_output_____" ], [ "polonium = Structure(Lattice.cubic(3.4), [\"Po\"], [[0.0, 0.0, 0.0]])\n\nprint(polonium)", "Full Formula (Po1)\nReduced Formula: Po\nabc : 3.400000 3.400000 3.400000\nangles: 90.000000 90.000000 90.000000\nSites (1)\n # SP a b c\n--- ---- --- --- ---\n 0 Po 0 0 0\n" ], [ "supercell = polonium * (2, 2, 2)\nprint(supercell)", "Full Formula (Po8)\nReduced Formula: Po\nabc : 6.800000 6.800000 6.800000\nangles: 90.000000 90.000000 90.000000\nSites (8)\n # SP a b c\n--- ---- --- --- ---\n 0 Po 0 0 0\n 1 Po 0 0 0.5\n 2 Po 0 0.5 0\n 3 Po 0 0.5 0.5\n 4 Po 0.5 0 0\n 5 Po 0.5 0 0.5\n 6 Po 0.5 0.5 0\n 7 Po 0.5 0.5 0.5\n" ], [ "BaTiO3=Structure.from_file(\"BaTiO3.cif\")\nprint(BaTiO3.get_space_group_info())\nBaTiO3.replace(0,'Mg')\nBaTiO3=BaTiO3*(1,1,4)\nprint(BaTiO3)\nprint(BaTiO3.get_space_group_info())", "('R3m', 160)\nFull Formula (Mg4 Ti4 O12)\nReduced Formula: MgTiO3\nabc : 4.077159 4.077159 16.308637\nangles: 89.699022 89.699022 89.699022\nSites (20)\n # SP a b c\n--- ---- -------- -------- --------\n 0 Mg 0.497155 0.497155 0.124289\n 1 Mg 0.497155 0.497155 0.374289\n 2 Mg 0.497155 0.497155 0.624289\n 3 Mg 0.497155 0.497155 0.874289\n 4 Ti 0.982209 0.982209 0.245552\n 5 Ti 0.982209 0.982209 0.495552\n 6 Ti 0.982209 0.982209 0.745552\n 7 Ti 0.982209 0.982209 0.995552\n 8 O 0.524065 0.012736 0.003184\n 9 O 0.524065 0.012736 0.253184\n 10 O 0.524065 0.012736 0.503184\n 11 O 0.524065 0.012736 0.753184\n 12 O 0.012736 0.012736 0.131016\n 13 O 0.012736 0.012736 0.381016\n 14 O 0.012736 0.012736 0.631016\n 15 O 0.012736 0.012736 0.881016\n 16 O 0.012736 0.524065 0.003184\n 17 O 0.012736 0.524065 0.253184\n 18 O 0.012736 0.524065 0.503184\n 19 O 0.012736 0.524065 0.753184\n('R3m', 160)\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb64ea955cc30f229b735f26b92c152b9296caec
153,225
ipynb
Jupyter Notebook
7week/notebook/assignment-07.ipynb
minjoong507/Machine-learning-project
f952a44fc0bb1fd2f042543534ed8bb1ea38abf3
[ "Apache-2.0" ]
null
null
null
7week/notebook/assignment-07.ipynb
minjoong507/Machine-learning-project
f952a44fc0bb1fd2f042543534ed8bb1ea38abf3
[ "Apache-2.0" ]
null
null
null
7week/notebook/assignment-07.ipynb
minjoong507/Machine-learning-project
f952a44fc0bb1fd2f042543534ed8bb1ea38abf3
[ "Apache-2.0" ]
null
null
null
303.415842
52,596
0.925247
[ [ [ "### - load data", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport math\n\ndataset = pd.read_csv('data-kmeans.csv')\ndata = dataset.values", "_____no_output_____" ] ], [ [ "### - init labels", "_____no_output_____" ] ], [ [ "label = []\nfor i in range(len(data)):\n label.append([i % 5 + 1])\n\nlabel = np.array(label)\ndata = np.concatenate((data, label), axis=1)\ninit_data = data.copy()", "_____no_output_____" ] ], [ [ "### - Compute init Centroids", "_____no_output_____" ] ], [ [ "init_Centroids = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]\n\nfor i in range(data.shape[0]):\n if data[i][2] == 1:\n init_Centroids[0][0] += data[i][0] / 40\n init_Centroids[0][1] += data[i][1] / 40\n \n elif data[i][2] == 2:\n init_Centroids[1][0] += data[i][0] / 40\n init_Centroids[1][1] += data[i][1] / 40\n\n elif data[i][2] == 3:\n init_Centroids[2][0] += data[i][0] / 40\n init_Centroids[2][1] += data[i][1] / 40\n \n elif data[i][2] == 4:\n init_Centroids[3][0] += data[i][0] / 40\n init_Centroids[3][1] += data[i][1] / 40\n \n elif data[i][2] == 5:\n init_Centroids[4][0] += data[i][0] / 40\n init_Centroids[4][1] += data[i][1] / 40", "_____no_output_____" ] ], [ [ "### - Define functions", "_____no_output_____" ] ], [ [ "def compute_distance(a, b):\n # distance between a and b\n dist = math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)\n\n return dist", "_____no_output_____" ], [ "def compute_centroid(Z):\n center = [[0, 0] for i in range(5)]\n cluster_n = [0 for i in range(5)]\n \n for i in range(data.shape[0]):\n if Z[i][2] == 1:\n center[0][0] += data[i][0]\n center[0][1] += data[i][1]\n cluster_n[0] +=1\n\n elif Z[i][2] == 2:\n center[1][0] += data[i][0]\n center[1][1] += data[i][1] \n cluster_n[1] +=1\n\n elif Z[i][2] == 3:\n center[2][0] += data[i][0]\n center[2][1] += data[i][1]\n cluster_n[2] +=1\n\n elif Z[i][2] == 4:\n center[3][0] += data[i][0] \n center[3][1] += data[i][1] \n cluster_n[3] +=1\n\n elif Z[i][2] == 5:\n center[4][0] += data[i][0] \n center[4][1] += data[i][1] \n cluster_n[4] +=1\n \n for i in range(len(center)):\n center[i][0] = center[i][0] / cluster_n[i]\n center[i][1] = center[i][1] / cluster_n[i]\n \n return center", "_____no_output_____" ], [ "def compute_label(z, M):\n \n distance_list = [compute_distance(z, M[i]) for i in range(len(M))]\n label = distance_list.index(min(distance_list)) + 1\n \n return label", "_____no_output_____" ], [ "def compute_loss(C, M):\n loss = 0\n \n for i in range(C.shape[0]):\n loss += compute_distance(C[i], M[C[i][2] - 1])\n \n return loss / C.shape[0]", "_____no_output_____" ] ], [ [ "### - main code", "_____no_output_____" ] ], [ [ "loss_curve = []\ncentroid_curv = [[] for i in range(5)]\nephochs = 100", "_____no_output_____" ], [ "for run in range(ephochs):\n Centroids = compute_centroid(data)\n\n for i in range(data.shape[0]):\n data[i][2] = compute_label(data[i], Centroids)\n loss_curve.append(compute_loss(data, Centroids))\n \n for j in range(len(centroid_curv)):\n centroid_curv[j].append(compute_distance([0, 0], Centroids[j]))", "_____no_output_____" ] ], [ [ "### - Define color and label", "_____no_output_____" ] ], [ [ "color_list = [\"green\", \"blue\", \"brown\", \"skyblue\", \"violet\"]\nname_list = [\"Cluster 1\", \"Cluster 2\", \"Cluster 3\", \"Cluster 4\", \"Cluster 5\"]", "_____no_output_____" ] ], [ [ "### - Compute clusters", "_____no_output_____" ] ], [ [ "init_Cluster1 = []\ninit_Cluster2 = []\ninit_Cluster3 = []\ninit_Cluster4 = []\ninit_Cluster5 = []\n\nfor i in range(init_data.shape[0]):\n if init_data[i][2] == 1:\n init_Cluster1.append(init_data[i])\n \n elif init_data[i][2] == 2:\n init_Cluster2.append(init_data[i])\n\n \n elif init_data[i][2] == 3:\n init_Cluster3.append(init_data[i])\n\n \n elif init_data[i][2] == 4:\n init_Cluster4.append(init_data[i])\n\n \n elif init_data[i][2] == 5:\n init_Cluster5.append(init_data[i])", "_____no_output_____" ], [ "Cluster1 = []\nCluster2 = []\nCluster3 = []\nCluster4 = []\nCluster5 = []\n\nfor i in range(init_data.shape[0]):\n if data[i][2] == 1:\n Cluster1.append(data[i])\n \n elif data[i][2] == 2:\n Cluster2.append(data[i])\n\n \n elif data[i][2] == 3:\n Cluster3.append(data[i])\n\n \n elif data[i][2] == 4:\n Cluster4.append(data[i])\n\n \n elif data[i][2] == 5:\n Cluster5.append(data[i])", "_____no_output_____" ] ], [ [ "## 1. Plot the data points [1pt]", "_____no_output_____" ] ], [ [ "fig = plt.figure(figsize=(12,10))\nplt.scatter(data[:,0], data[:,1], s =70, c = 'black', label='data')\nplt.title(\"data point\")\nplt.legend(loc = 'upper right') \nplt.show()", "_____no_output_____" ] ], [ [ "## 2. Visualise the initial condition of the point labels [1pt]", "_____no_output_____" ] ], [ [ "fig = plt.figure(figsize=(12,10))\nplt.scatter(np.array(init_Cluster1)[:,0], np.array(init_Cluster1)[:,1], s = 70, c = color_list[0], label = name_list[0])\nplt.scatter(np.array(init_Cluster2)[:,0], np.array(init_Cluster2)[:,1], s = 70, c = color_list[1], label = name_list[1])\nplt.scatter(np.array(init_Cluster3)[:,0], np.array(init_Cluster3)[:,1], s = 70, c = color_list[2], label = name_list[2])\nplt.scatter(np.array(init_Cluster4)[:,0], np.array(init_Cluster4)[:,1], s = 70, c = color_list[3], label = name_list[3])\nplt.scatter(np.array(init_Cluster5)[:,0], np.array(init_Cluster5)[:,1], s = 70, c = color_list[4], label = name_list[4])\nplt.scatter(np.array(init_Centroids)[:,0], np.array(init_Centroids)[:,1], s = 200, c = 'black', marker = '+', label = \"Centroids\")\n\n\nplt.title(\"Initial cluster\")\nplt.legend(loc = 'upper right') \nplt.show()", "_____no_output_____" ] ], [ [ "## 3. Plot the loss curve [5pt]", "_____no_output_____" ] ], [ [ "fig = plt.figure(figsize=(8,6))\nplt.plot([i for i in range(len(loss_curve))], loss_curve, c = 'b')\nplt.title('loss')\nplt.show()", "_____no_output_____" ] ], [ [ "## 4. Plot the centroid of each clsuter [5pt]", "_____no_output_____" ] ], [ [ "fig = plt.figure(figsize=(8,6))\n\nfor i in range(len(centroid_curv)):\n plt.plot([i for i in range(len(centroid_curv[i]))], centroid_curv[i], c = color_list[i], label = name_list[i])\n \nplt.title('centroid of cluster')\nplt.legend(loc = 'upper right') \nplt.show()", "_____no_output_____" ] ], [ [ "## 5. Plot the final clustering result [5pt]\n\n", "_____no_output_____" ] ], [ [ "fig = plt.figure(figsize=(12,10))\n\nplt.scatter(np.array(Cluster1)[:,0], np.array(Cluster1)[:,1], s = 70, c = color_list[0], label = name_list[0])\nplt.scatter(np.array(Cluster2)[:,0], np.array(Cluster2)[:,1], s = 70, c = color_list[1], label = name_list[1])\nplt.scatter(np.array(Cluster3)[:,0], np.array(Cluster3)[:,1], s = 70, c = color_list[2], label = name_list[2])\nplt.scatter(np.array(Cluster4)[:,0], np.array(Cluster4)[:,1], s = 70, c = color_list[3], label = name_list[3])\nplt.scatter(np.array(Cluster5)[:,0], np.array(Cluster5)[:,1], s = 70, c = color_list[4], label = name_list[4])\nplt.scatter(np.array(Centroids)[:,0], np.array(Centroids)[:,1], s = 200, c = 'black', marker = '+', label = \"Centroids\")\n\n\nplt.title(\"Initial cluster\")\nplt.legend(loc = 'upper right') \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" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb64f1cb4aab31f4a5d10edddb24d7120bc25584
26,617
ipynb
Jupyter Notebook
tutorial/tutorial.ipynb
RuishanLiu/TrialPathfinder
b54ef2250b3fa5e2fd6064e7242b02c2c0ed03bc
[ "MIT" ]
27
2021-04-07T16:53:10.000Z
2022-03-02T19:55:49.000Z
tutorial/tutorial.ipynb
RuishanLiu/TrialPathfinder
b54ef2250b3fa5e2fd6064e7242b02c2c0ed03bc
[ "MIT" ]
null
null
null
tutorial/tutorial.ipynb
RuishanLiu/TrialPathfinder
b54ef2250b3fa5e2fd6064e7242b02c2c0ed03bc
[ "MIT" ]
13
2021-04-20T22:26:10.000Z
2022-03-29T17:18:04.000Z
33.735108
369
0.485667
[ [ [ "import pandas as pd\nimport numpy as np\nimport TrialPathfinder as tp", "_____no_output_____" ] ], [ [ "# Trial PathFinder", "_____no_output_____" ], [ "## Load Data Tables\n\nTrialPathfinder reads tables in Pandas dataframe structure (pd.dataframe) as default. The date information should be read as datetime (use function pd.to_datetime to convert if not).\n\n**1. Features**:\n- <font color=darkblue>*Patient ID*</font>\n- Treatment Information\n - <font color=darkblue>*Drug name*</font>.\n - <font color=darkblue>*Start date*</font>.\n - <font color=darkblue>*Date of outcome*</font>. For example, if overall survival (OS) is used as metric, the date of outcome is the date of death. If progression-free survival (PFS) is used as metric, the date of outcome is the date of progression.\n - <font color=darkblue>*Date of last visit*</font>. The patient's last record date of visit, used for censoring.\n- <font color=darkblue>*Covariates (optional)*</font>: adjusted to emulate the blind assignment, used by Inverse probability of treatment weighting (IPTW) or propensity score matching (PSM). Some examples: age, gender, composite race/ethnicity, histology, smoking status, staging, ECOG, and biomarkers status.\n\n**2. Tables used by eligibility criteria.**\n- Use the same Patient ID as the features table.\n\nWe provide a synthetic example data in directory [tutorial/data](https://github.com/RuishanLiu/TrialPathfinder/tree/master/tutorial/data). The features (*'features.csv'*) contain the required treatment information and three covariates (gender, race, ecog). Two tables (*'demographics.csv'* and *'lab.csv'*) are used by its eligibility criteria (*'criteria.csv'*).", "_____no_output_____" ], [ "[tutorial.ipynb](https://github.com/RuishanLiu/TrialPathfinder/blob/master/tutorial/tutorial.ipynb) provides a detailed tutorial and example to use the library TrialPathFinder.\n\nWe provide a synthetic example data in directory [tutorial/data](https://github.com/RuishanLiu/TrialPathfinder/tree/master/tutorial/data). \n- Eligibility criteria (*'criteria.csv'*) have five rules: Age, Histology_Squamous, ECOG, Platelets, Bilirubin.\n- The features (*'features.csv'*) contain the required treatment information and three covariates (gender, race, ecog). \n- Two tables (*'demographics.csv'* and *'lab.csv'*) are used.", "_____no_output_____" ] ], [ [ "features = pd.read_csv('data/features.csv')\ndemographics = pd.read_csv('data/demographics.csv')\nlab = pd.read_csv('data/lab.csv')\nindicator_miss = 'Missing'\n\n# Process date information to be datetime format and explicitly define annotation for missing values\nfor table in [lab, features, demographics]:\n for col in table.columns:\n if 'Date' in col:\n table[col] = pd.to_datetime(table[col])\n table.loc[table[col].isna(), col] = indicator_miss", "_____no_output_____" ], [ "features.head()", "_____no_output_____" ], [ "demographics.head()", "_____no_output_____" ], [ "lab.head()", "_____no_output_____" ] ], [ [ "## Stadards of encoding eligibility criteria\n\nWe built a computational workflow to encode the description of eligibility criteria in the protocols into standardized instructions which can be parsed by Trial Pathfinder for cohort selection use. \n\n**1. Basic logic.**\n\n- Name of the criteria is written in the first row.\n- A new statement starts with “#inclusion” or “#exclusion” to indicate the criterion’s type. Whether to include patients who have missing entries in the criteria: “(missing include)” or “(missing exclude)”. The default choice is including patients with missing entries. \n- Data name format: “Table[‘featurename’]”. For example, “demographics[‘birthdate’]” denotes column date of birth in table demographics.\n- Equation: ==, !=, <, <=, >, >=. \n- Logic: AND, OR.\n- Other operations: MIN, MAX, ABS.\n- Time is encoded as “DAYS(80)”: 80 days; “MONTHS(4)”: 4 months; “YEARS(3)”: 3 years.\n\n---\n*Example: criteria \"Age\" - include patients more than 18 years old when they received the treatment.*\n\n> Age \\\n\\#Inclusion \\\nfeatures['StartDate'] >= demographics['BirthDate'] + @YEARS(18)\n\n---\n\n**2. Complex rule with hierachy.**\n- Each row is operated in sequential order\n - The tables are prepared before the last row. \n - The patients are selected at the last row. \n\n---\n*Example: criteria \"Platelets\" - include patients whose platelet count ≥ 100 x 10^3/μL*. \\\nTo encode this criterion, we follow the procedure: \n1. Prepare the lab table: \n 1. Pick the lab tests for platelet count\n 2. The lab test date should be within a -28 to +0 window around the treatment start date\n 3. Use the record closest to the treatment start date to do selection.\n2. Select patients: lab value larger than 100 x 10^3/μL.\n> Platelets \\\n\\#Inclusion \\\n(lab['LabName'] == 'Platelet count') \\\n(lab['TestDate'] >= features['StartDate'] - @DAYS(28) ) AND (lab['TestDate'] <= features['StartDate']) \\\nMIN(ABS(lab['TestDate'] - features['StartDate'])) \\\n(lab['LabValue'] >= 100)\n---\n\nHere we load the example criteria 'criteria.csv' under directory [tutorial/data](https://github.com/RuishanLiu/TrialPathfinder/tree/master/tutorial/data). \n", "_____no_output_____" ] ], [ [ "criteria = pd.read_csv('data/criteria.csv', header=None).values.reshape(-1)\nprint(*criteria, sep='\\n\\n')", "Age\n#Inclusion\nfeatures['StartDate'] >= demographics['BirthDate'] + @YEARS(18)\n\nHistology_Squamous\n#Inclusion\n(demographics['Histology'] == 'Squamous cell carcinoma')\n\nECOG\n#Inclusion\n(features['ECOG'] == 0) OR (features['ECOG'] == 1)\n\nPlatelets\n#Inclusion\n(lab['LabName'] == 'Platelet count')\n(lab['TestDate'] >= features['StartDate'] - @DAYS(28) ) AND (lab['TestDate'] <= features['StartDate'])\nMIN(ABS(lab['TestDate'] - features['StartDate']))\nlab['LabValue'] >= 100\n\nBilirubin\n#Inclusion\n(lab['LabName'] == 'Total bilirubin')\n(lab['TestDate'] >= features['StartDate'] - @DAYS(28) ) AND (lab['TestDate'] <= features['StartDate'])\nMIN(ABS(lab['TestDate'] - features['StartDate']))\nlab['LabValue'] <= 1\n" ] ], [ [ "## Preparation\n\nBefore simulating real trials, we first encode all the eligibility criteria --- load pseudo-code, input to the algorithm and figure out which patient is excluded by each rule.", "_____no_output_____" ], [ "1. Create an empty cohort object \n - tp.cohort_selection() requires all the patients ids used in the study. Here we analyze all the patients in the dataset, people can also use a subset of patients based on their needs.", "_____no_output_____" ] ], [ [ "patientids = features['PatientID']\ncohort = tp.cohort_selection(patientids, name_PatientID='PatientID')", "_____no_output_____" ] ], [ [ "2. Add the tables needed in the eligibility criterion.", "_____no_output_____" ] ], [ [ "cohort.add_table('demographics', demographics)\ncohort.add_table('lab', lab)\ncohort.add_table('features', features)", "_____no_output_____" ] ], [ [ "3. Add individual eligibility criterion", "_____no_output_____" ] ], [ [ "# Option 1: add rules individually\nfor rule in criteria[:]:\n name_rule, select, missing = cohort.add_rule(rule)\n print('Rule %s: exclude patients %d/%d' % (name_rule, select.shape[0]-np.sum(select), select.shape[0]))\n \n# # Option 2: add the list of criteria\n# cohort.add_rules(criteria)", "Rule Age: exclude patients 0/4000\nRule Histology_Squamous: exclude patients 2020/4000\nRule ECOG: exclude patients 1797/4000\nRule Platelets: exclude patients 1943/4000\nRule Bilirubin: exclude patients 2316/4000\n" ] ], [ [ "# Analysis\n\n- Treatment drug: B\n- Control drug: A\n- Criteria used: Age, ECOG, Histology_Squamous, Platelets, Bilirubin", "_____no_output_____" ] ], [ [ "drug_treatment = ['drug B']\ndrug_control = ['drug A']\nname_rules = ['Age', 'Histology_Squamous', 'ECOG', 'Platelets', 'Bilirubin']\ncovariates_cat = ['Gender', 'Race', 'ECOG'] # categorical covariates\ncovariates_cont = [] # continuous covariates", "_____no_output_____" ] ], [ [ "1. Original trial crieria\n - Criteria includes Age, ECOG, Histology_Squamous, Platelets, Bilirubin.", "_____no_output_____" ] ], [ [ "HR, CI, data_cox = tp.emulate_trials(cohort, features, drug_treatment, drug_control, name_rules, \n covariates_cat=covariates_cat, covariates_cont=covariates_cont, \n name_DrugName='DrugName', name_StartDate='StartDate', \n name_OutcomeDate='OutcomeDate', name_LastVisitDate='LastVisitDate',\n indicator_miss=indicator_miss)\nprint('Hazard Ratio: %.2f (%.2f-%.2f)' % (HR, CI[0], CI[1]))\nprint('Number of Patients: %d' % (data_cox.shape[0]))", "Hazard Ratio: 0.63 (0.41-0.96)\nNumber of Patients: 223\n" ] ], [ [ "2. Fully-relaxed criteria\n - No rule applied (name_rules=[]).", "_____no_output_____" ] ], [ [ "HR, CI, data_cox = tp.emulate_trials(cohort, features, drug_treatment, drug_control, [], \n covariates_cat=covariates_cat, covariates_cont=covariates_cont, \n name_DrugName='DrugName', name_StartDate='StartDate', \n name_OutcomeDate='OutcomeDate', name_LastVisitDate='LastVisitDate',\n indicator_miss=indicator_miss)\nprint('Hazard Ratio: %.2f (%.2f-%.2f)' % (HR, CI[0], CI[1]))\nprint('Number of Patients: %d' % (data_cox.shape[0]))", "Hazard Ratio: 0.77 (0.71-0.84)\nNumber of Patients: 4000\n" ] ], [ [ "3. Compute shapley values", "_____no_output_____" ] ], [ [ "shapley_values = tp.shapley_computation(cohort, features, drug_treatment, drug_control, name_rules,\n tolerance=0.01, iter_max=1000,\n covariates_cat=covariates_cat, covariates_cont=covariates_cont, \n name_DrugName='DrugName', name_StartDate='StartDate', \n name_OutcomeDate='OutcomeDate', name_LastVisitDate='LastVisitDate',\n indicator_miss=indicator_miss, \n random_seed=1001, verbose=1)", "Shapley Computation Iteration 0 | SEM = 0.0000\nShapley Computation Iteration 1 | SEM = 0.0223\nShapley Computation Iteration 2 | SEM = 0.0172\nShapley Computation Iteration 3 | SEM = 0.0146\nShapley Computation Iteration 4 | SEM = 0.0131\nShapley Computation Iteration 5 | SEM = 0.0117\nShapley Computation Iteration 6 | SEM = 0.0109\nShapley Computation Iteration 7 | SEM = 0.0099\nStopping criteria satisfied!\n" ], [ "pd.DataFrame([shapley_values], columns=name_rules, index=['Shapley Value'])", "_____no_output_____" ] ], [ [ "4. Data-driven criteria", "_____no_output_____" ] ], [ [ "name_rules_relax = np.array(name_rules)[shapley_values < 0]\nHR, CI, data_cox = tp.emulate_trials(cohort, features, drug_treatment, drug_control, name_rules_relax, \n covariates_cat=covariates_cat, covariates_cont=covariates_cont, \n name_DrugName='DrugName', name_StartDate='StartDate', \n name_OutcomeDate='OutcomeDate', name_LastVisitDate='LastVisitDate',\n indicator_miss=indicator_miss)\nprint('Hazard Ratio: %.2f (%.2f-%.2f)' % (HR, CI[0], CI[1]))\nprint('Number of Patients: %d' % (data_cox.shape[0]))", "Hazard Ratio: 0.67 (0.57-0.80)\nNumber of Patients: 1053\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
cb64f818c48f134d5aa603e64c1ae445b5f6a54f
52,288
ipynb
Jupyter Notebook
notebooks/Hackweek_Presentation.ipynb
georgettica/IS2_velocity
6bdb580a1a2def7faab5ec19821a00e3896d15c2
[ "BSD-3-Clause" ]
2
2020-07-28T09:28:33.000Z
2020-08-10T03:04:36.000Z
notebooks/Hackweek_Presentation.ipynb
saptarsi96/IS2_velocity
0e3a71ea8314bcd9104c88e96469476d8d2773af
[ "BSD-3-Clause" ]
13
2020-10-09T17:03:47.000Z
2021-08-18T20:40:56.000Z
notebooks/Hackweek_Presentation.ipynb
saptarsi96/IS2_velocity
0e3a71ea8314bcd9104c88e96469476d8d2773af
[ "BSD-3-Clause" ]
4
2020-06-15T21:08:40.000Z
2020-07-28T09:28:34.000Z
33.755972
957
0.532895
[ [ [ "# Team Surface Velocity", "_____no_output_____" ], [ "### **Members**: Grace Barcheck, Canyon Breyer, Rodrigo Gómez-Fell, Trevor Hillebrand, Ben Hills, Lynn Kaluzienski, Joseph Martin, David Polashenski", "_____no_output_____" ], [ "### **Science Advisor**: Daniel Shapero", "_____no_output_____" ], [ "### **Special Thanks**: Ben Smith, David Shean ", "_____no_output_____" ], [ "### Motivation\n\n**Speaker: Canyon Breyer**\n\nPrevious work by Marsh and Rack (2012), and Lee and others (2012), have demonstrated the value of using satellite altimetry as a method of calculating ice surface velocity utilizing the Geoscience Laser Altimeter System (GLAS) on board ICESat. This altimetry method has several advantages over more traditional techniques due to high pointing accuracy for geo-location and an ability to measure velocity in regions that lack visible surface features (Marsh and Rack, 2012). The method also has the added benefit of dealing with tidal fluctuations without the need for a tidal correction model. The motivation for this project was to expand the methodology outlined in Marsh and Rack (2012) to the ICE-Sat2 dataset. The smaller footprint of the ICE-Sat2 mission will likely improve the overall accuracy of velocity measurements and the nature of its precise repeat passes would provide an avenue for studying temporal variations of glacier velocities.", "_____no_output_____" ], [ "### Project Objective:\n\n**Speaker: Rodrigo Gómez-Fell**\n\nExtract surface ice velocity on polar regions from ICESat-2 along track measurements", "_____no_output_____" ], [ "##### Goals:\n\n- Compare the capabilities of ICESat-2 to extract surface ice velocity from ice shelves and ice streams\n- Compare ICESat GLAS methodology (along track) to ICESat-2 across track\n- Use crossovers for calculating velocities and determine how the measurements compare with simple along track and across track.\n -Does this resolve different directions of ice flow?\n- Can a surface velocity product be extracted from ATL06, or is ATL03 the more suitable product.", "_____no_output_____" ], [ "### Study Area:\n\nWhen looking for a study region to test our ICESat-2 velocity derivation method, we prioritized regions that **1)** included both grounded and floating ice and **2)** had a good alignment between satellite track position and overall flow direction. We found Foundation Ice Stream, a large ice stream draining into the Filchner-Ronne Ice Shelf, to meet both of these criteria. ", "_____no_output_____" ], [ "![FIS](FISimage.PNG)", "_____no_output_____" ], [ "### Data Selection\n\nWe used the ICESat-2 Land Ice Height ATL06 product and then used the MEaSUREs Antarctic Velocity Map V2 (Rignot, 2017) for validation of our derived velocities", "_____no_output_____" ], [ "### Method\n\n**Speaker: Ben Hills**\n\nFollowing Marsh and Rack (2012) we used the slope of elevation for analysis, this helped amplify differences in the ice profile between repeat measurements and also removed the influence of tidal effects. This is portrayed in the figure below.\n", "_____no_output_____" ], [ "![Beardmore](beardmore.PNG)", "_____no_output_____" ], [ "![Marsh_method](marsh2.PNG)", "_____no_output_____" ], [ "Fig.2: From Marsh and Rack 2012. Schematic of the method used to reduce the effect of oblique surface features and ice flow which is non-parallel to ICESat tracks. Black lines indicate satellite tracks, grey ticks indicate the orientation of surface features, and ⍺ is the feature-track angle. Bottom right profile illustrates that after adjustment there is no relative feature displacement due to cross-track separation, therefore all displacement is due to ice movement in the track direction.\n", "_____no_output_____" ], [ "### Our Methods:\n", "_____no_output_____" ], [ "**Cross-correlation background**\n\n**Speaker: Grace Barcheck**\n", "_____no_output_____" ], [ "##### Test.scipy.signal.correlate on some ATL06 data from Foundation Ice Stream (FIS)", "_____no_output_____" ] ], [ [ "import numpy as np\nimport scipy, sys, os, pyproj, glob, re, h5py\nimport matplotlib.pyplot as plt\n\nfrom scipy.signal import correlate\nfrom astropy.time import Time\n\n%matplotlib widget\n%load_ext autoreload\n%autoreload 2", "_____no_output_____" ] ], [ [ "##### Test scipy.signal.correlate\n\nGenerate test data", "_____no_output_____" ] ], [ [ "dx = 0.1\nx = np.arange(0,10,dx)\ny = np.zeros(np.shape(x))\nix0 = 30\nix1 = 30 + 15\ny[ix0:ix1] = 1\n\nfig,axs = plt.subplots(1,2)\naxs[0].plot(x,y,'k')\naxs[0].set_xlabel('distance (m)')\naxs[0].set_ylabel('value')\naxs[1].plot(np.arange(len(x)), y,'k')\naxs[1].set_xlabel('index')", "_____no_output_____" ] ], [ [ "Next, we generate a signal to correlate the test data with", "_____no_output_____" ] ], [ [ "imposed_offset = int(14/dx) # 14 meters, in units of samples\n\nx_noise = np.arange(0,50,dx) # make the vector we're comparing with much longer\ny_noise = np.zeros(np.shape(x_noise))\ny_noise[ix0 + imposed_offset : ix1 + imposed_offset] = 1\n\n# uncomment the line below to add noise\n# y_noise = y_noise * np.random.random(np.shape(y_noise))\n\nfig,axs = plt.subplots(1,2)\n\naxs[0].plot(x,y,'k')\naxs[0].set_xlabel('distance (m)')\naxs[0].set_ylabel('value')\naxs[1].plot(np.arange(len(x)), y, 'k')\naxs[1].set_xlabel('index')\n\naxs[0].plot(x_noise,y_noise, 'b')\naxs[0].set_xlabel('distance (m)')\naxs[0].set_ylabel('value')\naxs[1].plot(np.arange(len(x_noise)), y_noise,'b')\naxs[1].set_xlabel('index')\n\nfig.suptitle('black = original, blue = shifted')", "_____no_output_____" ] ], [ [ "##### Try scipy.signal.correlate:\n\nmode ='full' returns the entire cross correlation; could be 'valid' to return only non- zero-padded part\n\nmethod = direct (not fft)", "_____no_output_____" ] ], [ [ "corr = correlate(y_noise,y, mode = 'full', method = 'direct') \nnorm_val = np.sqrt(np.sum(y_noise**2)*np.sum(y**2))\ncorr = corr / norm_val", "_____no_output_____" ] ], [ [ "Let's look at the dimensions of corr", "_____no_output_____" ] ], [ [ "print('corr: ', np.shape(corr))\nprint('x: ', np.shape(x))\nprint('x: ', np.shape(x_noise))", "corr: (599,)\nx: (100,)\nx: (500,)\n" ] ], [ [ "##### Look at the correlation visualized in the plots below", "_____no_output_____" ] ], [ [ "# lagvec = np.arange(0,len(x_noise) - len(x) + 1)\nlagvec = np.arange( -(len(x) - 1), len(x_noise), 1)\nshift_vec = lagvec * dx\n\nix_peak = np.arange(len(corr))[corr == np.nanmax(corr)][0]\nbest_lag = lagvec[ix_peak]\nbest_shift = shift_vec[ix_peak]\n\nfig,axs = plt.subplots(3,1)\n\naxs[0].plot(lagvec,corr)\naxs[0].plot(lagvec[ix_peak],corr[ix_peak], 'r*')\naxs[0].set_xlabel('lag (samples)')\naxs[0].set_ylabel('correlation coefficient')\n\naxs[1].plot(shift_vec,corr)\naxs[1].plot(shift_vec[ix_peak],corr[ix_peak], 'r*')\naxs[1].set_xlabel('shift (m)')\naxs[1].set_ylabel('correlation coefficient')\n\naxs[2].plot(x + best_shift, y,'k')\naxs[2].plot(x_noise, y_noise, 'b--')\naxs[2].set_xlabel('shift (m)')\n\n\nfig.suptitle(' '.join(['Shift ', str(best_lag), ' samples, or ', str(best_shift), ' m to line up signals']))\n", "_____no_output_____" ] ], [ [ "### A little Background on cross-correlation...", "_____no_output_____" ], [ "![Correlation](Corr_Coeff.gif)", "_____no_output_____" ], [ "### Applying our method to ATL06 data\n\n**Speaker: Ben Hills**\n\nLoad repeat data:\nImport readers, etc.", "_____no_output_____" ] ], [ [ "# ! cd ..; [ -d pointCollection ] || git clone https://www.github.com/smithB/pointCollection.git\n# sys.path.append(os.path.join(os.getcwd(), '..'))\n\n#!python3 -m pip install --user git+https://github.com/tsutterley/pointCollection.git@pip\nimport pointCollection as pc", "_____no_output_____" ], [ "moa_datapath = '/srv/tutorial-data/land_ice_applications/'\ndatapath = '/home/jovyan/shared/surface_velocity/FIS_ATL06/'\n", "_____no_output_____" ] ], [ [ "#### **Geographic setting: Foundation Ice Stream**", "_____no_output_____" ] ], [ [ "print(pc.__file__)", "/home/jovyan/.local/lib/python3.7/site-packages/pointCollection/__init__.py\n" ], [ "spatial_extent = np.array([-65, -86, -55, -81])\nlat=spatial_extent[[1, 3, 3, 1, 1]]\nlon=spatial_extent[[2, 2, 0, 0, 2]]\nprint(lat)\nprint(lon)\n# project the coordinates to Antarctic polar stereographic\nxy=np.array(pyproj.Proj(3031)(lon, lat))\n# get the bounds of the projected coordinates \nXR=[np.nanmin(xy[0,:]), np.nanmax(xy[0,:])]\nYR=[np.nanmin(xy[1,:]), np.nanmax(xy[1,:])]\nMOA=pc.grid.data().from_geotif(os.path.join(moa_datapath, 'MOA','moa_2009_1km.tif'), bounds=[XR, YR])\n\n# show the mosaic:\nplt.figure()\nMOA.show(cmap='gray', clim=[14000, 17000])\nplt.plot(xy[0,:], xy[1,:])\nplt.title('Mosaic of Antarctica for Foundation Ice Stream')", "[-86 -81 -81 -86 -86]\n[-55 -55 -65 -65 -55]\n" ] ], [ [ "##### Load the repeat track data\n\nATL06 reader", "_____no_output_____" ] ], [ [ "def atl06_to_dict(filename, beam, field_dict=None, index=None, epsg=None):\n \"\"\"\n Read selected datasets from an ATL06 file\n\n Input arguments:\n filename: ATl06 file to read\n beam: a string specifying which beam is to be read (ex: gt1l, gt1r, gt2l, etc)\n field_dict: A dictinary describing the fields to be read\n keys give the group names to be read, \n entries are lists of datasets within the groups\n index: which entries in each field to read\n epsg: an EPSG code specifying a projection (see www.epsg.org). Good choices are:\n for Greenland, 3413 (polar stereographic projection, with Greenland along the Y axis)\n for Antarctica, 3031 (polar stereographic projection, centered on the Pouth Pole)\n Output argument:\n D6: dictionary containing ATL06 data. Each dataset in \n dataset_dict has its own entry in D6. Each dataset \n in D6 contains a numpy array containing the \n data\n \"\"\"\n if field_dict is None:\n field_dict={None:['latitude','longitude','h_li', 'atl06_quality_summary'],\\\n 'ground_track':['x_atc','y_atc'],\\\n 'fit_statistics':['dh_fit_dx', 'dh_fit_dy']}\n D={}\n # below: file_re = regular expression, it will pull apart the regular expression to get the information from the filename\n file_re=re.compile('ATL06_(?P<date>\\d+)_(?P<rgt>\\d\\d\\d\\d)(?P<cycle>\\d\\d)(?P<region>\\d\\d)_(?P<release>\\d\\d\\d)_(?P<version>\\d\\d).h5')\n with h5py.File(filename,'r') as h5f:\n for key in field_dict:\n for ds in field_dict[key]:\n if key is not None:\n ds_name=beam+'/land_ice_segments/'+key+'/'+ds\n else:\n ds_name=beam+'/land_ice_segments/'+ds\n if index is not None:\n D[ds]=np.array(h5f[ds_name][index])\n else:\n D[ds]=np.array(h5f[ds_name])\n if '_FillValue' in h5f[ds_name].attrs:\n bad_vals=D[ds]==h5f[ds_name].attrs['_FillValue']\n D[ds]=D[ds].astype(float)\n D[ds][bad_vals]=np.NaN\n D['data_start_utc'] = h5f['/ancillary_data/data_start_utc'][:]\n D['delta_time'] = h5f['/' + beam + '/land_ice_segments/delta_time'][:]\n D['segment_id'] = h5f['/' + beam + '/land_ice_segments/segment_id'][:]\n if epsg is not None:\n xy=np.array(pyproj.proj.Proj(epsg)(D['longitude'], D['latitude']))\n D['x']=xy[0,:].reshape(D['latitude'].shape)\n D['y']=xy[1,:].reshape(D['latitude'].shape)\n temp=file_re.search(filename)\n D['rgt']=int(temp['rgt'])\n D['cycle']=int(temp['cycle'])\n D['beam']=beam\n return D", "_____no_output_____" ] ], [ [ "##### Next we will read in the files", "_____no_output_____" ] ], [ [ "# find all the files in the directory:\n# ATL06_files=glob.glob(os.path.join(datapath, 'PIG_ATL06', '*.h5'))\nrgt = '0848'\nATL06_files=glob.glob(os.path.join(datapath, '*' + rgt + '*.h5'))\n\nD_dict={}\nerror_count=0\nfor file in ATL06_files[:10]:\n try:\n D_dict[file]=atl06_to_dict(file, '/gt2l', index=slice(0, -1, 25), epsg=3031)\n except KeyError as e:\n print(f'file {file} encountered error {e}')\n error_count += 1\nprint(f\"read {len(D_dict)} data files of which {error_count} gave errors\")", "read 4 data files of which 0 gave errors\n" ], [ "# find all the files in the directory:\n# ATL06_files=glob.glob(os.path.join(datapath, 'PIG_ATL06', '*.h5'))\nrgt = '0537'\nATL06_files=glob.glob(os.path.join(datapath, '*' + rgt + '*.h5'))\n\n#D_dict={}\nerror_count=0\nfor file in ATL06_files[:10]:\n try:\n D_dict[file]=atl06_to_dict(file, '/gt2l', index=slice(0, -1, 25), epsg=3031)\n except KeyError as e:\n print(f'file {file} encountered error {e}')\n error_count += 1\nprint(f\"read {len(D_dict)} data files of which {error_count} gave errors\")", "read 9 data files of which 0 gave errors\n" ] ], [ [ "##### Then, we will plot the ground tracks", "_____no_output_____" ] ], [ [ "plt.figure(figsize=[8,8])\nhax0=plt.gcf().add_subplot(211, aspect='equal')\nMOA.show(ax=hax0, cmap='gray', clim=[14000, 17000]);\nhax1=plt.gcf().add_subplot(212, aspect='equal', sharex=hax0, sharey=hax0)\nMOA.show(ax=hax1, cmap='gray', clim=[14000, 17000]);\nfor fname, Di in D_dict.items():\n cycle=Di['cycle']\n if cycle <= 2:\n ax=hax0\n else:\n ax=hax1\n #print(fname)\n #print(f'\\t{rgt}, {cycle}, {region}')\n ax.plot(Di['x'], Di['y'])\n if True:\n try:\n if cycle < 3:\n ax.text(Di['x'][0], Di['y'][0], f\"rgt={Di['rgt']}, cyc={cycle}\", clip_on=True)\n elif cycle==3:\n ax.text(Di['x'][0], Di['y'][0], f\"rgt={Di['rgt']}, cyc={cycle}+\", clip_on=True)\n except IndexError:\n pass\nhax0.set_title('cycles 1 and 2');\nhax1.set_title('cycle 3+');", "_____no_output_____" ], [ "# find all the files in the directory:\n# ATL06_files=glob.glob(os.path.join(datapath, 'PIG_ATL06', '*.h5'))\nrgt = '0848'\nATL06_files=glob.glob(os.path.join(datapath, '*' + rgt + '*.h5'))\n\nD_dict={}\nerror_count=0\nfor file in ATL06_files[:10]:\n try:\n D_dict[file]=atl06_to_dict(file, '/gt2l', index=slice(0, -1, 25), epsg=3031)\n except KeyError as e:\n print(f'file {file} encountered error {e}')\n error_count += 1\nprint(f\"read {len(D_dict)} data files of which {error_count} gave errors\")", "read 4 data files of which 0 gave errors\n" ] ], [ [ "##### Repeat track elevation profile", "_____no_output_____" ] ], [ [ "# A revised code to plot the elevations of segment midpoints (h_li):\ndef plot_elevation(D6, ind=None, **kwargs):\n \"\"\"\n Plot midpoint elevation for each ATL06 segment\n \"\"\"\n if ind is None:\n ind=np.ones_like(D6['h_li'], dtype=bool)\n # pull out heights of segment midpoints\n h_li = D6['h_li'][ind]\n # pull out along track x coordinates of segment midpoints\n x_atc = D6['x_atc'][ind]\n\n plt.plot(x_atc, h_li, **kwargs)", "_____no_output_____" ] ], [ [ "**Data Visualization**", "_____no_output_____" ] ], [ [ "D_2l={}\nD_2r={}\n\n# specify the rgt here:\nrgt=\"0027\"\nrgt=\"0848\" #Ben's suggestion\n\n# iterate over the repeat cycles\nfor cycle in ['03','04','05','06','07']:\n for filename in glob.glob(os.path.join(datapath, f'*ATL06_*_{rgt}{cycle}*_003*.h5')):\n try:\n # read the left-beam data\n D_2l[filename]=atl06_to_dict(filename,'/gt2l', index=None, epsg=3031)\n # read the right-beam data\n D_2r[filename]=atl06_to_dict(filename,'/gt2r', index=None, epsg=3031)\n # plot the locations in the previous plot\n map_ax.plot(D_2r[filename]['x'], D_2r[filename]['y'],'k'); \n map_ax.plot(D_2l[filename]['x'], D_2l[filename]['y'],'k');\n except Exception as e:\n print(f'filename={filename}, exception={e}')\n\nplt.figure();\nfor filename, Di in D_2l.items():\n #Plot only points that have ATL06_quality_summary==0 (good points)\n hl=plot_elevation(Di, ind=Di['atl06_quality_summary']==0, label=f\"cycle={Di['cycle']}\")\n #hl=plt.plot(Di['x_atc'][Di['atl06_quality_summary']==0], Di['h_li'][Di['atl06_quality_summary']==0], '.', label=f\"cycle={Di['cycle']}\")\n \nplt.legend()\nplt.xlabel('x_atc')\nplt.ylabel('elevation');", "filename=/home/jovyan/shared/surface_velocity/FIS_ATL06/processed_ATL06_20190523195046_08480311_003_01.h5, exception=name 'map_ax' is not defined\nfilename=/home/jovyan/shared/surface_velocity/FIS_ATL06/processed_ATL06_20190822153035_08480411_003_01.h5, exception=name 'map_ax' is not defined\n" ] ], [ [ "##### Now, we need to pull out a segment and cross correlate:\n\nLet's try 2.93e7 through x_atc=2.935e7", "_____no_output_____" ] ], [ [ "cycles = [] # names of cycles with data\nfor filename, Di in D_2l.items():\n cycles += [str(Di['cycle']).zfill(2)]\ncycles.sort()\n \n# x1 = 2.93e7\n# x2 = 2.935e7\n\nbeams = ['gt1l','gt1r','gt2l','gt2r','gt3l','gt3r']\n\n# try and smooth without filling nans\nsmoothing_window_size = int(np.round(60 / dx)) # meters / dx; odd multiples of 20 only! it will break\nfilt = np.ones(smoothing_window_size)\nsmoothed = True\n\n### extract and plot data from all available cycles\nfig, axs = plt.subplots(4,1)\nx_atc = {}\nh_li_raw = {}\nh_li = {}\nh_li_diff = {}\ntimes = {}\nfor cycle in cycles:\n # find Di that matches cycle:\n Di = {}\n x_atc[cycle] = {}\n h_li_raw[cycle] = {}\n h_li[cycle] = {}\n h_li_diff[cycle] = {}\n times[cycle] = {}\n\n filenames = glob.glob(os.path.join(datapath, f'*ATL06_*_{rgt}{cycle}*_003*.h5'))\n for filename in filenames:\n try:\n for beam in beams:\n Di[filename]=atl06_to_dict(filename,'/'+ beam, index=None, epsg=3031)\n\n times[cycle][beam] = Di[filename]['data_start_utc']\n \n # extract h_li and x_atc for that section\n x_atc_tmp = Di[filename]['x_atc']\n h_li_tmp = Di[filename]['h_li']#[ixs]\n \n # segment ids:\n seg_ids = Di[filename]['segment_id']\n# print(len(seg_ids), len(x_atc_tmp))\n \n # make a monotonically increasing x vector\n # assumes dx = 20 exactly, so be carefull referencing back\n ind = seg_ids - np.nanmin(seg_ids) # indices starting at zero, using the segment_id field, so any skipped segment will be kept in correct location\n x_full = np.arange(np.max(ind)+1) * 20 + x_atc_tmp[0]\n h_full = np.zeros(np.max(ind)+1) + np.NaN\n h_full[ind] = h_li_tmp\n \n \n x_atc[cycle][beam] = x_full\n h_li_raw[cycle][beam] = h_full\n \n # running average smoother /filter\n if smoothed == True:\n h_smoothed = (1/smoothing_window_size) * np.convolve(filt, h_full, mode=\"same\")\n #h_smoothed = h_smoothed[int(np.floor(smoothing_window_size/2)):int(-np.floor(smoothing_window_size/2))] # cut off ends\n h_li[cycle][beam] = h_smoothed\n\n # # differentiate that section of data\n h_diff = (h_smoothed[1:] - h_smoothed[0:-1]) / (x_full[1:] - x_full[0:-1])\n else: \n h_li[cycle][beam] = h_full\n h_diff = (h_full[1:] - h_full[0:-1]) / (x_full[1:] - x_full[0:-1])\n \n h_li_diff[cycle][beam] = h_diff\n\n # plot\n axs[0].plot(x_full, h_full)\n axs[1].plot(x_full[1:], h_diff)\n# axs[2].plot(x_atc_tmp[1:] - x_atc_tmp[:-1])\n axs[2].plot(np.isnan(h_full))\n axs[3].plot(seg_ids[1:]- seg_ids[:-1])\n\n\n\n except:\n print(f'filename={filename}, exception={e}')\n\n\n ", "_____no_output_____" ] ], [ [ "**Speaker: Grace Barcheck**", "_____no_output_____" ] ], [ [ "n_veloc = len(cycles) - 1\n\nsegment_length = 3000 # m\nx1 = 2.935e7# 2.925e7#x_atc[cycles[0]][beams[0]][1000] <-- the very first x value in a file; doesn't work, I think b/c nans # 2.93e7\n#x1=2.917e7\nsearch_width = 800 # m\ndx = 20 # meters between x_atc points\n\nfor veloc_number in range(n_veloc):\n cycle1 = cycles[veloc_number]\n cycle2 = cycles[veloc_number+1]\n t1_string = times[cycle1]['gt1l'][0].astype(str) #figure out later if just picking hte first one it ok\n t1 = Time(t1_string)\n \n t2_string = times[cycle2]['gt1l'][0].astype(str) #figure out later if just picking hte first one it ok\n t2 = Time(t2_string)\n \n dt = (t2 - t1).jd # difference in julian days\n \n velocities = {} \n for beam in beams:\n fig1, axs = plt.subplots(4,1)\n \n # cut out small chunk of data at time t1 (first cycle)\n x_full_t1 = x_atc[cycle1][beam]\n ix_x1 = np.arange(len(x_full_t1))[x_full_t1 >= x1][0]\n ix_x2 = ix_x1 + int(np.round(segment_length/dx)) \n x_t1 = x_full_t1[ix_x1:ix_x2]\n h_li1 = h_li_diff[cycle1][beam][ix_x1-1:ix_x2-1] # start 1 index earlier because the data are differentiated\n \n # cut out a wider chunk of data at time t2 (second cycle)\n x_full_t2 = x_atc[cycle2][beam]\n ix_x3 = ix_x1 - int(np.round(search_width/dx)) # offset on earlier end by # indices in search_width\n ix_x4 = ix_x2 + int(np.round(search_width/dx)) # offset on later end by # indices in search_width\n x_t2 = x_full_t2[ix_x3:ix_x4]\n h_li2 = h_li_diff[cycle2][beam][ix_x3:ix_x4]\n\n # plot data\n axs[0].plot(x_t2, h_li2, 'r')\n axs[0].plot(x_t1, h_li1, 'k')\n axs[0].set_xlabel('x_atc (m)')\n \n # correlate old with newer data\n corr = correlate(h_li1, h_li2, mode = 'valid', method = 'direct') \n norm_val = np.sqrt(np.sum(h_li1**2)*np.sum(h_li2**2)) # normalize so values range between 0 and 1\n corr = corr / norm_val\n \n \n# lagvec = np.arange( -(len(h_li1) - 1), len(h_li2), 1)# for mode = 'full'\n# lagvec = np.arange( -int(search_width/dx) - 1, int(search_width/dx) +1, 1) # for mode = 'valid'\n lagvec = np.arange(- int(np.round(search_width/dx)), int(search_width/dx) +1,1)# for mode = 'valid'\n\n shift_vec = lagvec * dx\n\n ix_peak = np.arange(len(corr))[corr == np.nanmax(corr)][0]\n best_lag = lagvec[ix_peak]\n best_shift = shift_vec[ix_peak]\n velocities[beam] = best_shift/(dt/365)\n\n axs[1].plot(lagvec,corr)\n axs[1].plot(lagvec[ix_peak],corr[ix_peak], 'r*')\n axs[1].set_xlabel('lag (samples)')\n\n axs[2].plot(shift_vec,corr)\n axs[2].plot(shift_vec[ix_peak],corr[ix_peak], 'r*')\n axs[2].set_xlabel('shift (m)')\n\n # plot shifted data\n axs[3].plot(x_t2, h_li2, 'r')\n axs[3].plot(x_t1 - best_shift, h_li1, 'k')\n axs[3].set_xlabel('x_atc (m)')\n \n axs[0].text(x_t2[100], 0.6*np.nanmax(h_li2), beam)\n axs[1].text(lagvec[5], 0.6*np.nanmax(corr), 'best lag: ' + str(best_lag) + '; corr val: ' + str(np.round(corr[ix_peak],3)))\n axs[2].text(shift_vec[5], 0.6*np.nanmax(corr), 'best shift: ' + str(best_shift) + ' m'+ '; corr val: ' + str(np.round(corr[ix_peak],3)))\n axs[2].text(shift_vec[5], 0.3*np.nanmax(corr), 'veloc of ' + str(np.round(best_shift/(dt/365),1)) + ' m/yr')\n\n plt.tight_layout() \n fig1.suptitle('black = older cycle data, red = newer cycle data to search across')", "_____no_output_____" ], [ "n_veloc = len(cycles) - 1\n\nsegment_length = 2000 # m\n\nsearch_width = 800 # m\ndx = 20 # meters between x_atc points\n\ncorrelation_threshold = 0.65\n\nx1 = 2.915e7#x_atc[cycles[0]][beams[0]][1000] <-- the very first x value in a file; doesn't work, I think b/c nans # 2.93e7\nx1s = x_atc[cycles[veloc_number]][beams[0]][search_width:-segment_length-2*search_width:10]\nvelocities = {} \ncorrelations = {} \n\nfor beam in beams:\n velocities[beam] = np.empty_like(x1s)\n correlations[beam] = np.empty_like(x1s)\nfor xi,x1 in enumerate(x1s):\n for veloc_number in range(n_veloc):\n cycle1 = cycles[veloc_number]\n cycle2 = cycles[veloc_number+1]\n t1_string = times[cycle1]['gt1l'][0].astype(str) #figure out later if just picking hte first one it ok\n t1 = Time(t1_string)\n\n t2_string = times[cycle2]['gt1l'][0].astype(str) #figure out later if just picking hte first one it ok\n t2 = Time(t2_string)\n\n dt = (t2 - t1).jd # difference in julian days\n\n for beam in beams:\n # cut out small chunk of data at time t1 (first cycle)\n x_full_t1 = x_atc[cycle1][beam]\n ix_x1 = np.arange(len(x_full_t1))[x_full_t1 >= x1][0]\n ix_x2 = ix_x1 + int(np.round(segment_length/dx)) \n x_t1 = x_full_t1[ix_x1:ix_x2]\n h_li1 = h_li_diff[cycle1][beam][ix_x1-1:ix_x2-1] # start 1 index earlier because the data are differentiated\n\n # cut out a wider chunk of data at time t2 (second cycle)\n x_full_t2 = x_atc[cycle2][beam]\n ix_x3 = ix_x1 - int(np.round(search_width/dx)) # offset on earlier end by # indices in search_width\n ix_x4 = ix_x2 + int(np.round(search_width/dx)) # offset on later end by # indices in search_width\n x_t2 = x_full_t2[ix_x3:ix_x4]\n h_li2 = h_li_diff[cycle2][beam][ix_x3:ix_x4]\n\n # correlate old with newer data\n corr = correlate(h_li1, h_li2, mode = 'valid', method = 'direct') \n norm_val = np.sqrt(np.sum(h_li1**2)*np.sum(h_li2**2)) # normalize so values range between 0 and 1\n corr = corr / norm_val\n\n\n # lagvec = np.arange( -(len(h_li1) - 1), len(h_li2), 1)# for mode = 'full'\n # lagvec = np.arange( -int(search_width/dx) - 1, int(search_width/dx) +1, 1) # for mode = 'valid'\n lagvec = np.arange(- int(np.round(search_width/dx)), int(search_width/dx) +1,1)# for mode = 'valid'\n\n shift_vec = lagvec * dx\n \n if all(np.isnan(corr)):\n velocities[beam][xi] = np.nan\n correlations[beam][xi] = np.nan\n\n else:\n correlation_value = np.nanmax(corr)\n if correlation_value >= correlation_threshold:\n ix_peak = np.arange(len(corr))[corr == correlation_value][0]\n best_lag = lagvec[ix_peak]\n best_shift = shift_vec[ix_peak]\n velocities[beam][xi] = best_shift/(dt/365)\n correlations[beam][xi] = correlation_value\n\n else:\n velocities[beam][xi] = np.nan\n correlations[beam][xi] = correlation_value\n\n", "_____no_output_____" ], [ "plt.figure()\nax1 = plt.subplot(211)\nfor filename, Di in D_2l.items():\n #Plot only points that have ATL06_quality_summary==0 (good points)\n hl=plot_elevation(Di, ind=Di['atl06_quality_summary']==0, label=f\"cycle={Di['cycle']}\")\n #hl=plt.plot(Di['x_atc'][Di['atl06_quality_summary']==0], Di['h_li'][Di['atl06_quality_summary']==0], '.', label=f\"cycle={Di['cycle']}\")\nplt.legend()\nplt.ylabel('elevation');\n\nax2 = plt.subplot(212,sharex=ax1)\nfor beam in beams:\n plt.plot(x1s+dx*(segment_length/2),velocities[beam],'.',alpha=0.2,ms=3,label=beam)\nplt.ylabel('velocity (m/yr)')\nplt.xlabel('x_atc')\nplt.ylim(0,1500)\nplt.legend()\nplt.suptitle('Along track velocity: all beams')", "/srv/conda/envs/notebook/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).\n \"\"\"Entry point for launching an IPython kernel.\n" ] ], [ [ "#### **Median velocity for all 6 beams:**\n\n**Above a cross-correlation threshold of 0.65**", "_____no_output_____" ] ], [ [ "plt.figure()\nax1 = plt.subplot(211)\nfor filename, Di in D_2l.items():\n #Plot only points that have ATL06_quality_summary==0 (good points)\n hl=plot_elevation(Di, ind=Di['atl06_quality_summary']==0, label=f\"cycle={Di['cycle']}\")\n #hl=plt.plot(Di['x_atc'][Di['atl06_quality_summary']==0], Di['h_li'][Di['atl06_quality_summary']==0], '.', label=f\"cycle={Di['cycle']}\")\nplt.legend()\nplt.ylabel('elevation');\n\nax2 = plt.subplot(212,sharex=ax1)\n\nmedians = np.empty(len(x1s))\nstds = np.empty(len(x1s))\n\nfor xi, x1 in enumerate(x1s):\n corr_vals = []\n velocs = []\n for beam in beams:\n corr_vals += [correlations[beam][xi]]\n velocs += [velocities[beam][xi]]\n n_obs = len(velocs)\n if n_obs >0:\n corr_mask = np.array(corr_vals) >= correlation_threshold\n veloc_mask = np.abs(np.array(velocs)) < 0.67*segment_length # get rid of segments that are nailed against one edge for some reason\n mask = corr_mask * veloc_mask\n median_veloc = np.nanmedian(np.array(velocs)[mask])\n \n std_veloc = np.nanstd(np.array(velocs)[mask])\n medians[xi] = median_veloc\n stds[xi] = std_veloc\n ax2.plot([x1,x1], [median_veloc - std_veloc, median_veloc +std_veloc], '-', color= [0.7, 0.7, 0.7])\n\nax2.plot(x1s, medians, 'k.', markersize=2)\n\n# for beam in beams:\n# plt.plot(x1s+dx*(segment_length/2),velocities[beam],'.',alpha=0.2,ms=3,label=beam)\nplt.ylabel('velocity (m/yr)')\nplt.xlabel('x_atc')\nplt.ylim(0,1500)\nplt.legend()\nplt.suptitle('Median along track velocity')\n\nplt.figure()\nax1 = plt.subplot(211)\nfor beam in beams:\n xvals = x1s+dx*(segment_length/2)\n corrs = correlations[beam]\n ixs = corrs >= correlation_threshold\n ax1.plot(xvals[ixs], corrs[ixs],'.',alpha=0.2,ms=3,label=beam)\nplt.ylabel('correlation values, 0->1')\nplt.xlabel('x_atc')\nplt.legend()\nplt.suptitle('Correlation values > threshold, all beams')\n\nax1 = plt.subplot(212)\nfor beam in beams:\n ax1.plot(x1s+dx*(segment_length/2),correlations[beam],'.',alpha=0.2,ms=3,label=beam)\nplt.ylabel('correlation values, 0->1')\nplt.xlabel('x_atc')\nplt.legend()\nplt.suptitle('Correlation values, all beams')", "/srv/conda/envs/notebook/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).\n \"\"\"Entry point for launching an IPython kernel.\n" ] ], [ [ "Comparison between measures", "_____no_output_____" ], [ "### Results:", "_____no_output_____" ], [ "**848**\n\n**Speaker: Lynn Kaluzienski**", "_____no_output_____" ], [ "![LynnFig](Figure_96.png)", "_____no_output_____" ], [ "![comparison1](median_along_track1.png)", "_____no_output_____" ], [ "**537**\n\n**Speaker: Joseph Martin**", "_____no_output_____" ], [ "![537_velocity](0537_measures.png)", "_____no_output_____" ], [ "![comparison](median_along_track2.png)", "_____no_output_____" ], [ "![537_veloc](537_velocity.png)", "_____no_output_____" ], [ "### Future Work for the Surface Velocity Team:\n\n**Speaker: David Polashenski**\n\n- Calculating correlation uncertainty\n- Considering larger, more complex areas\n- Pending objectives\n - Develop methodology to extract Across Track velocities and test efficacy\n - Compare ICESat GLAS methodology (Along Track) to ICESat-2 methodology (Across Track)\n - Compare the capabilites of ICESat-2 to extract surface ice velocity from ice shelves and ice streams", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "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", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cb64feaa6a262eed355fa74b3d90c714920daf42
15,540
ipynb
Jupyter Notebook
notebooks/training_hello_world.ipynb
thundercomb/aitextgen
6e07361a2f15de7925a3cdefc91d32390b7489c9
[ "MIT" ]
1,416
2020-05-18T15:41:34.000Z
2022-03-31T09:39:55.000Z
notebooks/training_hello_world.ipynb
thundercomb/aitextgen
6e07361a2f15de7925a3cdefc91d32390b7489c9
[ "MIT" ]
165
2020-05-19T00:14:32.000Z
2022-03-30T16:56:36.000Z
notebooks/training_hello_world.ipynb
thundercomb/aitextgen
6e07361a2f15de7925a3cdefc91d32390b7489c9
[ "MIT" ]
156
2020-05-18T16:28:17.000Z
2022-03-24T14:50:31.000Z
39.441624
1,907
0.600837
[ [ [ "# aitextgen Training Hello World\n\n_Last Updated: Feb 21, 2021 (v.0.4.0)_\n\nby Max Woolf\n\nA \"Hello World\" Tutorial to show how training works with aitextgen, even on a CPU!", "_____no_output_____" ] ], [ [ "from aitextgen.TokenDataset import TokenDataset\nfrom aitextgen.tokenizers import train_tokenizer\nfrom aitextgen.utils import GPT2ConfigCPU\nfrom aitextgen import aitextgen", "_____no_output_____" ] ], [ [ "First, download this [text file of Shakespeare's plays](https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt), to the folder with this notebook, then put the name of the downloaded Shakespeare text for training into the cell below.", "_____no_output_____" ] ], [ [ "file_name = \"input.txt\"", "_____no_output_____" ] ], [ [ "You can now train a custom Byte Pair Encoding Tokenizer on the downloaded text!\n\nThis will save one file: `aitextgen.tokenizer.json`, which contains the information needed to rebuild the tokenizer.", "_____no_output_____" ] ], [ [ "train_tokenizer(file_name)\ntokenizer_file = \"aitextgen.tokenizer.json\"", "_____no_output_____" ] ], [ [ "`GPT2ConfigCPU()` is a mini variant of GPT-2 optimized for CPU-training.\n\ne.g. the # of input tokens here is 64 vs. 1024 for base GPT-2. This dramatically speeds training up.", "_____no_output_____" ] ], [ [ "config = GPT2ConfigCPU()", "_____no_output_____" ] ], [ [ "Instantiate aitextgen using the created tokenizer and config", "_____no_output_____" ] ], [ [ "ai = aitextgen(tokenizer_file=tokenizer_file, config=config)", "_____no_output_____" ] ], [ [ "You can build datasets for training by creating TokenDatasets, which automatically processes the dataset with the appropriate size.", "_____no_output_____" ] ], [ [ "data = TokenDataset(file_name, tokenizer_file=tokenizer_file, block_size=64)\ndata", "100%|██████████| 40000/40000 [00:00<00:00, 86712.61it/s]\n" ] ], [ [ "Train the model! It will save pytorch_model.bin periodically and after completion to the `trained_model` folder. On a 2020 8-core iMac, this took ~25 minutes to run.\n\nThe configuration below processes 400,000 subsets of tokens (8 * 50000), which is about just one pass through all the data (1 epoch). Ideally you'll want multiple passes through the data and a training loss less than `2.0` for coherent output; when training a model from scratch, that's more difficult, but with long enough training you can get there!", "_____no_output_____" ] ], [ [ "ai.train(data, batch_size=8, num_steps=50000, generate_every=5000, save_every=5000)", "pytorch_model.bin already exists in /trained_model and will be overwritten!\nGPU available: False, used: False\nTPU available: None, using: 0 TPU cores\n\u001b[1m5,000 steps reached: saving model to /trained_model\u001b[0m\n\u001b[1m5,000 steps reached: generating sample texts.\u001b[0m\n==========\n's dead;\nBut is no winted in his northeritiff\nTave passage, and eleve your hours.\n\nPETRUCHIO:\nWhat is this I does, I will, sir;\nThat, you have, nor tolding we\n==========\n\u001b[1m10,000 steps reached: saving model to /trained_model\u001b[0m\n\u001b[1m10,000 steps reached: generating sample texts.\u001b[0m\n==========\n.\n\nQUEEN ELIZABETH:\nI know, to, fair beat, to my soul is wonder'd intend.\n\nKING RICHARD III:\nHold, and threaten, my lord, and my shame!\n\nQUEEN ELIZAB\n==========\n\u001b[1m15,000 steps reached: saving model to /trained_model\u001b[0m\n\u001b[1m15,000 steps reached: generating sample texts.\u001b[0m\n==========\ns of capitcts!\n\nEDWARD:\nGardener, what is this hour will not say.\nWhat, shall the joint, I pray, if they\nHarry, let bid me as he would readness so.\n\nB\n==========\n\u001b[1m20,000 steps reached: saving model to /trained_model\u001b[0m\n\u001b[1m20,000 steps reached: generating sample texts.\u001b[0m\n==========\n for.\n\nROMEO:\nFair to the iercing wide's fretch,\nAnd happy talk of the master,\nAnd waste their justice with the feet and punning,\nAnd therefore be ben\n==========\n\u001b[1m25,000 steps reached: saving model to /trained_model\u001b[0m\n\u001b[1m25,000 steps reached: generating sample texts.\u001b[0m\n==========\n,\nThat we we will have not lose such.\n\nSee, to the kingdom of our virtue,\nYou banish'd our purpose, for our own ignorse,\nDispon I remain, and seem'd in\n==========\n\u001b[1m30,000 steps reached: saving model to /trained_model\u001b[0m\n\u001b[1m30,000 steps reached: generating sample texts.\u001b[0m\n==========\n.\n\nBENVOLIO:\nO, she's dead!\n\nCAMILLO:\nNo, my lord;\nThese accession will be hous.\n\nDERBY:\nNo, my lord.\n\nGLOUCESTER:\nWhat is the\n==========\n\u001b[1m35,000 steps reached: saving model to /trained_model\u001b[0m\n\u001b[1m35,000 steps reached: generating sample texts.\u001b[0m\n==========\n,\nAnd whiles it is but the castle,\nThat stavin'd in the gods of men.\n\nCOMFEY:\nWhat, then?\n\nELBOW:\nPeace, my lord,\nAnd weat your greats\n==========\n\u001b[1m40,000 steps reached: saving model to /trained_model\u001b[0m\n\u001b[1m40,000 steps reached: generating sample texts.\u001b[0m\n==========\n\nThe white mercy of the sun upon my past,\nOf my father's son be first, thy sake,\nHis son's chief son, and my includy;\nAnd if thy brother's loss, thy thrief,\n\n==========\n\u001b[1m45,000 steps reached: saving model to /trained_model\u001b[0m\n\u001b[1m45,000 steps reached: generating sample texts.\u001b[0m\n==========\n to the crown,\nOr I'll privy I have.\n\nPOLIXENES:\nI have been a stir.\n\nLEONTES:\nThe worshiped, the benefition of the crown.\n\nHis somet\n==========\n\u001b[1m50,000 steps reached: saving model to /trained_model\u001b[0m\n\u001b[1m50,000 steps reached: generating sample texts.\u001b[0m\n==========\n:\nCatesby, girls, and make avoides;\nBut, welcome a far\nThat ever home, like a villain, and behold\nCanusy not passing nonquial at the g\n==========\nLoss: 2.940 — Avg: 2.884: 100%|██████████| 50000/50000 [31:39<00:00, 26.32it/s]\n" ] ], [ [ "Generate text from your trained model!", "_____no_output_____" ] ], [ [ "ai.generate(10, prompt=\"ROMEO:\")", "\u001b[1mROMEO:\u001b[0m\nAbook, ho! forthing me, gentle Earl's royal king,\nAnd this, I, with that I do not beseech you\nTo visit the battle, that I should believe you,\nWhich I would never\n==========\n\u001b[1mROMEO:\u001b[0m\nConfound is gone, thou art a maid into the widow;\nPut up my life and make me no harmony\nAnd make thee I know uncle,\nUnconted and curses: therefore in my\n==========\n\u001b[1mROMEO:\u001b[0m\nGod push! but what days to see\nThe giving bleedom's heart I do? Therefore,\nAnd most unless I had rather. He saddle\nTake your cold shack down; and so far I\n==========\n\u001b[1mROMEO:\u001b[0m\nPersetain'd up the earth of mercy,\nAnd never yet, the sun to make him all the\nMore than my battle.\n\nROMEO:\nI warrant him, to know, we'll not do't, but hate me\n==========\n\u001b[1mROMEO:\u001b[0m\nMethinks I am a mile, and trench one\nThy winded makes, in faults and cast\nWith one to meether, of twenty days,\nThat in my waters, that f\n==========\n\u001b[1mROMEO:\u001b[0m\nO, here is such a woman guilty.\n\nROMEO:\nI do not think it; I should be renowned\nThat I am in that which can controy\nA bawd I take it to the purpose.\n\nJU\n==========\n\u001b[1mROMEO:\u001b[0m\nI know not what I am.\n\nFLORIZEL:\nAy, as I did,\nI would be adverpite of the homely treason\nFrom the doubled in the farm of his bed.\nTa\n==========\n\u001b[1mROMEO:\u001b[0m\nI pray you, he would have taken to him but,\nAnd freely mark his into a fine of it,\nSpeak to the second to our cheek;\nAnd every day, and sanctious cover\n==========\n\u001b[1mROMEO:\u001b[0m\nI had left me--born to be drawn.\n\nJULIET:\nMy husbour, I will have thee here:\nAnd, I have found to seek thyself.\n\nJULIET:\nI will be not b\n==========\n\u001b[1mROMEO:\u001b[0m\nThat is a hour,\nThe castard is, I'll not buy, or indeeding.\n\nNurse:\nLADY CAPULET:\nThe matter, that ta'en as I may find thee.\n\n" ] ], [ [ "With your trained model, you can reload the model at any time by providing the `pytorch_model.bin` model weights, the `config`, and the `tokenizer`.", "_____no_output_____" ] ], [ [ "ai2 = aitextgen(model_folder=\"trained_model\",\n tokenizer_file=\"aitextgen.tokenizer.json\")", "_____no_output_____" ], [ "ai2.generate(10, prompt=\"ROMEO:\")", "\u001b[1mROMEO:\u001b[0m\nBoy, unreacher, unhallupony, in Padua,\nUntimely fall till I be learn'd.\n\nROMEO:\nFie, good friar, be quick, for I am,\nI'll\n==========\n\u001b[1mROMEO:\u001b[0m\nI'll be plain, I am a tail of blessed wounds;\nFor I am dead, I have not borne to make\nA couple of her fortune, but that I'll bear,\nAnd say 'Ay, chur\n==========\n\u001b[1mROMEO:\u001b[0m\nAnd yet I am a resolution of my dear dear:\nIf I have not reason to do me say\nI'll deny the sea of my body to answer,\nAnd all thy tale, or I have my m\n==========\n\u001b[1mROMEO:\u001b[0m\nIntenty to a bawd of my bait,--\n\nJULIET:\nNo, I hope to know the title,\nFor that I wish her place.\n\nJULIET:\nDo I assure her?\n==========\n\u001b[1mROMEO:\u001b[0m\nO, what's the parle that I chide thee,\nThat honourable may be, that I have still'd thee:\nI pray thee, my lord.\n\nMERCUTIO:\nI', my lord.\n\nROMEO:\nHere is a\n==========\n\u001b[1mROMEO:\u001b[0m\nAnd, for I am, and not talk of that?\n\nROMEO:\nWhere's my child, I would guess thee here.\n\nJULIET:\nNay, boy, I'll not be bowling why I;\nO thou\n==========\n\u001b[1mROMEO:\u001b[0m\nO, but thou hast seen thee of mine own.\n\nROMEO:\nI would assist thee--\n\nJULIET:\nAy, it is, and not so.\n\nROMEO:\nNo, but that I must told me with it.\n\nROMEO\n==========\n\u001b[1mROMEO:\u001b[0m\nNo, no, nor I am. I am content.\n\nBENVOLIO:\nI will not, sir: but I have required\nAs I am grown in the lawful virtue\nThat it hath bid you think, and I\n==========\n\u001b[1mROMEO:\u001b[0m\nThat I should pardon, I would be gone.\n\nESCALUS:\nI should believe you, sir, sir, ay, I would not\nnot know more, but that I can, but I would have savour me.\n\nP\n==========\n\u001b[1mROMEO:\u001b[0m\nAnd thou, I will find out thy life the wind of love.\n\nROMEO:\nIt is the morning groom of it.\n\nJULIET:\nFie, good sweet boy, I will take my leave to a happy day,\n" ] ], [ [ "# MIT License\n\nCopyright (c) 2021 Max Woolf\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
cb6500c1cbfb3e82eea9a0466473df8230f61f26
10,482
ipynb
Jupyter Notebook
jupyterhub/notebooks/zz_under_construction/zz_old/TensorFlow/TensorFrames/ML/KMeans.ipynb
just4jc/pipeline
3c7a4fa59c6363833766d2b55fa55ace6b6af351
[ "Apache-2.0" ]
1
2018-03-13T09:46:17.000Z
2018-03-13T09:46:17.000Z
jupyterhub/notebooks/zz_under_construction/zz_old/TensorFlow/TensorFrames/ML/KMeans.ipynb
just4jc/pipeline
3c7a4fa59c6363833766d2b55fa55ace6b6af351
[ "Apache-2.0" ]
null
null
null
jupyterhub/notebooks/zz_under_construction/zz_old/TensorFlow/TensorFrames/ML/KMeans.ipynb
just4jc/pipeline
3c7a4fa59c6363833766d2b55fa55ace6b6af351
[ "Apache-2.0" ]
2
2018-08-19T15:05:18.000Z
2020-08-13T16:31:48.000Z
49.443396
926
0.587388
[ [ [ "\"\"\" Simple distributed implementation of the K-Means algorithm using Tensorflow.\n\"\"\"\n\nimport tensorflow as tf\nimport tensorframes as tfs\nfrom pyspark.mllib.random import RandomRDDs\nimport numpy as np\n\nnum_features = 4\nk = 2\n# TODO: does not work with 1\ndata = RandomRDDs.normalVectorRDD(\n sc,\n numCols=num_features,\n numRows=100,\n seed=1).map(lambda v: [v.tolist()])\ndf = sqlContext.createDataFrame(data).toDF(\"features\")\n\n# For now, analysis is still required.\ndf0 = tfs.analyze(df)\n\ninit_centers = np.random.randn(k, num_features)\n\n# For debugging\nblock = np.array(data.take(10))[::,0,::]\n\n# Find the distances first\nwith tf.Graph().as_default() as g:\n points = tf.placeholder(tf.double, shape=[None, num_features], name='points')\n num_points = tf.shape(points)[0]\n #centers = tf.placeholder(tf.double, shape=[k, num_features], name='centers')\n centers = tf.constant(init_centers)\n squares = tf.reduce_sum(tf.square(points), reduction_indices=1)\n center_squares = tf.reduce_sum(tf.square(centers), reduction_indices=1)\n prods = tf.matmul(points, centers, transpose_b = True)\n t1a = tf.expand_dims(center_squares, 0)\n t1b = tf.pack([num_points, 1])\n t1 = tf.tile(t1a, t1b)\n t2a = tf.expand_dims(squares, 1)\n t2b = tf.pack([1, k])\n t2 = tf.tile(t2a, t2b)\n distances = t1 + t2 - 2 * prods\n indexes = tf.argmin(distances, 1)\n sess = tf.Session()\n print sess.run([distances, indexes], feed_dict={points:block, centers:init_centers})\n\nwith tf.Graph().as_default() as g:\n points = tf.placeholder(tf.double, shape=[None, num_features], name='features')\n num_points = tf.shape(points)[0]\n centers = tf.constant(init_centers)\n squares = tf.reduce_sum(tf.square(points), reduction_indices=1)\n center_squares = tf.reduce_sum(tf.square(centers), reduction_indices=1)\n prods = tf.matmul(points, centers, transpose_b = True)\n t1a = tf.expand_dims(center_squares, 0)\n t1b = tf.pack([num_points, 1])\n t1 = tf.tile(t1a, t1b)\n t2a = tf.expand_dims(squares, 1)\n t2b = tf.pack([1, k])\n t2 = tf.tile(t2a, t2b)\n distances = t1 + t2 - 2 * prods\n # TODO cast\n indexes = tf.argmin(distances, 1, name='indexes')\n min_distances = tf.reduce_min(distances, 1, name='min_distances')\n counts = tf.tile(tf.constant([1]), tf.pack([num_points]), name='count')\n df2 = tfs.map_blocks([indexes, counts, min_distances], df0)\n\n# Perform the reduction\ngb = df2.groupBy(\"indexes\")\nwith tf.Graph().as_default() as g:\n # Look at the documentation of tfs.aggregate for the naming conventions of the placeholders.\n x_input = tfs.block(df2, \"features\", tf_name=\"features_input\")\n count_input = tfs.block(df2, \"count\", tf_name=\"count_input\")\n md_input = tfs.block(df2, \"min_distances\", tf_name=\"min_distances_input\")\n x = tf.reduce_sum(x_input, [0], name='features')\n count = tf.reduce_sum(count_input, [0], name='count')\n min_distances = tf.reduce_sum(md_input, [0], name='min_distances')\n df3 = tfs.aggregate([x, count, min_distances], gb)\n\n# Get the new centroids\ndf3_c = df3.collect()\nnew_centers = np.array([np.array(row.features) / row['count'] for row in df3_c])\ntotal_distances = np.sum([row['min_distances'] for row in df3_c])\n\n\ndef run_one_step(dataframe, start_centers):\n \"\"\"\n Performs one iteration of K-Means.\n\n This function takes a dataframe with dense feature vectors, a set of centroids, and returns\n a new set of centroids along with the total distance of points to centroids.\n\n This function calculates for each point the closest centroid and then aggregates the newly\n formed clusters to find the new centroids.\n\n :param dataframe: a dataframe containing a column of features (an array of doubles)\n :param start_centers: a k x m matrix with k the number of centroids and m the number of features\n :return: a k x m matrix, and a positive double\n \"\"\"\n # The dimensions in the problem\n (num_centroids, num_features) = np.shape(start_centers)\n # For each feature vector, compute the nearest centroid and the distance to that centroid.\n # The index of the nearest centroid is stored in the 'indexes' column.\n # We also add a column of 1's that will be reduced later to count the number of elements in\n # each cluster.\n with tf.Graph().as_default() as g:\n # The placeholder for the input: we use the block format\n points = tf.placeholder(tf.double, shape=[None, num_features], name='features')\n # The shape of the block is extracted as a TF variable.\n num_points = tf.shape(points)[0]\n # The centers are embedded in the TF program.\n centers = tf.constant(start_centers)\n # Computation of the minimum distance. This is a standard implementation that follows\n # what MLlib does.\n squares = tf.reduce_sum(tf.square(points), reduction_indices=1)\n center_squares = tf.reduce_sum(tf.square(centers), reduction_indices=1)\n prods = tf.matmul(points, centers, transpose_b = True)\n t1a = tf.expand_dims(center_squares, 0)\n t1b = tf.pack([num_points, 1])\n t1 = tf.tile(t1a, t1b)\n t2a = tf.expand_dims(squares, 1)\n t2b = tf.pack([1, num_centroids])\n t2 = tf.tile(t2a, t2b)\n distances = t1 + t2 - 2 * prods\n # The outputs of the program.\n # The closest centroids are extracted.\n indexes = tf.argmin(distances, 1, name='indexes')\n # This could be done based on the indexes as well.\n min_distances = tf.reduce_min(distances, 1, name='min_distances')\n counts = tf.tile(tf.constant([1]), tf.pack([num_points]), name='count')\n df2 = tfs.map_blocks([indexes, counts, min_distances], dataframe)\n # Perform the reduction: we regroup the point by their centroid indexes.\n gb = df2.groupBy(\"indexes\")\n with tf.Graph().as_default() as g:\n # Look at the documentation of tfs.aggregate for the naming conventions of the placeholders.\n x_input = tfs.block(df2, \"features\", tf_name=\"features_input\")\n count_input = tfs.block(df2, \"count\", tf_name=\"count_input\")\n md_input = tfs.block(df2, \"min_distances\", tf_name=\"min_distances_input\")\n # Each operation is just the sum.\n x = tf.reduce_sum(x_input, [0], name='features')\n count = tf.reduce_sum(count_input, [0], name='count')\n min_distances = tf.reduce_sum(md_input, [0], name='min_distances')\n df3 = tfs.aggregate([x, count, min_distances], gb)\n # Get the new centroids\n df3_c = df3.collect()\n # The new centroids.\n new_centers = np.array([np.array(row.features) / row['count'] for row in df3_c])\n total_distances = np.sum([row['min_distances'] for row in df3_c])\n return (new_centers, total_distances)\n\ndef kmeans(dataframe, init_centers, num_iters = 50):\n c = init_centers\n d = np.Inf\n ds = []\n for i in range(num_iters):\n (c1, d1) = run_one_step(dataframe, c)\n print \"Step =\", i, \", overall distance = \", d1\n c = c1\n if d == d1:\n break\n d = d1\n ds.append(d1)\n return c, ds\n\nc, ds = kmeans(df0, init_centers)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
cb650203c540e3a004c25fecf475b1d9dcf13f05
482,890
ipynb
Jupyter Notebook
deTiN_example_0.1_TiN_sim.ipynb
btrspg/deTiN
8076827fb915e6d675dca3940721b7a49f7198d3
[ "BSD-3-Clause" ]
null
null
null
deTiN_example_0.1_TiN_sim.ipynb
btrspg/deTiN
8076827fb915e6d675dca3940721b7a49f7198d3
[ "BSD-3-Clause" ]
null
null
null
deTiN_example_0.1_TiN_sim.ipynb
btrspg/deTiN
8076827fb915e6d675dca3940721b7a49f7198d3
[ "BSD-3-Clause" ]
null
null
null
1,485.815385
177,464
0.948262
[ [ [ "## Example deTiN run using data from invitro mixing validation experiment", "_____no_output_____" ], [ "Loading data and deTiN modules:", "_____no_output_____" ] ], [ [ "import deTiN.deTiN \nimport deTiN.deTiN_SSNV_based_estimate as dssnv\nimport deTiN.deTiN_aSCNA_based_estimate as dascna\nimport deTiN.deTiN_utilities as du\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport optparse\nargs = optparse.Values()\nargs.mutation_data_path ='example_data/HCC_10_90.call_stats.pon_removed.txt'\nargs.cn_data_path = 'example_data/HCC-1143_100_T-sim-final.acs.seg'\nargs.tumor_het_data_path ='example_data/HCC_10_90.tumor.hets.tsv'\nargs.normal_het_data_path = 'example_data/HCC_10_90.normal.hets.tsv'\nargs.exac_data_path = 'example_data/exac.pickle_high_af'\nargs.indel_data_path = 'example_data/MuTect2.call_stats.txt'\nargs.indel_data_type = 'MuTect2'\nargs.output_dir = 'example_data/'\nargs.aSCNA_threshold = 0.1\nargs.output_name = 'HCC_10_90'\nargs.use_outlier_removal = True\nargs.mutation_prior = 0.1\nargs.TiN_prior = 1\nargs.resolution = 101\nargs.weighted_classification = False\ndi = deTiN.input(args)\ndi.read_and_preprocess_data()", "_____no_output_____" ] ], [ [ "Estimate tumor in normal based on SSNVs : ", "_____no_output_____" ] ], [ [ "reload(dssnv)\n# identify SSNV candidates based on MuTect and panel of normal flags \ndi.candidates = du.select_candidate_mutations(di.call_stats_table,di.exac_db_file)\n# generate SSNV based model using candidate sites\nssnv_based_model = dssnv.model(di.candidates, di.mutation_prior,di.resolution)\nssnv_based_model.perform_inference()", "pre-processing SSNV data\ninitialized TiN to 0\nTiN inference after 1 iterations = 0.09\nTiN inference after 2 iterations = 0.11\nTiN inference after 3 iterations = 0.11\nSSNV based TiN estimate converged: TiN = 0.11 based on 340 sites\n" ] ], [ [ "Estimate tumor in normal based on aSCNAs", "_____no_output_____" ] ], [ [ "# filter input SNPs based to maintain symmetry \ndi.aSCNA_hets = du.ensure_balanced_hets(di.seg_table,di.het_table)", "_____no_output_____" ], [ "# recalculate minor allele fraction and detect allelic imbalance\ndi.aSCNA_segs,convergent_segs = du.identify_aSCNAs(di.seg_table,di.aSCNA_hets,di.aSCNA_thresh)", "identified convergent aSCNA in normal on chromosomes:[2]\n" ], [ "reload(dascna)\n# generate aSCNA based model \nascna_based_model = dascna.model(di.aSCNA_segs, di.aSCNA_hets,di.resolution)\n# MAP estimate of TiN for each segment and then K-means clustering procedure\nascna_based_model.perform_inference()", "calculating aSCNA based TiN estimate using data from chromosomes: [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21]\ndetected 3 clusters\naSCNA based TiN estimate from selected TiN cluster : 0.12\n" ], [ "# calculate joint estimate and recover mutations \ndo = deTiN.output(di,ssnv_based_model,ascna_based_model)\ndo.calculate_joint_estimate()\n# reclassify somatic events based on TiN estimate\ndo.reclassify_mutations()\n# write out SSNVs with deTiN annotations (rescued SSNVs are marked KEEP)\ndo.SSNVs.to_csv(path_or_buf=do.input.output_path + '/' + do.input.output_name + '_deTiN_SSNVs.txt',sep='\\t')", "joint TiN estimate = 0.12\n" ], [ "# plot TiN posteriors from each model and the joint estimate\ndu.plot_TiN_models(do)", "_____no_output_____" ], [ "# plot recovered SSNVs based on TiN\ndu.plot_SSNVs(do)", "_____no_output_____" ], [ "# plot K-means clustering results and RSS information\ndu.plot_kmeans_info(ascna_based_model,do.input.output_path,do.input.output_name)", "_____no_output_____" ], [ "# plot K-means clustering results and RSS information\ndu.plot_aSCNA_het_data(do)", "_____no_output_____" ], [ "do.SSNVs.to_csv(path_or_buf=do.input.output_path + '/' + do.input.output_name + '_deTiN_SSNVs.txt', sep='\\t',index=None)\nfile = open(do.input.output_path + '/' + do.input.output_name + 'TiN_estimate_CI.txt', 'w')\nfile.write('%s - %s' % (str(do.CI_tin_low),str(do.CI_tin_high)))\nfile.close() \nfile = open(do.input.output_path +'/' + do.input.output_name + 'TiN_estimate.txt', 'w')\nfile.write('%d' % (do.TiN))\nfile.close()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb65047b8351099d62527ca6d9ed2b7193b320ba
18,073
ipynb
Jupyter Notebook
notebooks/Introductory/acquisition_model_mr_pet_ct.ipynb
paskino/SIRF-Exercises
8203077840b1667719467f0d8c6b009625e8f27d
[ "Apache-2.0" ]
null
null
null
notebooks/Introductory/acquisition_model_mr_pet_ct.ipynb
paskino/SIRF-Exercises
8203077840b1667719467f0d8c6b009625e8f27d
[ "Apache-2.0" ]
1
2021-05-18T22:33:44.000Z
2021-05-19T03:03:05.000Z
notebooks/Introductory/acquisition_model_mr_pet_ct.ipynb
paskino/SIRF-Exercises
8203077840b1667719467f0d8c6b009625e8f27d
[ "Apache-2.0" ]
null
null
null
30.946918
673
0.600454
[ [ [ "# Acquisition Models for MR, PET and CT\nThis demonstration shows how to set-up and use SIRF/CIL acquisition models for different modalities. You should have tried the `introduction` notebook first. The current notebook briefly repeats some items without explanation.\n\nThis demo is a jupyter notebook, i.e. intended to be run step by step.\nYou could export it as a Python file and run it one go, but that might\nmake little sense as the figures are not labelled.\n", "_____no_output_____" ], [ "Authors: Christoph Kolbitsch, Edoardo Pasca, Kris Thielemans\n\nFirst version: 23rd of April 2021 \n\nCCP SyneRBI Synergistic Image Reconstruction Framework (SIRF). \nCopyright 2015 - 2017 Rutherford Appleton Laboratory STFC. \nCopyright 2015 - 2019, 2021 University College London. \nCopyright 2021 Physikalisch-Technische Bundesanstalt.\n\nThis is software developed for the Collaborative Computational\nProject in Synergistic Reconstruction for Biomedical Imaging\n(http://www.ccpsynerbi.ac.uk/).\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.", "_____no_output_____" ], [ "# Initial set-up", "_____no_output_____" ] ], [ [ "# Make sure figures appears inline and animations works\n%matplotlib notebook", "_____no_output_____" ], [ "# Initial imports etc\nimport numpy\nimport matplotlib.pyplot as plt\n\nimport os\nimport sys\nimport shutil\nimport brainweb\nfrom tqdm.auto import tqdm\n\n# Import MR, PET and CT functionality\nimport sirf.Gadgetron as mr\nimport sirf.STIR as pet\nimport cil.framework as ct\n\nfrom sirf.Utilities import examples_data_path\nfrom cil.plugins.astra.operators import ProjectionOperator as ap", "_____no_output_____" ] ], [ [ "If the above failed with a message like `No module named 'cil.plugins.astra'`, Astra has not been installed. Most CIL lines will therefore fail. We recommend that you comment them out (or install the Astra plugin for CIL of course).", "_____no_output_____" ], [ "# Utilities", "_____no_output_____" ], [ "First define some handy function definitions to make subsequent code cleaner. You can ignore them when you first see this demo.\nThey have (minimal) documentation using Python docstrings such that you can do for instance `help(plot_2d_image)`", "_____no_output_____" ] ], [ [ "def plot_2d_image(idx,vol,title,clims=None,cmap=\"viridis\"):\n \"\"\"Customized version of subplot to plot 2D image\"\"\"\n plt.subplot(*idx)\n plt.imshow(vol,cmap=cmap)\n if not clims is None:\n plt.clim(clims)\n plt.colorbar()\n plt.title(title)\n plt.axis(\"off\")\n\ndef crop_and_fill(templ_im, vol):\n \"\"\"Crop volumetric image data and replace image content in template image object\"\"\"\n # Get size of template image and crop\n idim_orig = templ_im.as_array().shape\n idim = (1,)*(3-len(idim_orig)) + idim_orig\n offset = (numpy.array(vol.shape) - numpy.array(idim)) // 2\n vol = vol[offset[0]:offset[0]+idim[0], offset[1]:offset[1]+idim[1], offset[2]:offset[2]+idim[2]]\n \n # Make a copy of the template to ensure we do not overwrite it\n templ_im_out = templ_im.copy()\n \n # Fill image content \n templ_im_out.fill(numpy.reshape(vol, idim_orig))\n return(templ_im_out)", "_____no_output_____" ] ], [ [ "# Get brainweb data", "_____no_output_____" ], [ "We will download and use data from the brainweb. We will use a FDG image for PET and the PET uMAP for CT. MR usually provides qualitative images with an image contrast proportional to difference in T1, T2 or T2* depending on the sequence parameters. Nevertheless, we will make our life easy, by directly using the T1 map provided by the brainweb for MR.", "_____no_output_____" ] ], [ [ "fname, url= sorted(brainweb.utils.LINKS.items())[0]\nfiles = brainweb.get_file(fname, url, \".\")\ndata = brainweb.load_file(fname)\n\nbrainweb.seed(1337)", "_____no_output_____" ], [ "for f in tqdm([fname], desc=\"mMR ground truths\", unit=\"subject\"):\n vol = brainweb.get_mmr_fromfile(f, petNoise=1, t1Noise=0.75, t2Noise=0.75, petSigma=1, t1Sigma=1, t2Sigma=1)", "_____no_output_____" ], [ "FDG_arr = vol['PET']\nT1_arr = vol['T1']\nuMap_arr = vol['uMap']", "_____no_output_____" ], [ "# Display it\nplt.figure();\nslice_show = FDG_arr.shape[0]//2\nplot_2d_image([1,3,1], FDG_arr[slice_show, 100:-100, 100:-100], 'FDG', cmap=\"hot\")\nplot_2d_image([1,3,2], T1_arr[slice_show, 100:-100, 100:-100], 'T1', cmap=\"Greys_r\")\nplot_2d_image([1,3,3], uMap_arr[slice_show, 100:-100, 100:-100], 'uMap', cmap=\"bone\")", "_____no_output_____" ] ], [ [ "# Acquisition Models", "_____no_output_____" ], [ "In SIRF and CIL, an `AcquisitionModel` basically contains everything we need to know in order to describe what happens when we go from the imaged object to the acquired raw data (`AcquisitionData`) and then to the reconstructed image (`ImageData`). What we actually need to know depends strongly on the modality we are looking at. ", "_____no_output_____" ], [ "Here are some examples of modality specific information: \n\n * __PET__: scanner geometry, detector efficiency, attenuation, randoms/scatter background... \n * __CT__: scanner geometry \n * __MR__: k-space sampling pattern, coil sensitivity information,...", "_____no_output_____" ], [ "and then there is information which is independent of the modality such as field-of-view or image discretisation (e.g. voxel sizes).", "_____no_output_____" ], [ "For __PET__ and __MR__ a lot of this information is already in the raw data. Because it would be quite a lot of work to enter all the necessary information by hand and then checking it is consistent, we create `AcquisitionModel` objects from `AcquisitionData` objects. The `AcquisitionData` only serves as a template and both its actual image and raw data content can be (and in this exercise will be) replaced. For __CT__ we will create an acquisition model from scratch, i.e. we will define the scanner geometry, image dimensions and image voxels sizes and so by hand.", "_____no_output_____" ], [ "So let's get started with __MR__ .", "_____no_output_____" ], [ "## MR", "_____no_output_____" ], [ "For MR we basically need the following:\n\n 1. create an MR `AcquisitionData` object from a raw data file\n 2. calculate the coil sensitivity maps (csm, for more information on that please see the notebook `MR/c_coil_combination.ipynb`). \n 3. then we will carry out a simple image reconstruction to get a `ImageData` object which we can use as a template for our `AcquisitionModel`\n 4. then we will set up the MR `AcquisitionModel`", "_____no_output_____" ] ], [ [ "# 1. create MR AcquisitionData\nmr_acq = mr.AcquisitionData(os.path.join(examples_data_path('MR'),'grappa2_1rep.h5'))", "_____no_output_____" ], [ "# 2. calculate CSM\npreprocessed_data = mr.preprocess_acquisition_data(mr_acq)\n\ncsm = mr.CoilSensitivityData()\ncsm.smoothness = 50\ncsm.calculate(preprocessed_data)", "_____no_output_____" ], [ "# 3. calculate image template\nrecon = mr.FullySampledReconstructor()\nrecon.set_input(preprocessed_data)\nrecon.process()\nim_mr = recon.get_output()", "_____no_output_____" ], [ "# 4. create AcquisitionModel\nacq_mod_mr = mr.AcquisitionModel(preprocessed_data, im_mr)\n\n# Supply csm to the acquisition model \nacq_mod_mr.set_coil_sensitivity_maps(csm)", "_____no_output_____" ] ], [ [ "## PET", "_____no_output_____" ], [ "For PET we need to:\n\n 1. create a PET `AcquisitionData` object from a raw data file\n 2. create a PET `ImageData` object from the PET `AcquisitionData`\n 3. then we will set up the PET `AcquisitionModel`", "_____no_output_____" ] ], [ [ "# 1. create PET AcquisitionData\ntempl_sino = pet.AcquisitionData(os.path.join(examples_data_path('PET'),\"thorax_single_slice\",\"template_sinogram.hs\"))", "_____no_output_____" ], [ "# 2. create a template PET ImageData\nim_pet = pet.ImageData(templ_sino)", "_____no_output_____" ], [ "# 3. create AcquisitionModel\n\n# create PET acquisition model\nacq_mod_pet = pet.AcquisitionModelUsingRayTracingMatrix()\nacq_mod_pet.set_up(templ_sino, im_pet)", "_____no_output_____" ] ], [ [ "## CT", "_____no_output_____" ], [ "For CT we need to:\n\n 1. create a CT `AcquisitionGeometry` object\n 2. obtain CT `ImageGeometry` from `AcquisitionGeometry`\n 3. create a CT `ImageData` object\n 4. then we will set up the CT `AcquisitionModel`", "_____no_output_____" ] ], [ [ "# 1. define AcquisitionGeometry\nangles = numpy.linspace(0, 360, 50, True, dtype=numpy.float32)\nag2d = ct.AcquisitionGeometry.create_Cone2D((0,-1000), (0, 500))\\\n .set_panel(128,pixel_size=3.104)\\\n .set_angles(angles)", "_____no_output_____" ], [ "# 2. get ImageGeometry\nct_ig = ag2d.get_ImageGeometry()", "_____no_output_____" ], [ "# 3. create ImageData\nim_ct = ct_ig.allocate(None)", "_____no_output_____" ], [ "# 4. create AcquisitionModel\nacq_mod_ct = ap(ct_ig, ag2d, device='cpu')", "_____no_output_____" ] ], [ [ "# Apply acquisition models", "_____no_output_____" ], [ "## ImageData", "_____no_output_____" ], [ "In order to be able to apply our acquisition models in order to create raw data, we first need some image data. Because this image data has to fit to the `ImageData` and `AcquisitionData` objects of the different modalities, we will use them to create our image data. For more information on that please have a look at the notebook _introductory/introduction.ipynb_.", "_____no_output_____" ], [ "Let's create an `ImageData` object for each modality and display the slice in the centre of each data set:", "_____no_output_____" ] ], [ [ "# MR\nim_mr = crop_and_fill(im_mr, T1_arr)\n\n# PET\nim_pet = crop_and_fill(im_pet, FDG_arr)\n\n# CT\nim_ct = crop_and_fill(im_ct, uMap_arr)\n\nplt.figure();\nplot_2d_image([1,3,1], im_pet.as_array()[im_pet.dimensions()[0]//2, :, :], 'PET', cmap=\"hot\")\nplot_2d_image([1,3,2], numpy.abs(im_mr.as_array())[im_mr.dimensions()[0]//2, :, :], 'MR', cmap=\"Greys_r\")\nplot_2d_image([1,3,3], numpy.abs(im_ct.as_array()), 'CT', cmap=\"bone\")", "_____no_output_____" ] ], [ [ "## Forward and Backward", "_____no_output_____" ], [ "### Fun fact\nThe methods `forward` and `backward` for __MR__ and __PET__ describe to forward acquisition model (i.e. going from the object to the raw data) and backward acquisition model (i.e. going from the raw data to the object). For the __CT__ acquisition model we utilise functionality from __CIL__ . Here, these two operations are defined by `direct` (corresponding to `forward`) and `adjoint` (corresponding to `backward`). In order to make sure that the __MR__ and __PET__ acquisition models are fully compatible with all the __CIL__ functionality, both acquisition models also have the methods `direct` and `adjoint` which are simple aliases of `forward` and `backward`. ", "_____no_output_____" ], [ "Now back to our three acquisition models and let's create some raw data", "_____no_output_____" ] ], [ [ "# PET\nraw_pet = acq_mod_pet.forward(im_pet)\n\n# MR\nraw_mr = acq_mod_mr.forward(im_mr)\n\n# CT\nraw_ct = acq_mod_ct.direct(im_ct)", "_____no_output_____" ] ], [ [ "and we can apply the backward/adjoint operation to do a simply image reconstruction.", "_____no_output_____" ] ], [ [ "# PET\nbwd_pet = acq_mod_pet.backward(raw_pet)\n\n# MR\nbwd_mr = acq_mod_mr.backward(raw_mr)\n\n# CT\nbwd_ct = acq_mod_ct.adjoint(raw_ct)", "_____no_output_____" ], [ "plt.figure();\n# Raw data\nplot_2d_image([2,3,1], raw_pet.as_array()[0, raw_pet.dimensions()[1]//2, :, :], 'PET raw', cmap=\"viridis\")\nplot_2d_image([2,3,2], numpy.log(numpy.abs(raw_mr.as_array()[:, raw_mr.dimensions()[1]//2, :])), 'MR raw', cmap=\"viridis\")\nplot_2d_image([2,3,3], raw_ct.as_array(), 'CT raw', cmap=\"viridis\")\n\n# Rec data\nplot_2d_image([2,3,4], bwd_pet.as_array()[bwd_pet.dimensions()[0]//2, :, :], 'PET', cmap=\"magma\")\nplot_2d_image([2,3,5], numpy.abs(bwd_mr.as_array()[bwd_mr.dimensions()[0]//2, :, :]), 'MR', cmap=\"Greys_r\")\nplot_2d_image([2,3,6], bwd_ct.as_array(), 'CT', cmap=\"bone\")", "_____no_output_____" ] ], [ [ "These images don't look too great. This is due to many things, e.g. for MR the raw data is missing a lot of k-space information and hence we get undersampling artefacts.In general, the adjoint operation is not equal to the inverse operation. Therefore SIRF offers a range of more sophisticated image reconstruction techniques which strongly improve the image quality, but this is another notebook...", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
cb650541e122b87a2ec229e24d95bcd22f39aa1d
4,067
ipynb
Jupyter Notebook
example/MyEchoKernel-example.ipynb
rahul26goyal/jupyter-echo-kernel
d8ebb9ce7b9837387f013616f910870ca115371d
[ "Apache-2.0" ]
null
null
null
example/MyEchoKernel-example.ipynb
rahul26goyal/jupyter-echo-kernel
d8ebb9ce7b9837387f013616f910870ca115371d
[ "Apache-2.0" ]
null
null
null
example/MyEchoKernel-example.ipynb
rahul26goyal/jupyter-echo-kernel
d8ebb9ce7b9837387f013616f910870ca115371d
[ "Apache-2.0" ]
null
null
null
18.741935
132
0.486845
[ [ [ "\"Hello!!\"", "_____no_output_____" ], [ "\"Welcome to My Echo Kernel Project\"", "_____no_output_____" ], [ "\"What you type is what you get\"", "_____no_output_____" ], [ "\"This is an extension kernel on top in standar IPython, so you can still execute all the magic other than the python code.\"", "_____no_output_____" ], [ "%ls", "MyEchoKernel-example.ipynb\r\n" ], [ "%time \"hi\"", "CPU times: user 3 µs, sys: 0 ns, total: 3 µs\nWall time: 6.2 µs\n" ], [ "#%less ./MyEchoKernel-example.ipynb", "_____no_output_____" ], [ "\"Thanks for showing interest. If you have any query, feel free to message me on gitter: https://gitter.im/rahul26goyal\"", "_____no_output_____" ], [ "\"Have a good day!\"", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb651e2790ca45cf2b2cda1b4955bdc8cebf22b0
8,935
ipynb
Jupyter Notebook
notebooks/02-Train-Eval.ipynb
AmanDaVinci/meta-learning-few-shot-domain-adaptation
8224a00f65c6622a43961b645711cc444b8cdeb8
[ "MIT" ]
2
2021-01-02T23:58:16.000Z
2021-01-29T05:40:21.000Z
notebooks/02-Train-Eval.ipynb
AmanDaVinci/meta-learning-few-shot-domain-adaptation
8224a00f65c6622a43961b645711cc444b8cdeb8
[ "MIT" ]
null
null
null
notebooks/02-Train-Eval.ipynb
AmanDaVinci/meta-learning-few-shot-domain-adaptation
8224a00f65c6622a43961b645711cc444b8cdeb8
[ "MIT" ]
null
null
null
23.763298
129
0.498265
[ [ [ "# Train-Eval\n---", "_____no_output_____" ], [ "## Import Libraries", "_____no_output_____" ] ], [ [ "import os\nimport sys\nfrom pathlib import Path\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom torchtext.data import BucketIterator", "_____no_output_____" ], [ "sys.path.append(\"../\")\nfrom meta_infomax.datasets.fudan_reviews import prepare_data, get_data", "_____no_output_____" ] ], [ [ "## Global Constants", "_____no_output_____" ] ], [ [ "BSIZE = 16\nENCODER_DIM = 100\nCLASSIFIER_DIM = 100\nNUM_TASKS = 14\nEPOCHS = 1\nDATASETS = ['apparel', 'baby', 'books', 'camera_photo', 'electronics', \n 'health_personal_care', 'imdb', 'kitchen_housewares', 'magazines', \n 'music', 'software', 'sports_outdoors', 'toys_games', 'video']", "_____no_output_____" ] ], [ [ "# Load Data", "_____no_output_____" ] ], [ [ "from torchtext.vocab import GloVe", "_____no_output_____" ], [ "# prepare_data()\ntrain_set, dev_set, test_set, vocab = get_data()", "_____no_output_____" ], [ "train_iter, dev_iter, test_iter = BucketIterator.splits((train_set, dev_set, test_set),\n batch_sizes=(BSIZE, BSIZE*2, BSIZE*2),\n sort_within_batch=False,\n sort_key=lambda x: len(x.text))", "_____no_output_____" ], [ "batch = next(iter(train_iter))\nbatch", "_____no_output_____" ], [ "batch.text[0].shape, batch.label.shape, batch.task.shape", "_____no_output_____" ], [ "vocab.stoi[\"<pad>\"]", "_____no_output_____" ] ], [ [ "# Baseline Model", "_____no_output_____" ] ], [ [ "class Encoder(nn.Module):\n \n def __init__(self,emb_dim, hidden_dim, num_layers):\n super().__init__()\n self.lstm = nn.LSTM(emb_dim, hidden_dim, num_layers, batch_first=True, bidirectional=True)\n \n def forward(self, x):\n self.h0 = self.h0.to(x.device)\n self.c0 = self.c0.to(x.device)\n out, _ = self.lstm(x, (self.h0, self.c0))\n return out", "_____no_output_____" ], [ "class Classifier(nn.Module):\n \n def __init__(self, in_dim, hidden_dim, out_dim):\n super().__init__()\n self.layers = nn.Sequential(\n nn.Linear(in_dim, hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, out_dim)\n )\n \n def forward(self, x):\n return self.layers(x)", "_____no_output_____" ], [ "class MultiTaskInfoMax(nn.Module):\n \n def __init__(self, shared_encoder, embeddings, vocab, encoder_dim, encoder_layers, classifier_dim, out_dim):\n super().__init__()\n self.emb = nn.Embedding.from_pretrained(embeddings, freeze=True, padding_idx=vocab.stoi[\"<pad>\"])\n self.shared_encoder = shared_encoder\n self.private_encoder = Encoder(embeddings.shape[-1], encoder_dim, encoder_layers)\n self.classifier = Classifier(encoder_dim*4, classifier_dim, out_dim)\n \n def forward(self, sentences, lengths):\n sent_embed = self.emb(sentences)\n shared_out = self.shared_encoder(sent_embed)\n private_out = self.private_encoder(sent_embed)\n h = torch.cat((shared_out, private_out), dim=1)\n out = self.classifier(h)\n return out, shared_out, private_out ", "_____no_output_____" ] ], [ [ "# Train", "_____no_output_____" ], [ "## Overfit Batch", "_____no_output_____" ] ], [ [ "vocab.vectors.shape", "_____no_output_____" ], [ "shared_encoder = Encoder(vocab.vectors.shape[1], ENCODER_DIM, 1)\nshared_encoder", "_____no_output_____" ], [ "multitask_models = [MultiTaskInfoMax(shared_encoder=shared_encoder, embeddings=vocab.vectors, vocab=vocab, \n encoder_dim=ENCODER_DIM,encoder_layers=1, classifier_dim=CLASSIFIER_DIM, out_dim=2)\n for i in range(len(DATASETS))]", "_____no_output_____" ], [ "multitask_models[1]", "_____no_output_____" ], [ "multitask_models[batch]", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cb652060fd71c262d75558e4f25f35596c2ac274
13,879
ipynb
Jupyter Notebook
book/week_03/01-Intro-notebooks.ipynb
fmaussion/introduction_programming
1c5e7858712d61f23bafe5a14b7df97e8062dba9
[ "CC-BY-4.0" ]
1
2021-11-30T22:28:35.000Z
2021-11-30T22:28:35.000Z
book/week_03/01-Intro-notebooks.ipynb
fmaussion/intro_to_programming
9325c37cfa0c89b88a843e67795bdb09149b339a
[ "CC-BY-4.0" ]
null
null
null
book/week_03/01-Intro-notebooks.ipynb
fmaussion/intro_to_programming
9325c37cfa0c89b88a843e67795bdb09149b339a
[ "CC-BY-4.0" ]
null
null
null
33.85122
565
0.605879
[ [ [ "# Introduction to Jupyter Notebooks", "_____no_output_____" ], [ "Today we are going to learn about [Jupyter Notebooks](https://jupyter.org/)! The advantage of notebooks is that they can include explanatory text, code, and plots in the same document. **This makes notebooks an ideal playground for explaining and learning new things without having to jump between several documents.** You will use notebooks a LOT during your studies, and this is why I decided to teach you how they work very early in your programming journey.\n\nThis document itself is a notebook. It is a simple text file with a `.ipynb` file path ending. Notebooks are best opened in \"JupyterLab\", the development environment that you learned about last week.\n\n**Note: learning about notebooks is less urgent than learning how to write correct code. If you are feeling overwhelmed by coding, you should focus on the coding exercises for now and learn about notebooks a bit later. They will only become mandatory in about 2 to 3 weeks.**\n\nLet's start with a short video introduction, which will invite you to download this notebook to try it yourself:", "_____no_output_____" ] ], [ [ "from IPython.display import VimeoVideo\nVimeoVideo(691294249, width=900)", "_____no_output_____" ] ], [ [ "## First steps", "_____no_output_____" ], [ "Have you downloaded and opened the notebook as explained in the video? If not, do that first and continue this lesson on your own latpop.", "_____no_output_____" ], [ "At first sight the notebook looks like a text editor. Below this line, you can see a **cell**. The default purpose of a cell is to write code:", "_____no_output_____" ] ], [ [ "# Click on this cell, so that its frame gets highlighted\nm = 'Hello'\nprint(m)", "_____no_output_____" ] ], [ [ "You can write one or more lines of code in a cell. You can **run** this code by clicking on the \"Run\" button from the toolbar above when the cell's frame is highlighted. Try it now! \n\nClicking \"play\" through a notebook is possible, but it is much faster to use the keybord shortcut instead: `[Shift+Enter]`. Once you have executed a cell, the next cell is selected. You can **insert** cells in a notebook with the `+` button in the toolbar. Again, it is much faster to learn the keybord shortcut for this: `[Ctrl+m]` or `[ESC]` to enter in command mode (blue frame) then press `[a]` to insert a cell \"above\" the active cell or `[b]` for \"below\".\n\nCreate a few empty cells above and below the current one and try to create some variables. Instead of clicking on a cell to enter in edit mode press `[Enter]`.\n\nYou can **delete** a cell by clicking \"Delete\" in the \"Edit\" menu, or you can use the shortcut: `[Ctrl+m]` to enter in command mode then press `[d]` two times!", "_____no_output_____" ], [ "## More cell editing", "_____no_output_____" ], [ "When you have a look into the \"Edit\" menu, you will see that there are more possibilities to edit cells, like:\n- **copy** / **cut** and **paste**\n- **splitting** and **merging** cells \n\nand more.", "_____no_output_____" ] ], [ [ "a = 'This cell needs to be splitted.'\n\nb = 'Put the cursor in the row between the variables a and b, then choose [split cell] in the \"Edit\" menu!'", "_____no_output_____" ] ], [ [ "Another helpful command is \"Undo delete cell', which is sometimes needed when the key `[d]` was pressed too fast. ", "_____no_output_____" ], [ "## Writing and executing code", "_____no_output_____" ], [ "The variables created in one cell can be used (or overwritten) in subsequent cells:", "_____no_output_____" ] ], [ [ "s = 'Hello'\nprint(s)", "_____no_output_____" ], [ "s = s + ' Python!'\n# Lines which start with # are not executed. These are for comments.\ns", "_____no_output_____" ] ], [ [ "Note that we ommited the `print` commmand above (this is OK if you want to print something at the end of the cell only).", "_____no_output_____" ], [ "In jupyter notebooks, **code autocompletion** is supported. This is very useful when writing code. Variable names, functions and methods can be completed by pressing `[TAB]`.", "_____no_output_____" ] ], [ [ "# Let's define a random sentence as string.\nsentence = 'How Are You?'", "_____no_output_____" ], [ "# Now try autocompletion! Type 'se' in the next row and press [TAB].\n", "_____no_output_____" ] ], [ [ "An advantage of notebooks is that each single cell can be executed separately. That provides an easy way to execute code step by step, one cell after another. **It is important to notice that the order in which you execute the cells is the order with which the jupyter notebook calculates and saves variables - the execution order therefore depends on you, NOT on the order of the cells in the document**. That means that it makes a difference, whether you execute the cells top down one after another, or you mix them (cell 1, then cell 5, then cell 2 etc.).", "_____no_output_____" ], [ "The numbers on the left of each cell show you your order of execution. When a calculation is running longer, you will see an asterisk in the place of the number. That leads us to the next topic:", "_____no_output_____" ], [ "## Restart or interrupt the kernel", "_____no_output_____" ], [ "Sometimes calculations last too long and you want to **interrupt** them. You can do this by clicking the \"Stop button\" in the toolbar.\n\nThe \"**kernel**\" of a notebook is the actual python interpreter which runs your code. There is one kernel per opened notebook (i.e. the notebooks cannot share data or variables between each other). In certain situations (for example, if you got confused about the order of your cells and variables and want a fresh state), you might want to **retart the kernel**. You can do so (as well as other options such as **clearing the output** of a notebook) in the \"Kernel\" menu in the top jupyterlab bar.", "_____no_output_____" ], [ "## Errors in a cell ", "_____no_output_____" ], [ "Sometimes, a piece of code in a cell won't run properly. This happens to everyone! Here is an example:", "_____no_output_____" ] ], [ [ "# This will produce a \"NameError\"\ntest = 1 + 3\nprint(tesT)", "_____no_output_____" ] ], [ [ "When a cell ends with an error, don't panic! Nothing we cannot recover from. First of all, the other cells will still run (unless they depend on the output of the failing cell): i.e., your kernel is still active. If you want to recover from the error, adress the problem (here a capsize issue) and re-run the cell. ", "_____no_output_____" ], [ "## Formatting your notebook with text, titles and formulas", "_____no_output_____" ], [ "The default role of a cell is to run code, but you can tell the notebook to format a cell as \"text\" by clicking in the menu bar on \"Cell\", choose \"Cell Type\" $\\rightarrow$ \"Markdown\". The current cell will now be transformed to a normal text.\nAgain, there is a keyboard shortcut for this: press `[Ctrl+m]` to enter in command mode and then `[m]` to convert the active cell to text. The opposite (converting a text cell to code) can be done with `[Ctrl+m]` to enter in command mode and then `[y]`.\n\nAs we have seen, the notebook editor has two simple modes: the \"command mode\" to navigate between cells and activate them, and the \"edit mode\" to edit their content. To edit a cell you have two choices:\n- press `[enter]` on a selected (highlighted) cell \n- double click on a cell (any cell)\n\nNow, try to edit the cell below!", "_____no_output_____" ], [ "A text cell is formatted with the [Markdown](https://en.wikipedia.org/wiki/Markdown) format, e.g. it is possible to write lists:\n- item 1\n- item 2\n\nNumbered lists:\n1. part a\n2. part b\n\nTitles with the `#` syntax (the number of `#` indicating the level of the title:\n\n### This is a level 3 title (with 3 `#` symbols)\n\nMathematical formulas can be written down with the familiar Latex notation:\n\n$$ E = m c^2$$\n\nYou can also write text in **bold** or *cursive*.", "_____no_output_____" ], [ "## Download a notebook", "_____no_output_____" ], [ "Jupyter notebooks can be downloaded in various formats:\n\n- Standard notebook (`*.ipynb`): a text file only useful within the Jupyter framework\n- Python (`*.py`): a python script that can be executed separately. \n- HTML (`*.html`): an html text file that can be opened in any web browser (doens't require python or jupyter!) \n- ... and a number of other formats that may or may not work depending on your installation", "_____no_output_____" ], [ "**To download a jupyter notebook in the notebook format** (`.ipynb`), select the file on the left-hand side bar, right-click and select \"Download\". Try it now!\n\n**For all other formats**, go to the \"File\" menu, then \"Export notebook as...\"", "_____no_output_____" ], [ "## Take home points ", "_____no_output_____" ], [ "- jupyter notebooks consist of cells, which can be either code or text (not both)\n- one can navigate between cells in \"control mode\" (`[ctrl+m]`) and edit them in \"edit mode\" (`[enter]` or double click)\n- to exectute a cell, do: `[shift+enter]`\n- the order of execution of cells *does* matter\n- a text cell is written in markdown format, which allows lots of fancy formatting", "_____no_output_____" ], [ "These were the most important features of jupyter-notebook. In the notebook's menu bar the tab \"Help\" provides links to the documentation. Keyboard shortcuts are listed in the \"Palette\" icon on the left-hand side toolbar. Furthermore, there are more tutorials [on the Jupyter website](https://jupyter.org/try). \n\nBut with the few commands you learned today, you are already well prepared for the rest of the class!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cb65227f65874e2eb1a25af668ae493508f1a56a
50,031
ipynb
Jupyter Notebook
.ipynb_checkpoints/Navigation-checkpoint.ipynb
xsankar/p1_navigation
7ed7a5714e8d2506013e2fddd9fe4b378567d86f
[ "MIT" ]
1
2019-03-20T18:30:34.000Z
2019-03-20T18:30:34.000Z
.ipynb_checkpoints/Navigation-checkpoint.ipynb
xsankar/p1_navigation
7ed7a5714e8d2506013e2fddd9fe4b378567d86f
[ "MIT" ]
null
null
null
.ipynb_checkpoints/Navigation-checkpoint.ipynb
xsankar/p1_navigation
7ed7a5714e8d2506013e2fddd9fe4b378567d86f
[ "MIT" ]
1
2020-07-11T01:17:11.000Z
2020-07-11T01:17:11.000Z
66.442231
21,684
0.72535
[ [ [ "# Navigation\n\n---\n\nIn this notebook, you will learn how to use the Unity ML-Agents environment for the first project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893).\n\n### 1. Start the Environment\n\nWe begin by importing some necessary packages. If the code cell below returns an error, please revisit the project instructions to double-check that you have installed [Unity ML-Agents](https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Installation.md) and [NumPy](http://www.numpy.org/).", "_____no_output_____" ] ], [ [ "from unityagents import UnityEnvironment\nimport numpy as np", "_____no_output_____" ] ], [ [ "Next, we will start the environment! **_Before running the code cell below_**, change the `file_name` parameter to match the location of the Unity environment that you downloaded.\n\n- **Mac**: `\"path/to/Banana.app\"`\n- **Windows** (x86): `\"path/to/Banana_Windows_x86/Banana.exe\"`\n- **Windows** (x86_64): `\"path/to/Banana_Windows_x86_64/Banana.exe\"`\n- **Linux** (x86): `\"path/to/Banana_Linux/Banana.x86\"`\n- **Linux** (x86_64): `\"path/to/Banana_Linux/Banana.x86_64\"`\n- **Linux** (x86, headless): `\"path/to/Banana_Linux_NoVis/Banana.x86\"`\n- **Linux** (x86_64, headless): `\"path/to/Banana_Linux_NoVis/Banana.x86_64\"`\n\nFor instance, if you are using a Mac, then you downloaded `Banana.app`. If this file is in the same folder as the notebook, then the line below should appear as follows:\n```\nenv = UnityEnvironment(file_name=\"Banana.app\")\n```", "_____no_output_____" ] ], [ [ "env = UnityEnvironment(file_name=\"Banana.app\", no_graphics=True)", "INFO:unityagents:\n'Academy' started successfully!\nUnity Academy name: Academy\n Number of Brains: 1\n Number of External Brains : 1\n Lesson number : 0\n Reset Parameters :\n\t\t\nUnity brain name: BananaBrain\n Number of Visual Observations (per agent): 0\n Vector Observation space type: continuous\n Vector Observation space size (per agent): 37\n Number of stacked Vector Observation: 1\n Vector Action space type: discrete\n Vector Action space size (per agent): 4\n Vector Action descriptions: , , , \n" ] ], [ [ "### 1. Define imports\n\npython 3, numpy, matplotlib, torch", "_____no_output_____" ] ], [ [ "# General imports\nimport numpy as np\nimport random\nfrom collections import namedtuple, deque\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# torch imports\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim", "_____no_output_____" ], [ "# Constants Defin itions\nBUFFER_SIZE = int(1e5) # replay buffer size\nBATCH_SIZE = 64 # minibatch size\nGAMMA = 0.99 # discount factor\nTAU = 1e-3 # for soft update of target parameters\nLR = 5e-4 # learning rate \nUPDATE_EVERY = 4 # how often to update the network\n# Number of neurons in the layers of the q Network\nFC1_UNITS = 32 # 16 # 32 # 64\nFC2_UNITS = 16 # 8 # 16 # 64\nFC3_UNITS = 8 ", "_____no_output_____" ], [ "# Work area to quickly test utility functions\nimport time\nfrom datetime import datetime, timedelta\nstart_time = time.time()\ntime.sleep(10)\nprint('Elapsed : {}'.format(timedelta(seconds=time.time() - start_time)))", "Elapsed : 0:00:10.005479\n" ] ], [ [ "Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python.", "_____no_output_____" ] ], [ [ "from unityagents import UnityEnvironment\nenv = UnityEnvironment(file_name=\"Banana.app\", no_graphics=True)\n\n# get the default brain\nbrain_name = env.brain_names[0]\nbrain = env.brains[brain_name]", "INFO:unityagents:\n'Academy' started successfully!\nUnity Academy name: Academy\n Number of Brains: 1\n Number of External Brains : 1\n Lesson number : 0\n Reset Parameters :\n\t\t\nUnity brain name: BananaBrain\n Number of Visual Observations (per agent): 0\n Vector Observation space type: continuous\n Vector Observation space size (per agent): 37\n Number of stacked Vector Observation: 1\n Vector Action space type: discrete\n Vector Action space size (per agent): 4\n Vector Action descriptions: , , , \n" ] ], [ [ "### 2. Examine the State and Action Spaces\n\nThe simulation contains a single agent that navigates a large environment. At each time step, it has four actions at its disposal:\n- `0` - walk forward \n- `1` - walk backward\n- `2` - turn left\n- `3` - turn right\n\nThe state space has `37` dimensions and contains the agent's velocity, along with ray-based perception of objects around agent's forward direction. A reward of `+1` is provided for collecting a yellow banana, and a reward of `-1` is provided for collecting a blue banana. \n\nThe cell below tests to make sure the environment is up and running by printing some information about the environment.", "_____no_output_____" ] ], [ [ "# reset the environment for training agents via external python API\nenv_info = env.reset(train_mode=True)[brain_name]\n\n# number of agents in the environment\nprint('Number of agents:', len(env_info.agents))\n\n# number of actions\naction_size = brain.vector_action_space_size\nprint('Number of actions:', action_size)\n\n# examine the state space \nstate = env_info.vector_observations[0]\nprint('States look like:', state)\nstate_size = len(state)\nprint('States have length:', state_size)", "Number of agents: 1\nNumber of actions: 4\nStates look like: [1. 0. 0. 0. 0.84408134 0.\n 0. 1. 0. 0.0748472 0. 1.\n 0. 0. 0.25755 1. 0. 0.\n 0. 0.74177343 0. 1. 0. 0.\n 0.25854847 0. 0. 1. 0. 0.09355672\n 0. 1. 0. 0. 0.31969345 0.\n 0. ]\nStates have length: 37\n" ], [ "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")", "_____no_output_____" ], [ "class QNetwork(nn.Module):\n \"\"\"Actor (Policy) Model.\"\"\"\n\n def __init__(self, state_size, action_size, seed, fc1_units = FC1_UNITS, fc2_units = FC2_UNITS, fc3_units = FC3_UNITS):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n seed (int): Random seed\n \"\"\"\n super(QNetwork, self).__init__()\n self.seed = torch.manual_seed(seed)\n self.fc1 = nn.Linear(state_size,fc1_units)\n self.fc2 = nn.Linear(fc1_units,fc2_units)\n self.fc3 = nn.Linear(fc2_units,fc3_units)\n self.fc4 = nn.Linear(fc3_units,action_size)\n\n def forward(self, state):\n \"\"\"Build a network that maps state -> action values.\"\"\"\n x = F.relu(self.fc1(state))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n x = self.fc4(x)\n return x", "_____no_output_____" ], [ "class ReplayBuffer:\n \"\"\"Fixed-size buffer to store experience tuples.\"\"\"\n\n def __init__(self, action_size, buffer_size, batch_size, seed):\n \"\"\"Initialize a ReplayBuffer object.\n\n Params\n ======\n action_size (int): dimension of each action\n buffer_size (int): maximum size of buffer\n batch_size (int): size of each training batch\n seed (int): random seed\n \"\"\"\n self.action_size = action_size\n self.memory = deque(maxlen=buffer_size) \n self.batch_size = batch_size\n self.experience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n self.seed = random.seed(seed)\n \n def add(self, state, action, reward, next_state, done):\n \"\"\"Add a new experience to memory.\"\"\"\n e = self.experience(state, action, reward, next_state, done)\n self.memory.append(e)\n \n def sample(self):\n \"\"\"Randomly sample a batch of experiences from memory.\"\"\"\n experiences = random.sample(self.memory, k=self.batch_size)\n\n states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device)\n actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().to(device)\n rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device)\n next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(device)\n dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(device)\n \n return (states, actions, rewards, next_states, dones)\n\n def __len__(self):\n \"\"\"Return the current size of internal memory.\"\"\"\n return len(self.memory)", "_____no_output_____" ], [ "class Agent():\n \"\"\"Interacts with and learns from the environment.\"\"\"\n\n def __init__(self, state_size, action_size, seed):\n \"\"\"Initialize an Agent object.\n \n Params\n ======\n state_size (int): dimension of each state\n action_size (int): dimension of each action\n seed (int): random seed\n \"\"\"\n self.state_size = state_size\n self.action_size = action_size\n self.seed = random.seed(seed)\n\n # Q-Network\n self.qnetwork_local = QNetwork(state_size, action_size, seed).to(device)\n self.qnetwork_target = QNetwork(state_size, action_size, seed).to(device)\n self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR)\n\n # Replay memory\n self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed)\n # Initialize time step (for updating every UPDATE_EVERY steps)\n self.t_step = 0\n \n def step(self, state, action, reward, next_state, done):\n # Save experience in replay memory\n self.memory.add(state, action, reward, next_state, done)\n \n # Learn every UPDATE_EVERY time steps.\n self.t_step = (self.t_step + 1) % UPDATE_EVERY\n if self.t_step == 0:\n # If enough samples are available in memory, get random subset and learn\n if len(self.memory) > BATCH_SIZE:\n experiences = self.memory.sample()\n self.learn(experiences, GAMMA)\n\n def act(self, state, eps=0.):\n \"\"\"Returns actions for given state as per current policy.\n \n Params\n ======\n state (array_like): current state\n eps (float): epsilon, for epsilon-greedy action selection\n \"\"\"\n state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n self.qnetwork_local.eval()\n with torch.no_grad():\n action_values = self.qnetwork_local(state)\n self.qnetwork_local.train()\n\n # Epsilon-greedy action selection\n if random.random() > eps:\n return np.argmax(action_values.cpu().data.numpy())\n else:\n return random.choice(np.arange(self.action_size))\n\n def learn(self, experiences, gamma):\n \"\"\"Update value parameters using given batch of experience tuples.\n\n Params\n ======\n experiences (Tuple[torch.Variable]): tuple of (s, a, r, s', done) tuples \n gamma (float): discount factor\n \"\"\"\n states, actions, rewards, next_states, dones = experiences\n\n # compute and minimize the loss\n # Get max predicted Q values (for next states) from target model\n Q_targets_next = self.qnetwork_target(next_states).detach().max(1)[0].unsqueeze(1)\n # Compute Q targets for current states\n Q_targets = rewards + gamma * Q_targets_next * (1 - dones)\n \n # Get expected Q values from local model\n Q_expected = self.qnetwork_local(states).gather(1,actions)\n \n # Compute Loss\n loss = F.mse_loss(Q_expected,Q_targets)\n \n #Minimize Loss\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n # ------------------- update target network ------------------- #\n self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU) \n\n def soft_update(self, local_model, target_model, tau):\n \"\"\"Soft update model parameters.\n θ_target = τ*θ_local + (1 - τ)*θ_target\n\n Params\n ======\n local_model (PyTorch model): weights will be copied from\n target_model (PyTorch model): weights will be copied to\n tau (float): interpolation parameter \n \"\"\"\n for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):\n target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)", "_____no_output_____" ], [ "agent = Agent(state_size=state_size, action_size=action_size, seed=42)\nprint(agent.qnetwork_local)", "QNetwork(\n (fc1): Linear(in_features=37, out_features=32, bias=True)\n (fc2): Linear(in_features=32, out_features=16, bias=True)\n (fc3): Linear(in_features=16, out_features=8, bias=True)\n (fc4): Linear(in_features=8, out_features=4, bias=True)\n)\n" ], [ "def dqn(n_episodes=2000, max_t=1000, eps_start=1.0, eps_end=0.01, eps_decay=0.995):\n \"\"\"Deep Q-Learning.\n \n Params\n ======\n n_episodes (int): maximum number of training episodes\n max_t (int): maximum number of timesteps per episode\n eps_start (float): starting value of epsilon, for epsilon-greedy action selection\n eps_end (float): minimum value of epsilon\n eps_decay (float): multiplicative factor (per episode) for decreasing epsilon\n \"\"\"\n scores = [] # list containing scores from each episode\n scores_window = deque(maxlen=100) # last 100 scores\n eps = eps_start # initialize epsilon\n has_seen_13 = False\n max_score = 0\n for i_episode in range(1, n_episodes+1):\n env_info = env.reset(train_mode=True)[brain_name] # reset the environment\n state = env_info.vector_observations[0] # get the current state \n score = 0\n max_steps = 0\n for t in range(max_t):\n action = agent.act(state, eps)\n # next_state, reward, done, _ = env.step(action)\n env_info = env.step(action)[brain_name] # send the action to the environment\n next_state = env_info.vector_observations[0] # get the next state\n reward = env_info.rewards[0] # get the reward\n done = env_info.local_done[0] \n agent.step(state, action, reward, next_state, done)\n state = next_state\n score += reward\n max_steps += 1\n if done:\n break \n scores_window.append(score) # save most recent score\n scores.append(score) # save most recent score\n eps = max(eps_end, eps_decay*eps) # decrease epsilon\n print('\\rEpisode : {}\\tAverage Score : {:.2f}\\tMax_steps : {}'.format(i_episode, np.mean(scores_window),max_steps), end=\"\")\n if i_episode % 100 == 0:\n print('\\rEpisode : {}\\tAverage Score : {:.2f}\\tMax_steps : {}'.format(i_episode, np.mean(scores_window),max_steps))\n if (np.mean(scores_window)>=13.0) and (not has_seen_13):\n print('\\nEnvironment solved in {:d} episodes!\\tAverage Score: {:.2f}'.format(i_episode-100, np.mean(scores_window)))\n torch.save(agent.qnetwork_local.state_dict(), 'checkpoint.pth')\n has_seen_13 = True\n # break\n # To see how far it can go\n # Store the best model\n if np.mean(scores_window) > max_score:\n max_score = np.mean(scores_window)\n torch.save(agent.qnetwork_local.state_dict(), 'checkpoint.pth')\n return scores", "_____no_output_____" ], [ "start_time = time.time()\nscores = dqn() # The env ends at 300 steps. Tried max_t > 1K. Didn't see any complex adaptive temporal behavior\nenv.close() # Close the environment\nprint('Elapsed : {}'.format(timedelta(seconds=time.time() - start_time)))\n# plot the scores\nfig = plt.figure()\nax = fig.add_subplot(111)\nplt.plot(np.arange(len(scores)), scores)\nplt.ylabel('Score')\nplt.xlabel('Episode #')\nplt.show()\nagent.qnetwork_local\nprint('Max Score {:2f} at {}'.format(np.max(scores), np.argmax(scores)))\nprint('Percentile [25,50,75] : {}'.format(np.percentile(scores,[25,50,75])))\nprint('Variance : {:.3f}'.format(np.var(scores)))", "Episode : 100\tAverage Score : 0.18\tMax_steps : 300\nEpisode : 200\tAverage Score : 3.68\tMax_steps : 300\nEpisode : 300\tAverage Score : 6.40\tMax_steps : 300\nEpisode : 400\tAverage Score : 9.81\tMax_steps : 300\nEpisode : 500\tAverage Score : 12.93\tMax_steps : 300\nEpisode : 505\tAverage Score : 13.03\tMax_steps : 300\nEnvironment solved in 405 episodes!\tAverage Score: 13.03\nEpisode : 600\tAverage Score : 14.23\tMax_steps : 300\nEpisode : 700\tAverage Score : 15.36\tMax_steps : 300\nEpisode : 800\tAverage Score : 15.66\tMax_steps : 300\nEpisode : 900\tAverage Score : 15.64\tMax_steps : 300\nEpisode : 1000\tAverage Score : 15.10\tMax_steps : 300\nEpisode : 1100\tAverage Score : 15.10\tMax_steps : 300\nEpisode : 1200\tAverage Score : 16.09\tMax_steps : 300\nEpisode : 1300\tAverage Score : 16.22\tMax_steps : 300\nEpisode : 1400\tAverage Score : 16.30\tMax_steps : 300\nEpisode : 1500\tAverage Score : 17.05\tMax_steps : 300\nEpisode : 1600\tAverage Score : 16.54\tMax_steps : 300\nEpisode : 1700\tAverage Score : 16.69\tMax_steps : 300\nEpisode : 1800\tAverage Score : 16.16\tMax_steps : 300\nEpisode : 1900\tAverage Score : 16.48\tMax_steps : 300\nEpisode : 2000\tAverage Score : 15.99\tMax_steps : 300\nElapsed : 1:24:07.507518\nMax Score 28.000000 at 1201\n" ], [ "# Run Logs\n'''\nMax = 2000 episodes, \nGAMMA = 0.99 # discount factor\nTAU = 1e-3 # for soft update of target parameters\nLR = 5e-4 # learning rate \nUPDATE_EVERY = 4 # how often to update the network\n\nfc1:64-fc2:64-fc3:4 -> 510 episodes/13.04, Max 26 @ 1183 episodes, Runnimg 100 mean 16.25 @1200, @1800 \n Elapsed : 1:19:28.997291\n\nfc1:32-fc2:16-fc3:4 -> 449 episodes/13.01, Max 28 @ 1991 episodes, Runnimg 100 mean 16.41 @1300, 16.66 @1600, 17.65 @2000 \n Elapsed : 1:20:27.390989\n Less Variance ? Overall learns better & steady; keeps high scores onc it learned them - match impedence\n percentile[25,50,75] = [11. 15. 18.]; var = 30.469993749999997\n\nfc1:16-fc2:8-fc3:4 -> 502 episodes/13.01, Max 28 @ 1568 episodes, Runnimg 100 mean 16.41 @1400, 16.23 @1500, 16.32 @1600 \n Elapsed : 1:18:33.396898\n percentile[25,50,75] = [10. 14. 17.]; var = 30.15840975\n Very calm CPU ! Embed in TX2 or raspberry Pi environment - definitely this network\n Doesn't reach the highs of a larger network\n\nfc1:32-fc2:16-fc3:8-fc4:4 -> 405 episodes/13.03, Max 28 @ 1281 episodes, Runnimg 100 mean 17.05 @1500, 16.69 @1700 \n Elapsed : 1:24:07.507518\n percentile[25,50,75] = [11. 15. 18.]; var = 34.83351975\n Back to heavy CPU usage. Reaches solution faster, so definitely more fidelity. Depth gives early advantage\n\nfc1:64-fc2:32-fc3:16-fc4:8-fc5:4 -> 510 episodes, max score : 15.50 @ 700 episodes\n Monstrous atrocity !\n\nfc1:32-fc2:4-> 510 episodes, max score : 15.50 @ 700 episodes\n Minimalist\n'''", "_____no_output_____" ], [ "print(np.percentile(scores,[25,50,75]))\nprint(np.var(scores))", "[11. 15. 18.]\n34.83351975\n" ], [ "print(agent.qnetwork_local)", "QNetwork(\n (fc1): Linear(in_features=37, out_features=32, bias=True)\n (fc2): Linear(in_features=32, out_features=16, bias=True)\n (fc3): Linear(in_features=16, out_features=8, bias=True)\n (fc4): Linear(in_features=8, out_features=4, bias=True)\n)\n" ], [ "print('Max Score {:2f} at {}'.format(np.max(scores), np.argmax(scores)))\nlen(scores)\nnp.median(scores)", "Max Score 26.000000 at 1183\n" ], [ "# Run best model", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb65244fc0b65ba024c1c83af562259ec524e78d
203,677
ipynb
Jupyter Notebook
Early versions/Main_Phase_1.ipynb
luqmanbuang/Capstone
0a4fbfad6632fcd6d824d0fde690e28726dd3034
[ "MIT" ]
2
2021-11-21T07:49:37.000Z
2022-02-27T06:38:41.000Z
Early versions/Main_Phase_1.ipynb
luqmanbuang/Capstone
0a4fbfad6632fcd6d824d0fde690e28726dd3034
[ "MIT" ]
null
null
null
Early versions/Main_Phase_1.ipynb
luqmanbuang/Capstone
0a4fbfad6632fcd6d824d0fde690e28726dd3034
[ "MIT" ]
2
2021-08-03T13:39:06.000Z
2021-08-13T06:55:41.000Z
115.791359
110,494
0.743182
[ [ [ "import matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\ndf = pd.read_csv('train_FD001.txt', sep=' ', header=None)\n\n# dropping NAN values\ndf = df.dropna(axis=1, how='all')\n\n# Naming the columns\ndf.columns = [\"unit\", \"cycles\", \"Op1\",\n \"Op2\", \"Op3\", \"S1\", \"S2\",\n \"S3\", \"S4\", \"S5\", \"S6\", \"S7\", \"S8\", \"S9\", \"S10\", \"S11\",\n \"S12\", \"S13\", \"S14\", \"S15\", \"S16\", \"S17\", \"S18\", \"S19\", \"S20\", \"S21\"]\n# # show dataframe\n# df.head()\n\n", "_____no_output_____" ], [ "# data preprocessing; removing unnecessary data\ndf.drop(['Op3','S1', 'S5', 'S6', 'S16', 'S10', 'S18', 'S19'], axis=1, inplace=True)\ndf.head()\n\n\n# MinMaxScaler\nscaler = MinMaxScaler()\ndf.iloc[:,2:18] = scaler.fit_transform(df.iloc[:,2:18])", "_____no_output_____" ], [ "# finding the max cycles of a unit which is used to find the Time to Failure (TTF)\n\ndf = pd.merge(df, df.groupby('unit', as_index=False)['cycles'].max(), how='left', on='unit')\ndf.rename(columns={\"cycles_x\": \"cycles\", \"cycles_y\": \"maxcycles\"}, inplace=True)\n\ndf['TTF'] = df['maxcycles'] - df['cycles']\n\n# defining Fraction of Time to Failure (fTTF), where value of 1 denotes healthy engine and 0 denotes failure\ndef fractionTTF(dat,q):\n return(dat.TTF[q]-dat.TTF.min()) / (dat.TTF.max()-dat.TTF.min())\n\nfTTFz = []\nfTTF = []\n\nfor i in range(df['unit'].min(),df['unit'].max()+1):\n dat=df[df.unit==i]\n dat = dat.reset_index(drop=True)\n for q in range(len(dat)):\n fTTFz = fractionTTF(dat, q)\n fTTF.append(fTTFz)\n\ndf['fTTF'] = fTTF\ndf", "_____no_output_____" ], [ "cycles = df.groupby('unit', as_index=False)['cycles'].max()\nmx = cycles.iloc[0:4,1].sum()\n\nplt.plot(df.fTTF[0:mx])\nplt.legend(['Time to failure (fraction)'], bbox_to_anchor=(0., 1.02, 1., .102), loc=3, mode=\"expand\", borderaxespad=0)\nplt.ylabel('Scaled unit')\nplt.show()", "_____no_output_____" ], [ "# splitting train and test data, test size 20%\n\n# train set\ndf_train = df[(df.unit <= 80)]\nX_train = df_train[['cycles', 'Op1', 'Op2', 'S2', 'S3', 'S4', 'S7', 'S8', 'S9', 'S11', 'S12',\n 'S13', 'S14', 'S15', 'S17', 'S20', 'S21']].values\ny_train = df_train[['fTTF']].values.ravel()\n\n# test set\ndf_test = df[(df.unit > 80)]\nX_test = df_test[['cycles', 'Op1', 'Op2', 'S2', 'S3', 'S4', 'S7', 'S8', 'S9', 'S11', 'S12',\n 'S13', 'S14', 'S15', 'S17', 'S20', 'S21']].values\ny_test = df_test[['fTTF']].values.ravel()", "_____no_output_____" ], [ "from keras.models import Sequential\nfrom keras.layers.core import Dense, Activation\nfrom keras.wrappers.scikit_learn import KerasRegressor", "_____no_output_____" ], [ "model = Sequential()\nmodel.add(Dense(50, input_dim=17, kernel_initializer='normal', activation='relu'))\nmodel.add(Dense(1, kernel_initializer='normal'))\nmodel.compile(loss='mean_squared_error', optimizer='adam')\n\nmodel.fit(X_train, y_train, epochs = 50)", "Epoch 1/50\n505/505 [==============================] - 1s 1ms/step - loss: 0.0453\nEpoch 2/50\n505/505 [==============================] - 1s 1ms/step - loss: 0.0058\nEpoch 3/50\n505/505 [==============================] - 1s 1ms/step - loss: 0.0051\nEpoch 4/50\n505/505 [==============================] - 1s 1ms/step - loss: 0.0049\nEpoch 5/50\n505/505 [==============================] - 0s 976us/step - loss: 0.0049\nEpoch 6/50\n505/505 [==============================] - 0s 924us/step - loss: 0.0046\nEpoch 7/50\n505/505 [==============================] - 0s 934us/step - loss: 0.0046\nEpoch 8/50\n505/505 [==============================] - 0s 926us/step - loss: 0.0045\nEpoch 9/50\n505/505 [==============================] - 0s 920us/step - loss: 0.0045\nEpoch 10/50\n505/505 [==============================] - 0s 956us/step - loss: 0.0045\nEpoch 11/50\n505/505 [==============================] - 0s 908us/step - loss: 0.0044\nEpoch 12/50\n505/505 [==============================] - 0s 931us/step - loss: 0.0043\nEpoch 13/50\n505/505 [==============================] - 0s 915us/step - loss: 0.0043\nEpoch 14/50\n505/505 [==============================] - 0s 949us/step - loss: 0.0042\nEpoch 15/50\n505/505 [==============================] - 0s 928us/step - loss: 0.0042\nEpoch 16/50\n505/505 [==============================] - 0s 926us/step - loss: 0.0042\nEpoch 17/50\n505/505 [==============================] - 0s 922us/step - loss: 0.0040\nEpoch 18/50\n505/505 [==============================] - 0s 895us/step - loss: 0.0041\nEpoch 19/50\n505/505 [==============================] - 0s 912us/step - loss: 0.0040\nEpoch 20/50\n505/505 [==============================] - 0s 933us/step - loss: 0.0039\nEpoch 21/50\n505/505 [==============================] - 0s 935us/step - loss: 0.0039\nEpoch 22/50\n505/505 [==============================] - 0s 945us/step - loss: 0.0039\nEpoch 23/50\n505/505 [==============================] - 0s 894us/step - loss: 0.0038\nEpoch 24/50\n505/505 [==============================] - 0s 930us/step - loss: 0.0039\nEpoch 25/50\n505/505 [==============================] - 0s 939us/step - loss: 0.0038\nEpoch 26/50\n505/505 [==============================] - 0s 893us/step - loss: 0.0038\nEpoch 27/50\n505/505 [==============================] - 0s 975us/step - loss: 0.0038\nEpoch 28/50\n505/505 [==============================] - 0s 943us/step - loss: 0.0038\nEpoch 29/50\n505/505 [==============================] - 0s 942us/step - loss: 0.0038\nEpoch 30/50\n505/505 [==============================] - 0s 916us/step - loss: 0.0037\nEpoch 31/50\n505/505 [==============================] - 0s 938us/step - loss: 0.0037\nEpoch 32/50\n505/505 [==============================] - 0s 913us/step - loss: 0.0037\nEpoch 33/50\n505/505 [==============================] - 0s 938us/step - loss: 0.0037\nEpoch 34/50\n505/505 [==============================] - 0s 939us/step - loss: 0.0036\nEpoch 35/50\n505/505 [==============================] - 0s 953us/step - loss: 0.0037\nEpoch 36/50\n505/505 [==============================] - 0s 941us/step - loss: 0.0037\nEpoch 37/50\n505/505 [==============================] - 0s 931us/step - loss: 0.0038\nEpoch 38/50\n505/505 [==============================] - 0s 930us/step - loss: 0.0037\nEpoch 39/50\n505/505 [==============================] - 0s 922us/step - loss: 0.0037\nEpoch 40/50\n505/505 [==============================] - 0s 940us/step - loss: 0.0037\nEpoch 41/50\n505/505 [==============================] - 0s 926us/step - loss: 0.0037\nEpoch 42/50\n505/505 [==============================] - 0s 956us/step - loss: 0.0037\nEpoch 43/50\n505/505 [==============================] - 0s 914us/step - loss: 0.0036\nEpoch 44/50\n505/505 [==============================] - 0s 940us/step - loss: 0.0037\nEpoch 45/50\n505/505 [==============================] - 0s 904us/step - loss: 0.0037\nEpoch 46/50\n505/505 [==============================] - 0s 947us/step - loss: 0.0037\nEpoch 47/50\n505/505 [==============================] - 0s 921us/step - loss: 0.0037\nEpoch 48/50\n505/505 [==============================] - 0s 926us/step - loss: 0.0036\nEpoch 49/50\n505/505 [==============================] - 0s 951us/step - loss: 0.0035\nEpoch 50/50\n505/505 [==============================] - 0s 940us/step - loss: 0.0036\n" ], [ "score = model.predict(X_test) \ndf_test['predicted'] = score\n\nplt.figure(figsize = (16, 8)) \nplt.plot(df_test.fTTF) \nplt.plot(df_test.predicted)", "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \n" ], [ "# RMSE\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom math import sqrt\n\nnn_rmse = sqrt(mean_squared_error(y_test, score))\nprint(\"RMSE: \", nn_rmse)\n\n# r2 score\nnn_r2 = r2_score(y_test, score)\nprint(\"r2 score: \", nn_r2)\n\ndf_test", "RMSE: 0.07731335753561264\nr2 score: 0.9289076835747075\n" ], [ "def totcycles(data):\n return(data['cycles'] / (1-data['predicted']))\n \ndf_test['maxpredcycles'] = totcycles(df_test)\n\ndf_test", "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:4: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n after removing the cwd from sys.path.\n" ], [ "from google.colab import drive\ndrive.mount('/drive')\ndf_test.to_csv('/drive/My Drive/test_dataframe.csv') # export dataframe to google drive as as csv file to analyse the findings", "Mounted at /drive\n" ], [ "# upon observation it is noticed that the prediction gets more accurate the further the cycle is in the time series\n\n# df_test.groupby('unit', as_index=False)['maxpredcycles'].quantile(.10) // pd.groupby().quantile() to get the quantile result\n# df_test.groupby('unit', as_index=False)['cycles'].max()\n\ndff = pd.merge(df_test.groupby('unit', as_index=False)['maxpredcycles'].quantile(.72), df.groupby('unit', as_index=False)['maxcycles'].max(), how='left', on='unit')\ndff # display the preliminary results for obervation\n", "_____no_output_____" ], [ "MAXPRED = dff.maxpredcycles\nMAXI = dff.maxcycles \n\ndff_rmse = sqrt(mean_squared_error(MAXPRED, MAXI))\nprint(\"RMSE: \", dff_rmse)\n", "RMSE: 21.84978831316669\n" ], [ "", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb65272f960c40d7bfcbb1198de1c13cba407913
37,613
ipynb
Jupyter Notebook
ML-Disatater-Pipeline.ipynb
ohoudrehbini/disaster-pipeline
d88445d0a29a6df7b3c3d5f604e0b3eeb84cf25b
[ "FTL", "blessing" ]
null
null
null
ML-Disatater-Pipeline.ipynb
ohoudrehbini/disaster-pipeline
d88445d0a29a6df7b3c3d5f604e0b3eeb84cf25b
[ "FTL", "blessing" ]
null
null
null
ML-Disatater-Pipeline.ipynb
ohoudrehbini/disaster-pipeline
d88445d0a29a6df7b3c3d5f604e0b3eeb84cf25b
[ "FTL", "blessing" ]
null
null
null
39.760042
337
0.426794
[ [ [ "# ML Pipeline Preparation\nFollow the instructions below to help you create your ML pipeline.\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_____" ] ], [ [ "# import libraries\nimport pandas as pd\nimport numpy as np\nfrom sqlalchemy import create_engine\nfrom nltk.tokenize import word_tokenize , RegexpTokenizer\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.decomposition import TruncatedSVD\nimport pickle\nimport sqlite3\nimport nltk\nimport re \nimport string\nfrom sklearn.metrics import precision_recall_fscore_support\n%matplotlib inline\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "from nltk.corpus import wordnet as wn", "_____no_output_____" ], [ "import nltk\nnltk.download('wordnet')", "[nltk_data] Downloading package wordnet to\n[nltk_data] /Users/discoveryscientist/nltk_data...\n[nltk_data] Package wordnet is already up-to-date!\n" ], [ "nltk.download('punkt')\nnltk.download('wordent')\nnltk.download('stopwords')", "[nltk_data] Downloading package punkt to\n[nltk_data] /Users/discoveryscientist/nltk_data...\n[nltk_data] Package punkt is already up-to-date!\n[nltk_data] Error loading wordent: Package 'wordent' not found in\n[nltk_data] index\n[nltk_data] Downloading package stopwords to\n[nltk_data] /Users/discoveryscientist/nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n" ], [ "# load data from database\nengine = create_engine('sqlite:///InsertDatabaseName.db')", "_____no_output_____" ], [ "df = pd.read_sql_table('InsertTableName', engine)", "_____no_output_____" ], [ "X = df.filter(items=['id', 'message', 'original', 'genre'])\ny = df.drop(['id', 'message', 'original', 'genre', 'child_alone'], axis=1)#'child_alone' has no responses\n\ny['related']=y['related'].map(lambda x: 1 if x == 2 else x)\ndf.head()", "_____no_output_____" ] ], [ [ "### 2. Write a tokenization function to process your text data", "_____no_output_____" ] ], [ [ "from nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem.porter import PorterStemmer", "_____no_output_____" ], [ "def tokenize(text):\n tokens = nltk.word_tokenize(text)\n lemmatizer = nltk.WordNetLemmatizer()\n return [lemmatizer.lemmatize(w).lower().strip() for w in tokens]", "_____no_output_____" ], [ "#stop_words = nltk.corpus.stopwords.words(\"english\")\n#lemmatizer = nltk.stem.wordnet.WordNetLemmatizer()\n#remove_punc_table = str.maketrans('', '', string.punctuation)", "_____no_output_____" ] ], [ [ "### 3. Build a 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. You may find the [MultiOutputClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.multioutput.MultiOutputClassifier.html) helpful for predicting multiple target variables.", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom sklearn.pipeline import Pipeline", "_____no_output_____" ], [ "pipeline = Pipeline([('cvect', CountVectorizer(tokenizer = tokenize)),\n ('tfidf', TfidfTransformer()),\n ('clf', RandomForestClassifier())\n ])", "_____no_output_____" ] ], [ [ "### 4. Train pipeline\n- Split data into train and test sets\n- Train pipeline", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "X_train, X_test, y_train, y_test = train_test_split(X, y)\npipeline.fit(X_train['message'], y_train)", "/anaconda3/lib/python3.7/site-packages/sklearn/ensemble/forest.py:246: 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" ] ], [ [ "### 5. Test your 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_____" ] ], [ [ "from sklearn.metrics import classification_report", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, make_scorer\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.svm import SVC", "_____no_output_____" ], [ "y_pred_test = pipeline.predict(X_test['message'])\ny_pred_train = pipeline.predict(X_train['message'])\nprint(classification_report(y_test.values, y_pred_test, target_names=y.columns.values))\nprint('-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-')\nprint('\\n',classification_report(y_train.values, y_pred_train, target_names=y.columns.values))", "/anaconda3/lib/python3.7/site-packages/sklearn/metrics/classification.py:1143: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples.\n 'precision', 'predicted', average, warn_for)\n/anaconda3/lib/python3.7/site-packages/sklearn/metrics/classification.py:1143: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in samples with no predicted labels.\n 'precision', 'predicted', average, warn_for)\n/anaconda3/lib/python3.7/site-packages/sklearn/metrics/classification.py:1145: UndefinedMetricWarning: Recall and F-score are ill-defined and being set to 0.0 in samples with no true labels.\n 'recall', 'true', average, warn_for)\n" ], [ "parameters = {'clf__max_depth': [10, 20, None],\n 'clf__min_samples_leaf': [1, 2, 4],\n 'clf__min_samples_split': [2, 5, 10],\n 'clf__n_estimators': [10, 20, 40]}\n\ncv = GridSearchCV(pipeline, param_grid=parameters, scoring='f1_micro', verbose=1, n_jobs=-1)\ncv.fit(X_train['message'], y_train)", "/anaconda3/lib/python3.7/site-packages/sklearn/model_selection/_split.py:2053: 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" ] ], [ [ "### 7. Test your model\nShow the accuracy, precision, and recall of the tuned model. \n\nSince this project focuses on code quality, process, and pipelines, there is no minimum performance metric needed to pass. However, make sure to fine tune your models for accuracy, precision and recall to make your project stand out - especially for your portfolio!", "_____no_output_____" ] ], [ [ "y_pred_test = cv.predict(X_test['message'])\ny_pred_train = cv.predict(X_train['message'])\nprint(classification_report(y_test.values, y_pred_test, target_names=y.columns.values))\nprint('-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-\\|/-')\nprint('\\n',classification_report(y_train.values, y_pred_train, target_names=y.columns.values))", "/anaconda3/lib/python3.7/site-packages/sklearn/metrics/classification.py:1143: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples.\n 'precision', 'predicted', average, warn_for)\n/anaconda3/lib/python3.7/site-packages/sklearn/metrics/classification.py:1143: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in samples with no predicted labels.\n 'precision', 'predicted', average, warn_for)\n/anaconda3/lib/python3.7/site-packages/sklearn/metrics/classification.py:1145: UndefinedMetricWarning: Recall and F-score are ill-defined and being set to 0.0 in samples with no true labels.\n 'recall', 'true', average, warn_for)\n" ] ], [ [ "### 8. Try improving your model further. Here are a few ideas:\n* try other machine learning algorithms\n* add other features besides the TF-IDF", "_____no_output_____" ] ], [ [ "cv.best_params_", "_____no_output_____" ] ], [ [ "### 9. Export your model as a pickle file", "_____no_output_____" ] ], [ [ "m = pickle.dumps('clf')", "_____no_output_____" ], [ "with open('disaster_model.pkl', 'wb') as f:\n pickle.dump(cv, f)", "_____no_output_____" ] ], [ [ "### 10. Use this notebook to complete `train.py`\nUse the template file attached in the Resources folder to write a 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" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
cb65387633d2d72a6f7827ea2d48f78b4a2e32da
2,580
ipynb
Jupyter Notebook
docs/notebooks/pipelines/manual_segmentation.ipynb
alishakodibagkar/brainlit
2dc12eac3ea71412a36ecace3bab2deebd2ef29c
[ "Apache-2.0" ]
null
null
null
docs/notebooks/pipelines/manual_segmentation.ipynb
alishakodibagkar/brainlit
2dc12eac3ea71412a36ecace3bab2deebd2ef29c
[ "Apache-2.0" ]
6
2020-01-31T22:21:10.000Z
2020-01-31T22:24:59.000Z
docs/notebooks/pipelines/manual_segmentation.ipynb
alishakodibagkar/brainlit
2dc12eac3ea71412a36ecace3bab2deebd2ef29c
[ "Apache-2.0" ]
null
null
null
26.060606
219
0.592248
[ [ [ "# Napari Manual Segmentation Tutorial", "_____no_output_____" ], [ "This notebook demonstrates how to use Napari to manually edit a segmentation. To learn about generating an automatic segmentation and uploading segmentations to the cloud, refer to the segmentation pipeline demo. ", "_____no_output_____" ], [ "## Ensure Napari is in 2D-slice viewing", "_____no_output_____" ], [ "### 1. Ensure Napari is in 2D-slice viewing, not 3D view (The second button from the bottom left).\n![2D view](assets/2d_view.png \"2D View\")", "_____no_output_____" ], [ "### 2. Click the image layer and adjust the opacity, contrast limits, and gamma as desired.\n![Before adjustment](assets/contrast_1.png \"Before adjustment\")\n![After adjustment](assets/contrast_2.png \"After adjustment\")", "_____no_output_____" ], [ "### 3. Click on the layer for your existing automatic segmentation mask.\n![Segmentation Layer](assets/labels_1.png \"Segmentation Layer\")\n\nAlternatively, create a new layer for the segmentation mask.\n\n![New Labels Layer](assets/new_labels.png \"New Labels Layer\")", "_____no_output_____" ], [ "### 4. Click the paintbrush tool and adjust the brush size. Ensure that \"label\" is set to 1 to paint and 0 to erase.\n![Paintbrush Tool](assets/paintbrush.png \"Paintbrush Tool\")", "_____no_output_____" ], [ "### 5. Click and drag on the image to adjust labels. Changes are saved automatically, and CMD-Z to undo is supported.\n![Painted Labels](assets/painting.png \"Painted Labels\")", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cb65408923f5177bb40f6451f79ac9cffca8738b
298,903
ipynb
Jupyter Notebook
Practical Examples/7 - DataAugumentation and aspect ratio/animals_data_augmentation.ipynb
IgorMeloS/Computer-Vision-Training
cc458d17ee0ff880ce6ccc47179d667bd55f4bd1
[ "Apache-2.0" ]
null
null
null
Practical Examples/7 - DataAugumentation and aspect ratio/animals_data_augmentation.ipynb
IgorMeloS/Computer-Vision-Training
cc458d17ee0ff880ce6ccc47179d667bd55f4bd1
[ "Apache-2.0" ]
null
null
null
Practical Examples/7 - DataAugumentation and aspect ratio/animals_data_augmentation.ipynb
IgorMeloS/Computer-Vision-Training
cc458d17ee0ff880ce6ccc47179d667bd55f4bd1
[ "Apache-2.0" ]
null
null
null
307.830072
128,224
0.888312
[ [ [ "# Data Augumentation on Animals dataset using MiniVGG net\n\nIn this example, We explore the Data Augmentation. This method of regularization can aid us to improve our results during the training process. In addition, we consider the Aspect Ratio when resizing the images. Maintaining the aspect ratio help the CNN to extract considerable features from each image, unlike the simple resizing that distort the images, causing the loss of information contained on the images.\n\nWe perform two experiments. The fist, we just consider the resizing process maintaining the aspect ratio. For the second experiment, we consider the Data Augmentation and the aspect ration for the resizing. For the both models, We consider the Learning Rate Scheduler, defining a piecewise function.", "_____no_output_____" ], [ "## Importing libraries", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nimport tensorflow as tf\n#compvis modeule\nfrom compvis.preprocessing import ImageToArrayPreprocessor\nfrom compvis.preprocessing import ResizeAR\nfrom compvis.datasets import SimpleDatasetLoader\nfrom compvis.ann.cnns import MiniVGG\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import LearningRateScheduler\nfrom imutils import paths\nimport matplotlib.pyplot as plt\nimport numpy as np", "_____no_output_____" ] ], [ [ "## Loading and preprocessing the dataset", "_____no_output_____" ] ], [ [ "dataset = \"/home/igor/Documents/Artificial_Inteligence/Datasets/Animals\" #path\nimagePaths = list(paths.list_images(dataset)) # list of all images", "_____no_output_____" ], [ "ar = ResizeAR(32, 32) # simple image preprocessor\niap = ImageToArrayPreprocessor() # to convert image into arraey\nsdl = SimpleDatasetLoader(preprocessors=[ar, iap]) # to load images from disk and process them\n(data, labels) = sdl.load(imagePaths, verbose = 500) # return images and labels\ndata = data.astype(\"float\") / 255. # Normalize into 0 and 1", "[INFO] processed 500/3000\n[INFO] processed 1000/3000\n[INFO] processed 1500/3000\n[INFO] processed 2000/3000\n[INFO] processed 2500/3000\n[INFO] processed 3000/3000\n" ] ], [ [ "### Splitting the dataset into train and test set", "_____no_output_____" ] ], [ [ "(X_train, X_test, y_train, y_test) = train_test_split(data, labels, test_size = 0.25,\n random_state = 42)", "_____no_output_____" ] ], [ [ "### Transforming the labels", "_____no_output_____" ] ], [ [ "y_train = LabelBinarizer().fit_transform(y_train)\ny_test = LabelBinarizer().fit_transform(y_test)", "_____no_output_____" ] ], [ [ "### Defining the Image Generator function from Keras\n\nThe Data Augmentations consists in transform an image, rotating, shearing, zooming and flipping horizontally it. In this way, a simple image generates others six.", "_____no_output_____" ] ], [ [ "aug = ImageDataGenerator(rotation_range=30, width_shift_range=0.1,\n height_shift_range=0.1, shear_range=0.2, zoom_range=0.2,\n horizontal_flip=True, fill_mode=\"nearest\")", "_____no_output_____" ] ], [ [ "## Building the model Model\n", "_____no_output_____" ], [ "**Defining the step decay function**", "_____no_output_____" ] ], [ [ "def step_decay(epoch, lr):\n \n init_alpha = 0.01 # initial learning rate\n factor = 0.25\n dropEvery = 5 # step size\n \n if epoch == 1:\n lr = init_alpha\n elif epoch%5 == 0:\n lr = init_alpha * (factor ** np.floor((1 + epoch) / dropEvery))\n else:\n lr = lr\n return lr", "_____no_output_____" ] ], [ [ "**Defining the Callbacks**", "_____no_output_____" ] ], [ [ "callbacks = [LearningRateScheduler(step_decay)]", "_____no_output_____" ] ], [ [ "### Defining the first model", "_____no_output_____" ] ], [ [ "opt = SGD(momentum=0.9, nesterov=True) # regularization\nmodel = MiniVGG.build(32, 32, 3, 3) #model\nmodel.compile(loss = \"categorical_crossentropy\", optimizer = opt, metrics = [\"accuracy\"]) # compiling the model", "_____no_output_____" ] ], [ [ "### Training the first model\n\nWe choose the batch size of $32$ and $100$ epochs.", "_____no_output_____" ] ], [ [ "ne = 100\nbs = 32", "_____no_output_____" ], [ "H = model.fit(X_train, y_train, validation_data = (X_test, y_test),\n batch_size = bs, epochs = ne, callbacks=callbacks, verbose = 1)", "Train on 2250 samples, validate on 750 samples\nEpoch 1/100\n2250/2250 [==============================] - 3s 1ms/sample - loss: 1.3921 - accuracy: 0.5516 - val_loss: 3.5832 - val_accuracy: 0.4067\nEpoch 2/100\n2250/2250 [==============================] - 1s 241us/sample - loss: 1.1532 - accuracy: 0.5960 - val_loss: 1.4698 - val_accuracy: 0.5293\nEpoch 3/100\n2250/2250 [==============================] - 1s 238us/sample - loss: 1.0479 - accuracy: 0.6307 - val_loss: 1.2169 - val_accuracy: 0.4947\nEpoch 4/100\n2250/2250 [==============================] - 1s 236us/sample - loss: 1.0022 - accuracy: 0.6511 - val_loss: 1.0516 - val_accuracy: 0.5920\nEpoch 5/100\n2250/2250 [==============================] - 1s 241us/sample - loss: 0.9758 - accuracy: 0.6640 - val_loss: 0.8298 - val_accuracy: 0.6507\nEpoch 6/100\n2250/2250 [==============================] - 1s 238us/sample - loss: 0.7358 - accuracy: 0.7049 - val_loss: 0.7089 - val_accuracy: 0.6840\nEpoch 7/100\n2250/2250 [==============================] - 1s 236us/sample - loss: 0.6350 - accuracy: 0.7369 - val_loss: 0.7976 - val_accuracy: 0.6813\nEpoch 8/100\n2250/2250 [==============================] - 1s 240us/sample - loss: 0.6264 - accuracy: 0.7444 - val_loss: 0.7227 - val_accuracy: 0.6853\nEpoch 9/100\n2250/2250 [==============================] - 1s 237us/sample - loss: 0.5389 - accuracy: 0.7667 - val_loss: 0.6657 - val_accuracy: 0.7213\nEpoch 10/100\n2250/2250 [==============================] - 1s 248us/sample - loss: 0.4988 - accuracy: 0.7804 - val_loss: 0.6692 - val_accuracy: 0.7173\nEpoch 11/100\n2250/2250 [==============================] - 1s 242us/sample - loss: 0.4792 - accuracy: 0.7911 - val_loss: 0.6564 - val_accuracy: 0.7133\nEpoch 12/100\n2250/2250 [==============================] - 1s 252us/sample - loss: 0.4529 - accuracy: 0.8058 - val_loss: 0.6582 - val_accuracy: 0.7267\nEpoch 13/100\n2250/2250 [==============================] - 1s 240us/sample - loss: 0.4441 - accuracy: 0.8044 - val_loss: 0.6704 - val_accuracy: 0.7267\nEpoch 14/100\n2250/2250 [==============================] - 1s 244us/sample - loss: 0.4567 - accuracy: 0.7960 - val_loss: 0.6697 - val_accuracy: 0.7320\nEpoch 15/100\n2250/2250 [==============================] - 1s 255us/sample - loss: 0.4580 - accuracy: 0.8053 - val_loss: 0.6668 - val_accuracy: 0.7187\nEpoch 16/100\n2250/2250 [==============================] - 1s 253us/sample - loss: 0.4182 - accuracy: 0.8213 - val_loss: 0.6576 - val_accuracy: 0.7280\nEpoch 17/100\n2250/2250 [==============================] - 1s 270us/sample - loss: 0.4058 - accuracy: 0.8307 - val_loss: 0.6557 - val_accuracy: 0.7293\nEpoch 18/100\n2250/2250 [==============================] - 1s 244us/sample - loss: 0.4198 - accuracy: 0.8213 - val_loss: 0.6519 - val_accuracy: 0.7293\nEpoch 19/100\n2250/2250 [==============================] - 1s 242us/sample - loss: 0.3881 - accuracy: 0.8333 - val_loss: 0.6517 - val_accuracy: 0.7320\nEpoch 20/100\n2250/2250 [==============================] - 1s 246us/sample - loss: 0.4020 - accuracy: 0.8284 - val_loss: 0.6580 - val_accuracy: 0.7307\nEpoch 21/100\n2250/2250 [==============================] - 1s 239us/sample - loss: 0.4167 - accuracy: 0.8218 - val_loss: 0.6592 - val_accuracy: 0.7320\nEpoch 22/100\n2250/2250 [==============================] - 1s 245us/sample - loss: 0.4089 - accuracy: 0.8182 - val_loss: 0.6575 - val_accuracy: 0.7320\nEpoch 23/100\n2250/2250 [==============================] - 1s 243us/sample - loss: 0.3874 - accuracy: 0.8360 - val_loss: 0.6575 - val_accuracy: 0.7360\nEpoch 24/100\n2250/2250 [==============================] - 1s 244us/sample - loss: 0.4048 - accuracy: 0.8284 - val_loss: 0.6569 - val_accuracy: 0.7307\nEpoch 25/100\n2250/2250 [==============================] - 1s 243us/sample - loss: 0.3970 - accuracy: 0.8293 - val_loss: 0.6571 - val_accuracy: 0.7320\nEpoch 26/100\n2250/2250 [==============================] - 1s 240us/sample - loss: 0.4011 - accuracy: 0.8196 - val_loss: 0.6566 - val_accuracy: 0.7320\nEpoch 27/100\n2250/2250 [==============================] - 1s 240us/sample - loss: 0.3904 - accuracy: 0.8369 - val_loss: 0.6582 - val_accuracy: 0.7333\nEpoch 28/100\n2250/2250 [==============================] - 1s 242us/sample - loss: 0.4030 - accuracy: 0.8289 - val_loss: 0.6584 - val_accuracy: 0.7320\nEpoch 29/100\n2250/2250 [==============================] - 1s 245us/sample - loss: 0.3940 - accuracy: 0.8324 - val_loss: 0.6588 - val_accuracy: 0.7320\nEpoch 30/100\n2250/2250 [==============================] - 1s 243us/sample - loss: 0.4211 - accuracy: 0.8262 - val_loss: 0.6577 - val_accuracy: 0.7333\nEpoch 31/100\n2250/2250 [==============================] - 1s 241us/sample - loss: 0.4078 - accuracy: 0.8244 - val_loss: 0.6565 - val_accuracy: 0.7333\nEpoch 32/100\n2250/2250 [==============================] - 1s 243us/sample - loss: 0.4073 - accuracy: 0.8196 - val_loss: 0.6581 - val_accuracy: 0.7333\nEpoch 33/100\n2250/2250 [==============================] - 1s 241us/sample - loss: 0.3969 - accuracy: 0.8293 - val_loss: 0.6587 - val_accuracy: 0.7333\nEpoch 34/100\n2250/2250 [==============================] - 1s 243us/sample - loss: 0.3985 - accuracy: 0.8302 - val_loss: 0.6581 - val_accuracy: 0.7333\nEpoch 35/100\n2250/2250 [==============================] - 1s 239us/sample - loss: 0.4033 - accuracy: 0.8271 - val_loss: 0.6592 - val_accuracy: 0.7333\nEpoch 36/100\n2250/2250 [==============================] - 1s 242us/sample - loss: 0.4365 - accuracy: 0.8182 - val_loss: 0.6587 - val_accuracy: 0.7333\nEpoch 37/100\n2250/2250 [==============================] - 1s 238us/sample - loss: 0.4101 - accuracy: 0.8316 - val_loss: 0.6586 - val_accuracy: 0.7333\nEpoch 38/100\n2250/2250 [==============================] - 1s 245us/sample - loss: 0.3723 - accuracy: 0.8413 - val_loss: 0.6585 - val_accuracy: 0.7333\nEpoch 39/100\n2250/2250 [==============================] - 1s 244us/sample - loss: 0.3991 - accuracy: 0.8298 - val_loss: 0.6575 - val_accuracy: 0.7333\nEpoch 40/100\n2250/2250 [==============================] - 1s 246us/sample - loss: 0.4063 - accuracy: 0.8258 - val_loss: 0.6585 - val_accuracy: 0.7333\nEpoch 41/100\n2250/2250 [==============================] - 1s 244us/sample - loss: 0.4002 - accuracy: 0.8271 - val_loss: 0.6594 - val_accuracy: 0.7307\nEpoch 42/100\n2250/2250 [==============================] - 1s 247us/sample - loss: 0.4143 - accuracy: 0.8222 - val_loss: 0.6604 - val_accuracy: 0.7320\nEpoch 43/100\n2250/2250 [==============================] - 1s 240us/sample - loss: 0.3983 - accuracy: 0.8289 - val_loss: 0.6587 - val_accuracy: 0.7320\nEpoch 44/100\n2250/2250 [==============================] - 1s 240us/sample - loss: 0.3996 - accuracy: 0.8284 - val_loss: 0.6593 - val_accuracy: 0.7320\nEpoch 45/100\n2250/2250 [==============================] - 1s 240us/sample - loss: 0.4114 - accuracy: 0.8249 - val_loss: 0.6578 - val_accuracy: 0.7320\nEpoch 46/100\n2250/2250 [==============================] - 1s 237us/sample - loss: 0.4054 - accuracy: 0.8298 - val_loss: 0.6587 - val_accuracy: 0.7307\nEpoch 47/100\n2250/2250 [==============================] - 1s 238us/sample - loss: 0.4067 - accuracy: 0.8289 - val_loss: 0.6586 - val_accuracy: 0.7333\nEpoch 48/100\n2250/2250 [==============================] - 1s 236us/sample - loss: 0.3741 - accuracy: 0.8382 - val_loss: 0.6581 - val_accuracy: 0.7307\nEpoch 49/100\n2250/2250 [==============================] - 1s 240us/sample - loss: 0.4031 - accuracy: 0.8293 - val_loss: 0.6590 - val_accuracy: 0.7320\nEpoch 50/100\n2250/2250 [==============================] - 1s 241us/sample - loss: 0.4155 - accuracy: 0.8160 - val_loss: 0.6603 - val_accuracy: 0.7347\nEpoch 51/100\n2250/2250 [==============================] - 1s 241us/sample - loss: 0.4117 - accuracy: 0.8191 - val_loss: 0.6605 - val_accuracy: 0.7320\nEpoch 52/100\n2250/2250 [==============================] - 1s 242us/sample - loss: 0.3902 - accuracy: 0.8373 - val_loss: 0.6598 - val_accuracy: 0.7333\nEpoch 53/100\n2250/2250 [==============================] - 1s 260us/sample - loss: 0.3977 - accuracy: 0.8276 - val_loss: 0.6599 - val_accuracy: 0.7333\nEpoch 54/100\n2250/2250 [==============================] - 1s 267us/sample - loss: 0.3984 - accuracy: 0.8142 - val_loss: 0.6599 - val_accuracy: 0.7320\nEpoch 55/100\n2250/2250 [==============================] - 1s 250us/sample - loss: 0.4157 - accuracy: 0.8213 - val_loss: 0.6599 - val_accuracy: 0.7320\nEpoch 56/100\n2250/2250 [==============================] - 1s 237us/sample - loss: 0.4173 - accuracy: 0.8289 - val_loss: 0.6630 - val_accuracy: 0.7320\nEpoch 57/100\n2250/2250 [==============================] - 1s 274us/sample - loss: 0.4007 - accuracy: 0.8311 - val_loss: 0.6608 - val_accuracy: 0.7320\nEpoch 58/100\n2250/2250 [==============================] - 1s 267us/sample - loss: 0.3957 - accuracy: 0.8209 - val_loss: 0.6603 - val_accuracy: 0.7307\nEpoch 59/100\n2250/2250 [==============================] - 1s 264us/sample - loss: 0.3899 - accuracy: 0.8333 - val_loss: 0.6574 - val_accuracy: 0.7320\nEpoch 60/100\n2250/2250 [==============================] - 1s 237us/sample - loss: 0.4105 - accuracy: 0.8271 - val_loss: 0.6574 - val_accuracy: 0.7333\nEpoch 61/100\n2250/2250 [==============================] - 1s 261us/sample - loss: 0.4115 - accuracy: 0.8178 - val_loss: 0.6583 - val_accuracy: 0.7320\nEpoch 62/100\n2250/2250 [==============================] - 1s 250us/sample - loss: 0.4098 - accuracy: 0.8231 - val_loss: 0.6578 - val_accuracy: 0.7320\nEpoch 63/100\n2250/2250 [==============================] - 1s 248us/sample - loss: 0.3950 - accuracy: 0.8280 - val_loss: 0.6567 - val_accuracy: 0.7333\nEpoch 64/100\n2250/2250 [==============================] - 1s 267us/sample - loss: 0.4166 - accuracy: 0.8151 - val_loss: 0.6572 - val_accuracy: 0.7333\nEpoch 65/100\n2250/2250 [==============================] - 1s 237us/sample - loss: 0.3938 - accuracy: 0.8373 - val_loss: 0.6578 - val_accuracy: 0.7333\nEpoch 66/100\n2250/2250 [==============================] - 1s 251us/sample - loss: 0.4047 - accuracy: 0.8147 - val_loss: 0.6578 - val_accuracy: 0.7333\nEpoch 67/100\n2250/2250 [==============================] - 1s 269us/sample - loss: 0.4084 - accuracy: 0.8271 - val_loss: 0.6588 - val_accuracy: 0.7347\nEpoch 68/100\n2250/2250 [==============================] - 1s 259us/sample - loss: 0.4023 - accuracy: 0.8253 - val_loss: 0.6588 - val_accuracy: 0.7320\nEpoch 69/100\n2250/2250 [==============================] - 1s 267us/sample - loss: 0.4194 - accuracy: 0.8222 - val_loss: 0.6595 - val_accuracy: 0.7333\nEpoch 70/100\n2250/2250 [==============================] - 1s 255us/sample - loss: 0.4232 - accuracy: 0.8142 - val_loss: 0.6608 - val_accuracy: 0.7320\nEpoch 71/100\n2250/2250 [==============================] - 1s 242us/sample - loss: 0.3977 - accuracy: 0.8271 - val_loss: 0.6576 - val_accuracy: 0.7333\nEpoch 72/100\n2250/2250 [==============================] - 1s 263us/sample - loss: 0.3968 - accuracy: 0.8316 - val_loss: 0.6564 - val_accuracy: 0.7347\nEpoch 73/100\n2250/2250 [==============================] - 1s 261us/sample - loss: 0.4312 - accuracy: 0.8111 - val_loss: 0.6570 - val_accuracy: 0.7320\nEpoch 74/100\n2250/2250 [==============================] - 1s 264us/sample - loss: 0.4040 - accuracy: 0.8258 - val_loss: 0.6586 - val_accuracy: 0.7347\nEpoch 75/100\n2250/2250 [==============================] - 1s 257us/sample - loss: 0.3980 - accuracy: 0.8298 - val_loss: 0.6576 - val_accuracy: 0.7333\nEpoch 76/100\n2250/2250 [==============================] - 1s 244us/sample - loss: 0.4069 - accuracy: 0.8231 - val_loss: 0.6576 - val_accuracy: 0.7320\nEpoch 77/100\n2250/2250 [==============================] - 1s 266us/sample - loss: 0.3946 - accuracy: 0.8324 - val_loss: 0.6583 - val_accuracy: 0.7333\nEpoch 78/100\n2250/2250 [==============================] - 1s 242us/sample - loss: 0.4032 - accuracy: 0.8284 - val_loss: 0.6585 - val_accuracy: 0.7333\nEpoch 79/100\n2250/2250 [==============================] - 1s 245us/sample - loss: 0.4155 - accuracy: 0.8227 - val_loss: 0.6581 - val_accuracy: 0.7320\nEpoch 80/100\n2250/2250 [==============================] - 1s 245us/sample - loss: 0.3988 - accuracy: 0.8182 - val_loss: 0.6580 - val_accuracy: 0.7320\nEpoch 81/100\n2250/2250 [==============================] - 1s 236us/sample - loss: 0.4308 - accuracy: 0.8227 - val_loss: 0.6581 - val_accuracy: 0.7333\nEpoch 82/100\n2250/2250 [==============================] - 1s 231us/sample - loss: 0.4043 - accuracy: 0.8347 - val_loss: 0.6586 - val_accuracy: 0.7320\nEpoch 83/100\n2250/2250 [==============================] - 1s 250us/sample - loss: 0.4113 - accuracy: 0.8236 - val_loss: 0.6586 - val_accuracy: 0.7320\nEpoch 84/100\n2250/2250 [==============================] - 1s 240us/sample - loss: 0.4008 - accuracy: 0.8267 - val_loss: 0.6583 - val_accuracy: 0.7307\nEpoch 85/100\n2250/2250 [==============================] - 1s 244us/sample - loss: 0.4102 - accuracy: 0.8262 - val_loss: 0.6580 - val_accuracy: 0.7307\nEpoch 86/100\n2250/2250 [==============================] - 1s 240us/sample - loss: 0.4091 - accuracy: 0.8187 - val_loss: 0.6589 - val_accuracy: 0.7320\nEpoch 87/100\n2250/2250 [==============================] - 1s 248us/sample - loss: 0.4048 - accuracy: 0.8204 - val_loss: 0.6579 - val_accuracy: 0.7320\nEpoch 88/100\n2250/2250 [==============================] - 1s 264us/sample - loss: 0.4009 - accuracy: 0.8280 - val_loss: 0.6591 - val_accuracy: 0.7320\nEpoch 89/100\n2250/2250 [==============================] - 1s 256us/sample - loss: 0.3959 - accuracy: 0.8271 - val_loss: 0.6583 - val_accuracy: 0.7333\nEpoch 90/100\n2250/2250 [==============================] - 1s 256us/sample - loss: 0.3760 - accuracy: 0.8391 - val_loss: 0.6586 - val_accuracy: 0.7307\nEpoch 91/100\n2250/2250 [==============================] - 1s 253us/sample - loss: 0.4021 - accuracy: 0.8142 - val_loss: 0.6585 - val_accuracy: 0.7307\nEpoch 92/100\n2250/2250 [==============================] - 1s 263us/sample - loss: 0.4079 - accuracy: 0.8204 - val_loss: 0.6578 - val_accuracy: 0.7360\nEpoch 93/100\n2250/2250 [==============================] - 1s 250us/sample - loss: 0.4171 - accuracy: 0.8227 - val_loss: 0.6573 - val_accuracy: 0.7320\nEpoch 94/100\n2250/2250 [==============================] - 1s 251us/sample - loss: 0.4019 - accuracy: 0.8289 - val_loss: 0.6588 - val_accuracy: 0.7307\nEpoch 95/100\n2250/2250 [==============================] - 1s 269us/sample - loss: 0.4028 - accuracy: 0.8191 - val_loss: 0.6576 - val_accuracy: 0.7307\nEpoch 96/100\n2250/2250 [==============================] - 1s 262us/sample - loss: 0.3898 - accuracy: 0.8289 - val_loss: 0.6583 - val_accuracy: 0.7333\nEpoch 97/100\n2250/2250 [==============================] - 1s 284us/sample - loss: 0.4004 - accuracy: 0.8267 - val_loss: 0.6581 - val_accuracy: 0.7333\nEpoch 98/100\n2250/2250 [==============================] - 1s 296us/sample - loss: 0.3761 - accuracy: 0.8409 - val_loss: 0.6582 - val_accuracy: 0.7347\nEpoch 99/100\n2250/2250 [==============================] - 1s 267us/sample - loss: 0.3929 - accuracy: 0.8364 - val_loss: 0.6575 - val_accuracy: 0.7347\nEpoch 100/100\n2250/2250 [==============================] - 1s 280us/sample - loss: 0.4090 - accuracy: 0.8169 - val_loss: 0.6574 - val_accuracy: 0.7333\n" ] ], [ [ "### Predicting on the first trained model", "_____no_output_____" ] ], [ [ "predictions = model.predict(X_test, batch_size = bs)", "_____no_output_____" ] ], [ [ "### Evaluating the first model", "_____no_output_____" ] ], [ [ "cr = classification_report(y_test.argmax(axis = 1),\n predictions.argmax(axis = 1),\n target_names = [\"cat\", \"dog\", \"panda\"])", "_____no_output_____" ], [ "print(cr)", " precision recall f1-score support\n\n cat 0.69 0.67 0.68 249\n dog 0.61 0.71 0.66 239\n panda 0.91 0.82 0.87 262\n\n accuracy 0.73 750\n macro avg 0.74 0.73 0.73 750\nweighted avg 0.75 0.73 0.74 750\n\n" ] ], [ [ "### Visualizing the metrics results", "_____no_output_____" ] ], [ [ "plt.style.use(\"ggplot\")\nplt.figure(figsize=(20,20))\nplt.plot(np.arange(0, ne), H.history[\"loss\"], label=\"train_loss\")\nplt.plot(np.arange(0, ne), H.history[\"val_loss\"], label=\"val_loss\")\nplt.plot(np.arange(0, ne), H.history[\"accuracy\"], label=\"train_acc\")\nplt.plot(np.arange(0, ne), H.history[\"val_accuracy\"], label=\"val_acc\")\nplt.axis((0, ne, 0.25, 1))\nplt.title(\"Training Loss and Accuracy\")\nplt.xlabel(\"Epoch #\")\nplt.ylabel(\"Loss/Accuracy\")\nplt.legend()\nplt.show()\n", "_____no_output_____" ] ], [ [ "### Defining the second model with Data Augmentation", "_____no_output_____" ] ], [ [ "model1 = MiniVGG.build(32, 32, 3, 3)\nmodel1.compile(loss = \"categorical_crossentropy\", optimizer = opt, metrics = [\"accuracy\"])", "_____no_output_____" ] ], [ [ "### Training the second model\n\nIn the fit, We have add the aug.flow() that accepts as argument, the training and the batch size.", "_____no_output_____" ] ], [ [ "H = model1.fit(aug.flow(X_train, y_train, batch_size=bs), validation_data=(X_test, y_test),\n steps_per_epoch=len(X_train) // 32,\n epochs=ne, callbacks=callbacks, verbose=1)", "WARNING:tensorflow:sample_weight modes were coerced from\n ...\n to \n ['...']\nTrain for 70 steps, validate on 750 samples\nEpoch 1/100\n70/70 [==============================] - 2s 26ms/step - loss: 1.4887 - accuracy: 0.5298 - val_loss: 2.1248 - val_accuracy: 0.3853\nEpoch 2/100\n70/70 [==============================] - 1s 15ms/step - loss: 1.2853 - accuracy: 0.5550 - val_loss: 2.2235 - val_accuracy: 0.3547\nEpoch 3/100\n70/70 [==============================] - 1s 15ms/step - loss: 1.2097 - accuracy: 0.5654 - val_loss: 1.6565 - val_accuracy: 0.4093\nEpoch 4/100\n70/70 [==============================] - 1s 16ms/step - loss: 1.1782 - accuracy: 0.5717 - val_loss: 1.6933 - val_accuracy: 0.4213\nEpoch 5/100\n70/70 [==============================] - 1s 15ms/step - loss: 1.1248 - accuracy: 0.5920 - val_loss: 1.0718 - val_accuracy: 0.6160\nEpoch 6/100\n70/70 [==============================] - 1s 15ms/step - loss: 1.0167 - accuracy: 0.6168 - val_loss: 0.7027 - val_accuracy: 0.6733\nEpoch 7/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.8647 - accuracy: 0.6366 - val_loss: 0.7053 - val_accuracy: 0.6947\nEpoch 8/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.7914 - accuracy: 0.6610 - val_loss: 0.6211 - val_accuracy: 0.7213\nEpoch 9/100\n70/70 [==============================] - 1s 16ms/step - loss: 0.7589 - accuracy: 0.6506 - val_loss: 0.6776 - val_accuracy: 0.6840\nEpoch 10/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.7314 - accuracy: 0.6646 - val_loss: 0.6808 - val_accuracy: 0.6893\nEpoch 11/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.7113 - accuracy: 0.6718 - val_loss: 0.6328 - val_accuracy: 0.7213\nEpoch 12/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6737 - accuracy: 0.6885 - val_loss: 0.6163 - val_accuracy: 0.7280\nEpoch 13/100\n70/70 [==============================] - 1s 16ms/step - loss: 0.6860 - accuracy: 0.6835 - val_loss: 0.6297 - val_accuracy: 0.7053\nEpoch 14/100\n70/70 [==============================] - 1s 16ms/step - loss: 0.6677 - accuracy: 0.6880 - val_loss: 0.6262 - val_accuracy: 0.7227\nEpoch 15/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6686 - accuracy: 0.6894 - val_loss: 0.6047 - val_accuracy: 0.7293\nEpoch 16/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6587 - accuracy: 0.6817 - val_loss: 0.6002 - val_accuracy: 0.7293\nEpoch 17/100\n70/70 [==============================] - 1s 16ms/step - loss: 0.6404 - accuracy: 0.7083 - val_loss: 0.5990 - val_accuracy: 0.7427\nEpoch 18/100\n70/70 [==============================] - 1s 16ms/step - loss: 0.6554 - accuracy: 0.7024 - val_loss: 0.5970 - val_accuracy: 0.7387\nEpoch 19/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6424 - accuracy: 0.7029 - val_loss: 0.5963 - val_accuracy: 0.7373\nEpoch 20/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6309 - accuracy: 0.6984 - val_loss: 0.5969 - val_accuracy: 0.7360\nEpoch 21/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6496 - accuracy: 0.6975 - val_loss: 0.5980 - val_accuracy: 0.7333\nEpoch 22/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6295 - accuracy: 0.7015 - val_loss: 0.5971 - val_accuracy: 0.7387\nEpoch 23/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6356 - accuracy: 0.7060 - val_loss: 0.5970 - val_accuracy: 0.7400\nEpoch 24/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6274 - accuracy: 0.7006 - val_loss: 0.5960 - val_accuracy: 0.7400\nEpoch 25/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6340 - accuracy: 0.6979 - val_loss: 0.5982 - val_accuracy: 0.7400\nEpoch 26/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6536 - accuracy: 0.6975 - val_loss: 0.5981 - val_accuracy: 0.7400\nEpoch 27/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6481 - accuracy: 0.7020 - val_loss: 0.5984 - val_accuracy: 0.7400\nEpoch 28/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6528 - accuracy: 0.6898 - val_loss: 0.5979 - val_accuracy: 0.7373\nEpoch 29/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6285 - accuracy: 0.7038 - val_loss: 0.5960 - val_accuracy: 0.7413\nEpoch 30/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6502 - accuracy: 0.6790 - val_loss: 0.5965 - val_accuracy: 0.7400\nEpoch 31/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6352 - accuracy: 0.6975 - val_loss: 0.5972 - val_accuracy: 0.7400\nEpoch 32/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6336 - accuracy: 0.6984 - val_loss: 0.5962 - val_accuracy: 0.7427\nEpoch 33/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6275 - accuracy: 0.6961 - val_loss: 0.5964 - val_accuracy: 0.7400\nEpoch 34/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6258 - accuracy: 0.6975 - val_loss: 0.5972 - val_accuracy: 0.7400\nEpoch 35/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6399 - accuracy: 0.7020 - val_loss: 0.5967 - val_accuracy: 0.7400\nEpoch 36/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6245 - accuracy: 0.7020 - val_loss: 0.5962 - val_accuracy: 0.7400\nEpoch 37/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6428 - accuracy: 0.6934 - val_loss: 0.5964 - val_accuracy: 0.7413\nEpoch 38/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6297 - accuracy: 0.6970 - val_loss: 0.5957 - val_accuracy: 0.7427\nEpoch 39/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6382 - accuracy: 0.7083 - val_loss: 0.5958 - val_accuracy: 0.7413\nEpoch 40/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6381 - accuracy: 0.6921 - val_loss: 0.5956 - val_accuracy: 0.7413\nEpoch 41/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6228 - accuracy: 0.7011 - val_loss: 0.5961 - val_accuracy: 0.7413\nEpoch 42/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6292 - accuracy: 0.7074 - val_loss: 0.5961 - val_accuracy: 0.7413\nEpoch 43/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6203 - accuracy: 0.7101 - val_loss: 0.5964 - val_accuracy: 0.7400\nEpoch 44/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6380 - accuracy: 0.7015 - val_loss: 0.5953 - val_accuracy: 0.7413\nEpoch 45/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6281 - accuracy: 0.7119 - val_loss: 0.5952 - val_accuracy: 0.7413\nEpoch 46/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6417 - accuracy: 0.7029 - val_loss: 0.5965 - val_accuracy: 0.7413\nEpoch 47/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6377 - accuracy: 0.6975 - val_loss: 0.5966 - val_accuracy: 0.7400\nEpoch 48/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6346 - accuracy: 0.7069 - val_loss: 0.5972 - val_accuracy: 0.7400\nEpoch 49/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6337 - accuracy: 0.6984 - val_loss: 0.5963 - val_accuracy: 0.7427\nEpoch 50/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6498 - accuracy: 0.6979 - val_loss: 0.5980 - val_accuracy: 0.7400\nEpoch 51/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6341 - accuracy: 0.7002 - val_loss: 0.5976 - val_accuracy: 0.7400\nEpoch 52/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6332 - accuracy: 0.7074 - val_loss: 0.5978 - val_accuracy: 0.7413\nEpoch 53/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6326 - accuracy: 0.7047 - val_loss: 0.5973 - val_accuracy: 0.7413\nEpoch 54/100\n70/70 [==============================] - 1s 16ms/step - loss: 0.6433 - accuracy: 0.7056 - val_loss: 0.5970 - val_accuracy: 0.7400\nEpoch 55/100\n70/70 [==============================] - 1s 16ms/step - loss: 0.6293 - accuracy: 0.7029 - val_loss: 0.5971 - val_accuracy: 0.7400\nEpoch 56/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6324 - accuracy: 0.7096 - val_loss: 0.5975 - val_accuracy: 0.7400\nEpoch 57/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6194 - accuracy: 0.7096 - val_loss: 0.5973 - val_accuracy: 0.7400\nEpoch 58/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6298 - accuracy: 0.7047 - val_loss: 0.5964 - val_accuracy: 0.7400\nEpoch 59/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6403 - accuracy: 0.7065 - val_loss: 0.5966 - val_accuracy: 0.7413\nEpoch 60/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6348 - accuracy: 0.7029 - val_loss: 0.5966 - val_accuracy: 0.7400\nEpoch 61/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6409 - accuracy: 0.7096 - val_loss: 0.5962 - val_accuracy: 0.7413\nEpoch 62/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6241 - accuracy: 0.7060 - val_loss: 0.5962 - val_accuracy: 0.7427\nEpoch 63/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6487 - accuracy: 0.7002 - val_loss: 0.5969 - val_accuracy: 0.7400\nEpoch 64/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6145 - accuracy: 0.7119 - val_loss: 0.5963 - val_accuracy: 0.7427\nEpoch 65/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6305 - accuracy: 0.7006 - val_loss: 0.5969 - val_accuracy: 0.7400\nEpoch 66/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6299 - accuracy: 0.7083 - val_loss: 0.5965 - val_accuracy: 0.7400\nEpoch 67/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6250 - accuracy: 0.7029 - val_loss: 0.5957 - val_accuracy: 0.7413\nEpoch 68/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6444 - accuracy: 0.6943 - val_loss: 0.5965 - val_accuracy: 0.7400\nEpoch 69/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6363 - accuracy: 0.7087 - val_loss: 0.5961 - val_accuracy: 0.7413\nEpoch 70/100\n70/70 [==============================] - 1s 16ms/step - loss: 0.6404 - accuracy: 0.6961 - val_loss: 0.5956 - val_accuracy: 0.7413\nEpoch 71/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6354 - accuracy: 0.7033 - val_loss: 0.5953 - val_accuracy: 0.7413\nEpoch 72/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6306 - accuracy: 0.7115 - val_loss: 0.5941 - val_accuracy: 0.7427\nEpoch 73/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6105 - accuracy: 0.7173 - val_loss: 0.5956 - val_accuracy: 0.7413\nEpoch 74/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6534 - accuracy: 0.6966 - val_loss: 0.5968 - val_accuracy: 0.7400\nEpoch 75/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6499 - accuracy: 0.6907 - val_loss: 0.5961 - val_accuracy: 0.7400\nEpoch 76/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6316 - accuracy: 0.6957 - val_loss: 0.5974 - val_accuracy: 0.7400\nEpoch 77/100\n70/70 [==============================] - 1s 16ms/step - loss: 0.6395 - accuracy: 0.7074 - val_loss: 0.5977 - val_accuracy: 0.7400\nEpoch 78/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6469 - accuracy: 0.6957 - val_loss: 0.5968 - val_accuracy: 0.7400\nEpoch 79/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6353 - accuracy: 0.6939 - val_loss: 0.5965 - val_accuracy: 0.7400\nEpoch 80/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6330 - accuracy: 0.7015 - val_loss: 0.5961 - val_accuracy: 0.7387\nEpoch 81/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6408 - accuracy: 0.7029 - val_loss: 0.5961 - val_accuracy: 0.7400\nEpoch 82/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6290 - accuracy: 0.6885 - val_loss: 0.5965 - val_accuracy: 0.7400\nEpoch 83/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6333 - accuracy: 0.7119 - val_loss: 0.5963 - val_accuracy: 0.7400\nEpoch 84/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6207 - accuracy: 0.7196 - val_loss: 0.5961 - val_accuracy: 0.7413\nEpoch 85/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6369 - accuracy: 0.7092 - val_loss: 0.5958 - val_accuracy: 0.7427\nEpoch 86/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6131 - accuracy: 0.7151 - val_loss: 0.5955 - val_accuracy: 0.7400\nEpoch 87/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6151 - accuracy: 0.7119 - val_loss: 0.5967 - val_accuracy: 0.7400\nEpoch 88/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6076 - accuracy: 0.7259 - val_loss: 0.5958 - val_accuracy: 0.7413\nEpoch 89/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6352 - accuracy: 0.7110 - val_loss: 0.5965 - val_accuracy: 0.7400\nEpoch 90/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6395 - accuracy: 0.7011 - val_loss: 0.5961 - val_accuracy: 0.7413\nEpoch 91/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6120 - accuracy: 0.7299 - val_loss: 0.5953 - val_accuracy: 0.7413\nEpoch 92/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6280 - accuracy: 0.7033 - val_loss: 0.5967 - val_accuracy: 0.7400\nEpoch 93/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6318 - accuracy: 0.7124 - val_loss: 0.5961 - val_accuracy: 0.7427\nEpoch 94/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6262 - accuracy: 0.7128 - val_loss: 0.5959 - val_accuracy: 0.7413\nEpoch 95/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6360 - accuracy: 0.7065 - val_loss: 0.5954 - val_accuracy: 0.7413\nEpoch 96/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6183 - accuracy: 0.7078 - val_loss: 0.5948 - val_accuracy: 0.7413\nEpoch 97/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6306 - accuracy: 0.7096 - val_loss: 0.5959 - val_accuracy: 0.7413\nEpoch 98/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6523 - accuracy: 0.6844 - val_loss: 0.5969 - val_accuracy: 0.7400\nEpoch 99/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6262 - accuracy: 0.7119 - val_loss: 0.5976 - val_accuracy: 0.7400\nEpoch 100/100\n70/70 [==============================] - 1s 15ms/step - loss: 0.6349 - accuracy: 0.7024 - val_loss: 0.5981 - val_accuracy: 0.7400\n" ] ], [ [ "### Predicting on the second model", "_____no_output_____" ] ], [ [ "predictions = model.predict(X_test, batch_size = bs)", "_____no_output_____" ] ], [ [ "### Evaluating the second model", "_____no_output_____" ] ], [ [ "cr = classification_report(y_test.argmax(axis = 1),\n predictions.argmax(axis = 1),\n target_names = [\"cat\", \"dog\", \"panda\"])", "_____no_output_____" ], [ "print(cr)", " precision recall f1-score support\n\n cat 0.69 0.67 0.68 249\n dog 0.61 0.71 0.66 239\n panda 0.91 0.82 0.87 262\n\n accuracy 0.73 750\n macro avg 0.74 0.73 0.73 750\nweighted avg 0.75 0.73 0.74 750\n\n" ] ], [ [ "### Visualizing the metrics results", "_____no_output_____" ] ], [ [ "plt.style.use(\"ggplot\")\nplt.figure(figsize=(20,20))\nplt.plot(np.arange(0, ne), H.history[\"loss\"], label=\"train_loss\")\nplt.plot(np.arange(0, ne), H.history[\"val_loss\"], label=\"val_loss\")\nplt.plot(np.arange(0, ne), H.history[\"accuracy\"], label=\"train_acc\")\nplt.plot(np.arange(0, ne), H.history[\"val_accuracy\"], label=\"val_acc\")\n#plt.axis('on')\nplt.axis((0, ne, 0.25, 1))\nplt.title(\"Training Loss and Accuracy\")\nplt.xlabel(\"Epoch #\")\nplt.ylabel(\"Loss/Accuracy\")\nplt.legend()\nplt.savefig(\"1off\")\nplt.show()\n", "_____no_output_____" ] ], [ [ "## Conclusions\n\nFirst of all, We can note that all results for the Animal dataset increased, in comparison with the last implemented model. The primary accuracy was of $70\\%$ considering the [ShallowNet architecture](https://github.com/IgorMeloS/Computer-Vision-Training/blob/main/Practical%20Examples/3%20-%20Simple%20CNN/Animals_shallownet.ipynb). Here, the accuracy for the two model was $74\\%$, a gain of $4\\%$, that can represent a significant gain.\n\nThe result from the first model shows an interesting fact, resize the images considering the aspect ratio, enable us to improve our results. On the other hand, the model still in over-fitting situation, the gap between the train and validation loss is enough considerable, despite the gain on the accuracy.\n\nThe second model shows in your results, the power of Data Augmentation. This regularization allowed us to obtain a gain for the accuracy, but the remarkable aspect is, the loss for the training set and validation do not show a gap, this indicates there is no overt-fit. The fact that the model didn’t reach a higher accuracy is due to the depth of the network.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cb65444f1d5c96958f2bfefe77cf3ae7983f0793
62,219
ipynb
Jupyter Notebook
ipynb/ParticleInMultiD.ipynb
PaulWAyers/IntroQChemProblems
0491272e0b8e71059e601537b196181ab6b367cd
[ "CC0-1.0" ]
6
2021-01-16T15:35:43.000Z
2022-01-17T17:43:32.000Z
ipynb/ParticleInMultiD.ipynb
PaulWAyers/IntroQChemProblems
0491272e0b8e71059e601537b196181ab6b367cd
[ "CC0-1.0" ]
null
null
null
ipynb/ParticleInMultiD.ipynb
PaulWAyers/IntroQChemProblems
0491272e0b8e71059e601537b196181ab6b367cd
[ "CC0-1.0" ]
6
2021-01-29T16:30:34.000Z
2022-03-03T08:41:47.000Z
61.481225
9,290
0.612208
[ [ [ "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Multi-dimensional-Particle-in-a-Box\" data-toc-modified-id=\"Multi-dimensional-Particle-in-a-Box-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Multi-dimensional Particle-in-a-Box</a></span><ul class=\"toc-item\"><li><span><a href=\"#🥅-Learning-Objectives\" data-toc-modified-id=\"🥅-Learning-Objectives-4.1\"><span class=\"toc-item-num\">4.1&nbsp;&nbsp;</span>🥅 Learning Objectives</a></span></li><li><span><a href=\"#The-2-Dimensional-Particle-in-a-Box\" data-toc-modified-id=\"The-2-Dimensional-Particle-in-a-Box-4.2\"><span class=\"toc-item-num\">4.2&nbsp;&nbsp;</span>The 2-Dimensional Particle-in-a-Box</a></span></li><li><span><a href=\"#📝-Exercise:-Verify-the-above-equation-for-the-energy-eigenvalues-of-a-particle-confined-to-a-rectangular-box.\" data-toc-modified-id=\"📝-Exercise:-Verify-the-above-equation-for-the-energy-eigenvalues-of-a-particle-confined-to-a-rectangular-box.-4.3\"><span class=\"toc-item-num\">4.3&nbsp;&nbsp;</span>📝 Exercise: Verify the above equation for the energy eigenvalues of a particle confined to a rectangular box.</a></span></li><li><span><a href=\"#Separation-of-Variables\" data-toc-modified-id=\"Separation-of-Variables-4.4\"><span class=\"toc-item-num\">4.4&nbsp;&nbsp;</span>Separation of Variables</a></span></li><li><span><a href=\"#📝-Exercise:-By-direct-substitution,-verify-that-the-above-expressions-for-the-eigenvalues-and-eigenvectors-of-a-Hamiltonian-sum-are-correct.\" data-toc-modified-id=\"📝-Exercise:-By-direct-substitution,-verify-that-the-above-expressions-for-the-eigenvalues-and-eigenvectors-of-a-Hamiltonian-sum-are-correct.-4.5\"><span class=\"toc-item-num\">4.5&nbsp;&nbsp;</span>📝 Exercise: By direct substitution, verify that the above expressions for the eigenvalues and eigenvectors of a Hamiltonian-sum are correct.</a></span></li><li><span><a href=\"#Degenerate-States\" data-toc-modified-id=\"Degenerate-States-4.6\"><span class=\"toc-item-num\">4.6&nbsp;&nbsp;</span>Degenerate States</a></span></li><li><span><a href=\"#Electrons-in-a-3-dimensional-box-(cuboid)\" data-toc-modified-id=\"Electrons-in-a-3-dimensional-box-(cuboid)-4.7\"><span class=\"toc-item-num\">4.7&nbsp;&nbsp;</span>Electrons in a 3-dimensional box (cuboid)</a></span></li><li><span><a href=\"#📝-Exercise:-Verify-the-expressions-for-the-eigenvalues-and-eigenvectors-of-a-particle-in-a-cuboid.\" data-toc-modified-id=\"📝-Exercise:-Verify-the-expressions-for-the-eigenvalues-and-eigenvectors-of-a-particle-in-a-cuboid.-4.8\"><span class=\"toc-item-num\">4.8&nbsp;&nbsp;</span>📝 Exercise: Verify the expressions for the eigenvalues and eigenvectors of a particle in a cuboid.</a></span></li><li><span><a href=\"#📝-Exercise:-Construct-an-accidentally-degenerate-state-for-the-particle-in-a-cuboid.\" data-toc-modified-id=\"📝-Exercise:-Construct-an-accidentally-degenerate-state-for-the-particle-in-a-cuboid.-4.9\"><span class=\"toc-item-num\">4.9&nbsp;&nbsp;</span>📝 Exercise: Construct an accidentally degenerate state for the particle-in-a-cuboid.</a></span></li><li><span><a href=\"#Particle-in-a-circle\" data-toc-modified-id=\"Particle-in-a-circle-4.10\"><span class=\"toc-item-num\">4.10&nbsp;&nbsp;</span>Particle-in-a-circle</a></span><ul class=\"toc-item\"><li><span><a href=\"#The-Schrödinger-equation-for-a-particle-confined-to-a-circular-disk.\" data-toc-modified-id=\"The-Schrödinger-equation-for-a-particle-confined-to-a-circular-disk.-4.10.1\"><span class=\"toc-item-num\">4.10.1&nbsp;&nbsp;</span>The Schrödinger equation for a particle confined to a circular disk.</a></span></li><li><span><a href=\"#The-Schrödinger-Equation-in-Polar-Coordinates\" data-toc-modified-id=\"The-Schrödinger-Equation-in-Polar-Coordinates-4.10.2\"><span class=\"toc-item-num\">4.10.2&nbsp;&nbsp;</span>The Schrödinger Equation in Polar Coordinates</a></span></li><li><span><a href=\"#The-Angular-Schrödinger-equation-in-Polar-Coordinates\" data-toc-modified-id=\"The-Angular-Schrödinger-equation-in-Polar-Coordinates-4.10.3\"><span class=\"toc-item-num\">4.10.3&nbsp;&nbsp;</span>The Angular Schrödinger equation in Polar Coordinates</a></span></li><li><span><a href=\"#The-Radial-Schrödinger-equation-in-Polar-Coordinates\" data-toc-modified-id=\"The-Radial-Schrödinger-equation-in-Polar-Coordinates-4.10.4\"><span class=\"toc-item-num\">4.10.4&nbsp;&nbsp;</span>The Radial Schrödinger equation in Polar Coordinates</a></span></li><li><span><a href=\"#The-Radial-Schrödinger-Equation-for-a-Particle-Confined-to-a-Circular-Disk\" data-toc-modified-id=\"The-Radial-Schrödinger-Equation-for-a-Particle-Confined-to-a-Circular-Disk-4.10.5\"><span class=\"toc-item-num\">4.10.5&nbsp;&nbsp;</span>The Radial Schrödinger Equation for a Particle Confined to a Circular Disk</a></span></li><li><span><a href=\"#Eigenvalues-and-Eigenfunctions-for-a-Particle-Confined-to-a-Circular-Disk\" data-toc-modified-id=\"Eigenvalues-and-Eigenfunctions-for-a-Particle-Confined-to-a-Circular-Disk-4.10.6\"><span class=\"toc-item-num\">4.10.6&nbsp;&nbsp;</span>Eigenvalues and Eigenfunctions for a Particle Confined to a Circular Disk</a></span></li></ul></li><li><span><a href=\"#Particle-in-a-Spherical-Ball\" data-toc-modified-id=\"Particle-in-a-Spherical-Ball-4.11\"><span class=\"toc-item-num\">4.11&nbsp;&nbsp;</span>Particle-in-a-Spherical Ball</a></span><ul class=\"toc-item\"><li><span><a href=\"#The-Schrödinger-equation-for-a-particle-confined-to-a-spherical-ball\" data-toc-modified-id=\"The-Schrödinger-equation-for-a-particle-confined-to-a-spherical-ball-4.11.1\"><span class=\"toc-item-num\">4.11.1&nbsp;&nbsp;</span>The Schrödinger equation for a particle confined to a spherical ball</a></span></li><li><span><a href=\"#The-Schrödinger-Equation-in-Spherical-Coordinates\" data-toc-modified-id=\"The-Schrödinger-Equation-in-Spherical-Coordinates-4.11.2\"><span class=\"toc-item-num\">4.11.2&nbsp;&nbsp;</span>The Schrödinger Equation in Spherical Coordinates</a></span></li><li><span><a href=\"#The-Angular-Wavefunction-in-Spherical-Coordinates\" data-toc-modified-id=\"The-Angular-Wavefunction-in-Spherical-Coordinates-4.11.3\"><span class=\"toc-item-num\">4.11.3&nbsp;&nbsp;</span>The Angular Wavefunction in Spherical Coordinates</a></span></li><li><span><a href=\"#The-Radial-Schrödinger-equation-in-Spherical-Coordinates\" data-toc-modified-id=\"The-Radial-Schrödinger-equation-in-Spherical-Coordinates-4.11.4\"><span class=\"toc-item-num\">4.11.4&nbsp;&nbsp;</span>The Radial Schrödinger equation in Spherical Coordinates</a></span></li></ul></li><li><span><a href=\"#📝-Exercise:-Use-the-equation-for-the-zeros-of-$\\sin-x$-to-write-the-wavefunction-and-energy-for-the-one-dimensional-particle-in-a-box-in-a-form-similar-to-the-expressions-for-the-particle-in-a-disk-and-the-particle-in-a-sphere.\" data-toc-modified-id=\"📝-Exercise:-Use-the-equation-for-the-zeros-of-$\\sin-x$-to-write-the-wavefunction-and-energy-for-the-one-dimensional-particle-in-a-box-in-a-form-similar-to-the-expressions-for-the-particle-in-a-disk-and-the-particle-in-a-sphere.-4.12\"><span class=\"toc-item-num\">4.12&nbsp;&nbsp;</span>📝 Exercise: Use the equation for the zeros of $\\sin x$ to write the wavefunction and energy for the one-dimensional particle-in-a-box in a form similar to the expressions for the particle-in-a-disk and the particle-in-a-sphere.</a></span><ul class=\"toc-item\"><li><span><a href=\"#Solutions-to-the-Schrödinger-Equation-for-a-Particle-Confined-to-a-Spherical-Ball\" data-toc-modified-id=\"Solutions-to-the-Schrödinger-Equation-for-a-Particle-Confined-to-a-Spherical-Ball-4.12.1\"><span class=\"toc-item-num\">4.12.1&nbsp;&nbsp;</span>Solutions to the Schrödinger Equation for a Particle Confined to a Spherical Ball</a></span></li></ul></li><li><span><a href=\"#📝-Exercise:-For-the-hydrogen-atom,-the-2s-orbital-($n=2$,-$l=0$)-and-2p-orbitals-($n=2$,$l=1$,$m_l=-1,0,1$)-have-the-same-energy.-Is-this-true-for-the-particle-in-a-ball?\" data-toc-modified-id=\"📝-Exercise:-For-the-hydrogen-atom,-the-2s-orbital-($n=2$,-$l=0$)-and-2p-orbitals-($n=2$,$l=1$,$m_l=-1,0,1$)-have-the-same-energy.-Is-this-true-for-the-particle-in-a-ball?-4.13\"><span class=\"toc-item-num\">4.13&nbsp;&nbsp;</span>📝 Exercise: For the hydrogen atom, the 2s orbital ($n=2$, $l=0$) and 2p orbitals ($n=2$,$l=1$,$m_l=-1,0,1$) have the same energy. Is this true for the particle-in-a-ball?</a></span></li><li><span><a href=\"#🪞-Self-Reflection\" data-toc-modified-id=\"🪞-Self-Reflection-4.14\"><span class=\"toc-item-num\">4.14&nbsp;&nbsp;</span>🪞 Self-Reflection</a></span></li><li><span><a href=\"#🤔-Thought-Provoking-Questions\" data-toc-modified-id=\"🤔-Thought-Provoking-Questions-4.15\"><span class=\"toc-item-num\">4.15&nbsp;&nbsp;</span>🤔 Thought-Provoking Questions</a></span></li><li><span><a href=\"#🔁-Recapitulation\" data-toc-modified-id=\"🔁-Recapitulation-4.16\"><span class=\"toc-item-num\">4.16&nbsp;&nbsp;</span>🔁 Recapitulation</a></span></li><li><span><a href=\"#🔮-Next-Up...\" data-toc-modified-id=\"🔮-Next-Up...-4.17\"><span class=\"toc-item-num\">4.17&nbsp;&nbsp;</span>🔮 Next Up...</a></span></li><li><span><a href=\"#📚-References\" data-toc-modified-id=\"📚-References-4.18\"><span class=\"toc-item-num\">4.18&nbsp;&nbsp;</span>📚 References</a></span></li></ul></li></ul></div>", "_____no_output_____" ], [ "# Multi-dimensional Particle-in-a-Box\n![Particles in 2D confinement](https://github.com/PaulWAyers/IntroQChem/blob/main/linkedFiles/MVZL4.jpg?raw=true \"Particles in various types of 2-dimensional confinement\")\n\n## 🥅 Learning Objectives\n- Hamiltonian for a two-dimensional particle-in-a-box\n- Hamiltonian for a three-dimensional particle-in-a-box\n- Hamiltonian for a 3-dimensional spherical box\n- Separation of variables\n- Solutions for the 2- and 3- dimensional particle-in-a-box (rectangular)\n- Solutions for the 3-dimensional particle in a box (spherical)\n- Expectation values", "_____no_output_____" ], [ "## The 2-Dimensional Particle-in-a-Box\n![Particles in a 2-dimensional box](https://github.com/PaulWAyers/IntroQChem/blob/main/linkedFiles/1024px-Particle2D.svg.png?raw=true \"Particles in 2-dimensional box with nx=ny=2; image from wikipedia courtesy of Keenan Pepper\")\nWe have treated the particle in a one-dimensional box, where the (time-independent) Schr&ouml;dinger equation was:\n$$ \n\\left(-\\frac{\\hbar^2}{2m} \\frac{d^2}{dx^2} + V(x) \\right)\\psi_n(x) = E_n \\psi_n(x)\n$$\nwhere \n$$\nV(x) = \n\\begin{cases}\n +\\infty & x\\leq 0\\\\\n 0 & 0\\lt x \\lt a\\\\\n +\\infty & a \\leq x\n\\end{cases}\n$$\n\nHowever, electrons really move in three dimensions. However, just as sometimes electrons are (essentially) confined to one dimension, sometimes they are effectively confined to two dimensions. If the confinement is to a rectangle with side-widths $a_x$ and $a_y$, then the Schr&ouml;dinger equation is:\n$$ \n\\left(-\\frac{\\hbar^2}{2m} \\frac{d^2}{dx^2} -\\frac{\\hbar^2}{2m} \\frac{d^2}{dy^2} + V(x,y) \\right)\\psi_{n_x,n_y}(x,y) = E_{n_x,n_y} \\psi_{n_x,n_y}(x,y)\n$$\nwhere \n$$\nV(x,y) = \n\\begin{cases}\n +\\infty & x\\leq 0 \\text{ or }y\\leq 0 \\\\\n 0 & 0\\lt x \\lt a_x \\text{ and } 0 \\lt y \\lt a_y \\\\\n +\\infty & a_x \\leq x \\text{ or } a_y \\leq y\n\\end{cases}\n$$\nThe first thing to notice is that there are now two quantum numbers, $n_x$ and $n_y$. \n> The number of quantum numbers that are needed to label the state of a system is equal to its dimensionality.\n\nThe second thing to notice is that the Hamiltonian in this Schr&ouml;dinger equation can be written as the sum of two Hamiltonians,\n$$ \n\\left[\\left(-\\frac{\\hbar^2}{2m} \\frac{d^2}{dx^2} + V_x(x) \\right)\n+\\left(-\\frac{\\hbar^2}{2m} \\frac{d^2}{dy^2} + V_y(y) \\right) \\right]\\psi_{n_x,n_y}(x,y) = E_{n_x,n_y} \\psi_{n_x,n_y}(x,y)\n$$\nwhere \n$$\nV_x(x) = \n\\begin{cases}\n +\\infty & x\\leq 0\\\\\n 0 & 0\\lt x \\lt a_x\\\\\n +\\infty & a_x \\leq x\n\\end{cases} \\\\\nV_y(y) = \n\\begin{cases}\n +\\infty & y\\leq 0\\\\\n 0 & 0\\lt y \\lt a_y\\\\\n +\\infty & a_y \\leq y\n\\end{cases}\n$$\nBy the same logic as we used for the 1-dimensional particle in a box, we can deduce that the ground-state wavefunction for an electron in a rectangular box is:\n$$\n\\psi_{n_x n_y}(x,y) = \\frac{2}{\\sqrt{a_x a_y}} \\sin\\left(\\tfrac{n_x \\pi x}{a_x}\\right) \\sin\\left(\\tfrac{n_y \\pi y}{a_y}\\right) \\qquad \\qquad n_x=1,2,3,\\ldots;n_y=1,2,3,\\ldots\n$$\nThe corresponding energy is thus:\n$$\nE_{n_x n_y} = \\frac{h^2}{8m}\\left(\\frac{n_x^2}{a_x^2}+\\frac{n_y^2}{a_y^2}\\right)\\qquad \\qquad n_x,n_y=1,2,3,\\ldots\n$$", "_____no_output_____" ], [ "## &#x1f4dd; Exercise: Verify the above equation for the energy eigenvalues of a particle confined to a rectangular box.", "_____no_output_____" ], [ "## Separation of Variables\nThe preceding solution is a very special case of a general approach called separation of variables. \n> Given a $D$-dimensional Hamiltonian that is a sum of independent terms, \n$$\n\\hat{H}(x_1,x_2,\\ldots,x_D) = \\sum_{d=1}^D\\hat{H}_d(x_d)\n$$\nwhere the solutions to the individual Schr&ouml;dinger equations are known:\n$$\n\\hat{H}_d \\psi_{d;n_d}(x_d) = E_{d;n_d} \\psi_{d;n_d}(x_d)\n$$\nthe solution to the $D$-dimensional Schr&ouml;dinger equation is\n$$\n\\hat{H}(x_1,x_2,\\ldots,x_D) \\Psi_{n_1,n_2,\\ldots,n_D}(x_1,x_2,\\ldots,x_D) = E_{n_1,n_2,\\ldots,n_D}\\Psi_{n_1,n_2,\\ldots,n_D}(x_1,x_2,\\ldots,x_D)\n$$\nwhere the $D$-dimensional eigenfunctions are products of the Schr&ouml;dinger equations of the individual terms\n$$\n\\Psi_{n_1,n_2,\\ldots,n_D}(x_1,x_2,\\ldots,x_D) = \\prod_{d=1}^D\\psi_{d;n_d}(x_d)\n$$\nand the $D$-dimensional eigenvalues are sums of the eigenvalues of the individual terms,\n$$\nE_{n_1,n_2,\\ldots,n_D} = \\sum_{d=1}^D E_{d;n_d}\n$$\n\nThis expression can be verified by direct substitution. Interpretatively, in a Hamiltonian with the form \n$$\n\\hat{H}(x_1,x_2,\\ldots,x_D) = \\sum_{d=1}^D\\hat{H}_d(x_d)\n$$\nthe coordinates $x_1,x_2,\\ldots,x_D$ are all independent, because there are no terms that couple them together in the Hamiltonian. This means that the probability of observing a particle with values $x_1,x_2,\\ldots,x_D$ are all independent. Recall that when probabilities are independent, they are multiplied together. E.g., if the probability that your impoverished professor will be paid today is independent of the probability that will rain today, then \n$$\np_{\\text{paycheck + rain}} = p_{\\text{paycheck}} p_{\\text{rain}}\n$$\nSimilarly, because $x_1,x_2,\\ldots,x_D$ are all independent,\n$$\np(x_1,x_2,\\ldots,x_D) = p_1(x_1) p_2(x_2) \\ldots p_D(x_D)\n$$\nOwing to the Born postulate, the probability distribution function for observing a particle at $x_1,x_2,\\ldots,x_D$ is the wavefunction squared, so \n$$\n\\left| \\Psi_{n_1,n_2,\\ldots,n_D}(x_1,x_2,\\ldots,x_D)\\right|^2 = \\prod_{d=1}^D \\left| \\psi_{d;n_d}(x_d) \\right|^2\n$$\nIt is reassuring that the separation-of-independent-variables solution to the $D$-dimensional Schr&ouml;dinger equation reproduces this intuitive conclusion.", "_____no_output_____" ], [ "## &#x1f4dd; Exercise: By direct substitution, verify that the above expressions for the eigenvalues and eigenvectors of a Hamiltonian-sum are correct.", "_____no_output_____" ], [ "## Degenerate States\nWhen two quantum states have the same energy, they are said to be degenerate. For example, for a square box, where $a_x = a_y = a$, the states with $n_x=1; n_y=2$ and $n_x=2;n_y=1$ are degenerate because:\n$$\nE_{1,2} = \\frac{h^2}{8ma^2}\\left(1+4\\right) = \\frac{h^2}{8ma^2}\\left(4+1\\right) = E_{2,1}\n$$\nThis symmetry reflects physical symmetry, whereby the $x$ and $y$ coordinates are equivalent. The state with energy $E=\\frac{5h^2}{8ma^2}$ is said to be two-fold degenerate, or to have degeneracy of two. \n\nFor the particle in a square box, degeneracies of all levels exist. An example of a three-fold degeneracy is:\n$$\nE_{1,7} = E_{7,1} = E_{5,5} = \\frac{50h^2}{8ma^2}\n$$\nand an example of a four-fold degeneracy is: \n$$\nE_{1,8} = E_{8,1} = E_{7,4} = E_{4,7} = \\frac{65h^2}{8ma^2}\n$$\nIt isn't trivial to show that degeneracies of all orders are possible (it's tied up in the theory of [Diophantine equations](https://en.wikipedia.org/wiki/Diophantine_equation)), but perhaps it becomes plausible by giving an example with an eight-fold degeneracy:\n$$\nE_{8,49} = E_{49,8} = E_{16,47} = E_{47,16} = E_{23,44} = E_{44,23} = E_{28,41} = E_{41,28} = \\frac{2465 h^2}{8ma^2}\n$$\n\nNotice that all of these degeneracies are removed if the symmetry of the box is broken. For example, if a slight change of the box changes it from square to rectangulary, $a_x \\rightarrow a_x + \\delta x$, then the aforementioned states have different energies. This doesn't mean, however, that rectangular boxes do not have degeneracies. If $\\tfrac{a_x}{a_y}$ is a rational number, $\\tfrac{p}{q}$, then there will be an *accidental* degeneracies when $n_x$ is divisible by $p$ and $n_y$ is divisible by $q$. For example, if $a_x = 2a$ and $a_y = 3a$ (so $p=2$ and $q=3$), there is a degeneracy associated with \n$$\nE_{4,3} = \\frac{h^2}{8m}\\left(\\frac{4^2}{(2a)^2}+\\frac{3^2}{(3a)^2}\\right) \n= \\frac{h^2}{8m}\\left(\\frac{2^2}{(2a)^2}+\\frac{6^2}{(3a)^2}\\right) = \\frac{5h^2}{8ma^2}= E_{2,6}\n$$\nThis is called an *accidental* degeneracy because it is not related to a symmetry of the system, like the $x \\sim y$ symmetry that induces the degeneracy in the case of particles in a square box. ", "_____no_output_____" ], [ "## Electrons in a 3-dimensional box (cuboid)\n![Particles in a 3-dimensional box](https://github.com/PaulWAyers/IntroQChem/blob/main/linkedFiles/Particle3Dbox.png?raw=true \"Particles in 3-dimensional box; image from Gary Drobny's online notes at Univ. of Washington\")\n\nSuppose that particles are confined to a [cuboid](https://en.wikipedia.org/wiki/Cuboid) (or rectangular prism) with side-lengths $a_x$, $a_y$, and $a_z$. Then the Schr&ouml;dinger equation is:\n$$ \n\\left[-\\frac{\\hbar^2}{2m}\\left( \\frac{d^2}{dx^2} + \\frac{d^2}{dy^2} + \\frac{d^2}{dz^2} \\right) + V(x,y,z) \\right]\\psi_{n_x,n_y,n_z}(x,y,z) = E_{n_x,n_y,n_z} \\psi_{n_x,n_y,n_z}(x,y,z)\n$$\nwhere \n$$\nV(x,y,z) = \n\\begin{cases}\n +\\infty & x\\leq 0 \\text{ or }y\\leq 0 \\text{ or }z\\leq 0 \\\\\n 0 & 0\\lt x \\lt a_x \\text{ and } 0 \\lt y \\lt a_y \\text{ and } 0 \\lt z \\lt a_z \\\\\n +\\infty & a_x \\leq x \\text{ or } a_y \\leq y \\text{ or } a_z \\leq z\n\\end{cases}\n$$\nThere are three quantum numbers because the system is three-dimensional. \n\nThe three-dimensional second derivative is called the Laplacian, and is denoted \n$$\n\\nabla^2 = \\frac{d^2}{dx^2} + \\frac{d^2}{dy^2} + \\frac{d^2}{dz^2} = \\nabla \\cdot \\nabla\n$$\nwhere \n$$\n\\nabla = \\left[ \\frac{d}{dx}, \\frac{d}{dy}, \\frac{d}{dz} \\right]^T\n$$\nis the operator that defines the gradient vector. The 3-dimensional momentum operator is \n$$\n\\hat{\\mathbf{p}} = i \\hbar \\nabla\n$$\nwhich explains why the kinetic energy is given by\n$$\n\\hat{T} = \\frac{\\hat{\\mathbf{p}} \\cdot \\hat{\\mathbf{p}}}{2m} = \\frac{\\hbar^2}{2m} \\nabla^2\n$$\n\nAs with the 2-dimensional particle-in-a-rectangle, the 3-dimensional particle-in-a-cuboid can be solved by separation of variables. Rewriting the Schr&ouml;dinger equation as:\n$$ \n\\left[\\left(-\\frac{\\hbar^2}{2m} \\frac{d^2}{dx^2} + V_x(x) \\right)\n+\\left(-\\frac{\\hbar^2}{2m} \\frac{d^2}{dy^2} + V_y(y) \\right) \n+\\left(-\\frac{\\hbar^2}{2m} \\frac{d^2}{dz^2} + V_z(z) \\right) \\right]\\psi_{n_x,n_y,n_z}(x,y,z) = E_{n_x,n_y,n_z} \\psi_{n_x,n_y,n_z}(x,y,z)\n$$\nwhere \n$$\nV_x(x) = \n\\begin{cases}\n +\\infty & x\\leq 0\\\\\n 0 & 0\\lt x \\lt a_x\\\\\n +\\infty & a_x \\leq x\n\\end{cases} \\\\\nV_y(y) = \n\\begin{cases}\n +\\infty & y\\leq 0\\\\\n 0 & 0\\lt y \\lt a_y\\\\\n +\\infty & a_y \\leq y\n\\end{cases} \\\\\nV_z(z) = \n\\begin{cases}\n +\\infty & z\\leq 0\\\\\n 0 & 0\\lt z \\lt a_z\\\\\n +\\infty & a_z \\leq z\n\\end{cases} \n$$\nBy the same logic as we used for the 1-dimensional particle in a box, we can deduce that the ground-state wavefunction for an electron in a cuboid is:\n$$\n\\psi_{n_x n_y n_z}(x,y,z) = \\frac{2\\sqrt{2}}{\\sqrt{a_x a_y z_z}} \\\n\\sin\\left(\\tfrac{n_x \\pi x}{a_x}\\right) \\sin\\left(\\tfrac{n_y \\pi y}{a_y}\\right)\\sin\\left(\\tfrac{n_z \\pi z}{a_z}\\right) \\qquad \\qquad n_x=1,2,3,\\ldots;n_y=1,2,3,\\ldots;n_z=1,2,3,\\ldots\n$$\nThe corresponding energy is thus:\n$$\nE_{n_x n_y n_z} = \\frac{h^2}{8m}\\left(\\frac{n_x^2}{a_x^2}+\\frac{n_y^2}{a_y^2}+\\frac{n_z^2}{a_z^2}\\right)\\qquad \\qquad n_x,n_y,n_z=1,2,3,\\ldots\n$$\n\nAs before, especially when there is symmetry, there are many degenerate states. For example, for a particle-in-a-cube, where $a_x = a_y = a_z = a$, the first excited state is three-fold degenerate since:\n$$\nE_{2,1,1} = E_{1,2,1} = E_{1,1,2} = \\frac{6h^2}{8ma^2}\n$$\nThere are other states of even higher degeneracy. For example, there is a twelve-fold degenerate state:\n$$\nE_{5,8,15} = E_{5,15,8} = E_{8,5,15} = E_{8,15,5} = E_{15,5,8} = E_{15,8,5} = E_{3,4,17} = E_{3,17,4} = E_{4,3,17} = E_{4,17,3} = E_{17,3,4} = E_{17,4,3} = \\frac{314 h^2}{8ma^2}\n$$", "_____no_output_____" ], [ "## &#x1f4dd; Exercise: Verify the expressions for the eigenvalues and eigenvectors of a particle in a cuboid.", "_____no_output_____" ], [ "## &#x1f4dd; Exercise: Construct an accidentally degenerate state for the particle-in-a-cuboid. \n(Hint: this is a lot easier than you may think.)", "_____no_output_____" ], [ "## Particle-in-a-circle\n### The Schr&ouml;dinger equation for a particle confined to a circular disk.\n![Particle in a Ring](https://github.com/PaulWAyers/IntroQChem/blob/main/linkedFiles/The_Well_(Quantum_Corral).jpg?raw=true \"The states of particle confined by a ring of atoms (a quantum corral) is similar to a particle-in-acircle. Image licensed CC-SA by Julian Voss-Andreae\")\n\nWhat happens if instead of being confined to a rectangle or a cuboid, the electrons were confined to some other shape? For example, it is not uncommon to have electrons confined in a circular disk ([quantum corral](https://en.wikipedia.org/wiki/Quantum_mirage)) or a sphere ([quantum dot](https://en.wikipedia.org/wiki/Quantum_dot)). It is relatively easy to write the Hamiltonian in these cases, but less easy to solve it because Cartesian (i.e., $x,y,z$) coordinates are less natural for these geometries. \n\nThe Schr&ouml;dinger equation for a particle confined to a circular disk of radius $a$ is:\n$$ \n\\left(-\\frac{\\hbar^2}{2m} \\nabla^2 + V(x,y) \\right)\\psi(x,y) = E \\psi(x,y)\n$$\nwhere \n$$\nV(x,y) = \n\\begin{cases}\n 0 & \\sqrt{x^2 + y^2} \\lt a\\\\\n +\\infty & a \\leq \\sqrt{x^2 + y^2}\n\\end{cases}\n$$\nHowever, it is more useful to write this in polar coordinates (i.e., $r,\\theta$): \n\\begin{align}\nx &= r \\cos \\theta \\\\\ny &= r \\sin \\theta \\\\\n\\\\\nr &= \\sqrt{x^2 + y^2} \\\\\n\\theta &= \\arctan{\\tfrac{y}{x}}\n\\end{align}\nbecause the potential depends only on the distance from the center of the system, \n$$ \n\\left(-\\frac{\\hbar^2}{2m} \\nabla^2 + V(r) \\right)\\psi(r,\\theta) = E \\psi(r,\\theta)\n$$\nwhere \n$$\nV(r) = \n\\begin{cases}\n 0 & r \\lt a\\\\\n +\\infty & a \\leq r\n\\end{cases}\n$$", "_____no_output_____" ], [ "### The Schr&ouml;dinger Equation in Polar Coordinates\nIn order to solve this Schr&ouml;dinger equation, we need to rewrite the Laplacian, $\\nabla^2 = \\frac{d^2}{dx^2} + \\frac{d^2}{dy^2}$ in polar coordinates. Deriving the Laplacian in alternative coordinate systems is a standard (and tedious) exercise that you hopefully saw in your calculus class. (If not, cf. [wikipedia](https://en.wikipedia.org/wiki/Laplace_operator) or this [meticulous derivation](https://www.math.ucdavis.edu/~saito/courses/21C.w11/polar-lap.pdf).) The result is that: \n$$\n\\nabla^2 = \\frac{d^2}{dr^2} + \\frac{1}{r} \\frac{d}{dr} + \\frac{1}{r^2}\\frac{d^2}{d\\theta^2}\n$$\nThe resulting Schr&ouml;dinger equation is,\n$$\n\\left[-\\frac{\\hbar^2}{2m} \\left(\\frac{d^2}{dr^2} + \\frac{1}{r} \\frac{d}{dr} + \\frac{1}{r^2}\\frac{d^2}{d\\theta^2} \\right)+ V(r) \\right] \\psi(r,\\theta) = E \\psi(r,\\theta)\n$$\n\nThis looks like it might be amenable to solution by separation of variables insofar as the potential doesn't compute the radial and angular positions of the particles, and the kinetic energy doesn't couple the particles angular and radial momenta (i.e., the derivatives). So we propose the solution $\\psi(r,\\theta) = R(r) \\Theta(\\theta)$. Substituting this into the Schr&ouml;dinger equation, we obtain:\n\\begin{align}\n\\left[-\\frac{\\hbar^2}{2m} \\left(\\frac{d^2}{dr^2} + \\frac{1}{r} \\frac{d}{dr} + \\frac{1}{r^2}\\frac{d^2}{d\\theta^2} \\right)+ V(r) \\right] R(r) \\Theta(\\theta) &= E R(r) \\Theta(\\theta) \\\\\n\\left[-\\Theta(\\theta)\\frac{\\hbar^2}{2m} \\left(\\frac{d^2 R(r)}{dr^2} + \\frac{1}{r} \\frac{d R(r)}{dr} \\right) -\\frac{\\hbar^2}{2m} \\frac{R(r)}{r^2}\\left(\\frac{d^2 \\Theta(\\theta)}{d \\theta^2} \\right) + V(r) R(r) \\Theta(\\theta) \\right] &= E R(r)\\Theta(\\theta)\n\\end{align}\nDividing both sides by $R(r) \\Theta(\\theta)$ and multiplying both sides by $r^2$ we obtain:\n$$\nE r^2 +\\frac{\\hbar^2}{2m}\\frac{r^2}{R(r)} \\left(\\frac{d^2 R(r)}{dr^2} + \\frac{1}{r} \\frac{d R(r)}{dr} \\right) - r^2 V(r)=-\\frac{\\hbar^2}{2m} \\frac{1}{\\Theta(\\theta)}\\left(\\frac{d^2 \\Theta(\\theta)}{d \\theta^2} \\right) \n$$\nThe right-hand-side depends only on $r$ and the left-hand-side depends only on $\\theta$; this can only be true for all $r$ and all $\\theta$ if both sides are equal to the same constant. This problem can therefore be solved by separation of variables, though it is a slightly different form from the one we considered previously.", "_____no_output_____" ], [ "### The Angular Schr&ouml;dinger equation in Polar Coordinates\nTo find the solution, we first solve the set the left-hand-side equal to a constant, which gives a 1-dimensional Schr&ouml;dinger equations for the angular motion of the particle around the circle,\n$$\n-\\frac{\\hbar^2}{2m} \\frac{d^2 \\Theta_l(\\theta)}{d \\theta^2} = E_{\\theta;l} \\Theta_l(\\theta)\n$$\nThis equation is identical to the particle-in-a-box, and has (unnormalized) solutions\n$$\n\\Theta_l(\\theta) = e^{i l \\theta} \\qquad \\qquad l = 0, \\pm 1, \\pm 2, \\ldots\n$$\nwhere $l$ must be an integer because otherwise the fact the periodicity of the wavefunction (i.e., that $\\Theta_l(\\theta) = \\Theta_l(\\theta + 2 k \\pi)$ for any integer $k$) is not achieved. Using the expression for $\\Theta_l(\\theta)$, the angular kinetic energy of the particle in a circle is seen to be:\n$$\nE_{\\theta,l} = \\tfrac{\\hbar^2 l^2}{2m}\n$$", "_____no_output_____" ], [ "### The Radial Schr&ouml;dinger equation in Polar Coordinates\nInserting the results for the angular wavefunction into the Schr&ouml;dinger equation, we obtain\n$$\nE r^2 +\\frac{\\hbar^2}{2m}\\frac{r^2}{R(r)} \\left(\\frac{d^2 R(r)}{dr^2} + \\frac{1}{r} \\frac{d R(r)}{dr} \\right) - r^2 V(r)=-\\frac{\\hbar^2}{2m} \\frac{1}{\\Theta_l(\\theta)}\\left(\\frac{d^2 \\Theta_l(\\theta)}{d \\theta^2} \\right) = \\frac{\\hbar^2 l^2}{2m}\n$$\nwhich can be rearranged into the radial Schr&ouml;dinger equation,\n$$\n-\\frac{\\hbar^2}{2m} \\left(\\frac{1}{r^2} \\frac{d^2}{dr^2} + \\frac{1}{r} \\frac{d}{dr} - \\frac{l^2}{r^2} \\right)R_{n,l}(r) + V(r) R_{n,l}(r) = E_{n,l} R_{n,l}(r)\n$$\nNotice that the radial eigenfunctions, $R_{n,l}(r)$, and the energy eigenvalues, $E_{n,l}$, depend on the angular motion of the particle, as quantized by $l$. The term $\\frac{\\hbar^2 l^2}{2mr^2}$ is exactly the centrifugal potential, indicating that it takes energy to hold a rotating particle in an orbit with radius $r$, and that the potential energy that is required grows with $r^{-2}$. Notice also that no assumptions have been made about the nature of the circular potential, $V(r)$. The preceding analysis holds for *any* circular-symmetric potential.", "_____no_output_____" ], [ "### The Radial Schr&ouml;dinger Equation for a Particle Confined to a Circular Disk\nFor the circular disk, where\n$$\nV(r) = \n\\begin{cases}\n 0 & r \\lt a\\\\\n +\\infty & a \\leq r\n\\end{cases}\n$$\nit is somewhat more convenient to rewrite the radial Schr&ouml;dinger equation as a [homogeneous linear differential equation](https://en.wikipedia.org/wiki/Homogeneous_differential_equation)\n$$\n-\\frac{\\hbar^2}{2m} \\left(r^2 \\frac{d^2 R_{n,l}(r)}{dr^2} + r \\frac{d R_{n,l}(r)}{dr} + \\left[\\left(\\frac{2m E_{n,l}}{\\hbar^2} \\right) r^2 - l^2\\right]R_{n,l}(r) \\right) + r^2 V(r) R_{n,l}(r) = 0\n$$\nUsing the specific form of the equation, we have that, for $0 \\lt r \\lt a$, \n$$\n-\\frac{\\hbar^2}{2m} \\left(r^2 \\frac{d^2 R_{n,l}(r)}{dr^2} + r \\frac{d R_{n,l}(r)}{dr} + \\left[\\left(\\frac{2m E_{n,l}}{\\hbar^2} \\right) r^2 - l^2\\right]R_{n,l}(r) \\right) = 0\n$$\nWhile this equation can be solved by the usual methods, that is [beyond the scope of this course](https://opencommons.uconn.edu/cgi/viewcontent.cgi?article=1013&context=chem_educ). However, we recognize that this equation is strongly resembles [Bessel's differential equation](https://en.wikipedia.org/wiki/Bessel_function),\n$$\nx^2 \\frac{d^2 f}{dx^2} + x \\frac{df}{dx} + \\left(x^2 - \\alpha^2 \\right) f(x) = 0\n$$\nThe solutions to Bessel's equation are called the *Bessel functions of the first kind* and denoted, $J_{\\alpha}(r)$. However, the radial wavefunction must vanish at the edge of the disk, $R_{n,l}(a) = 0$, and the Bessel functions generally do not satisfy this requirement. Recall that the boundary condition in the 1-dimensional particle in a box was satisfied by moving from the generic solution, $\\psi(x) \\propto \\sin(x)$ to the scaled solution, $\\psi(x) \\propto \\sin(k x)$, where $k=\\tfrac{2 \\pi}{a}$ was chosen to satisfy the boundary condition. Similarly, we write the solutions as $R_{n,l}(r) \\propto J_l(kr)$. Substituting this form into the Schr&ouml;dinger equation and using the fact that:\n$$\n(kr)^n \\frac{d^n}{d(kr)^n} = r^n \\frac{d^n}{dr^n} \\qquad \\qquad n=1,2,\\ldots \n$$\nwe have\n$$\n-\\frac{\\hbar^2}{2m} \\left((kr)^2 \\frac{d^2 J_{l}(kr)}{d(kr)^2} + (kr) \\frac{d J_{l}(kr)}{d(kr)} + \\left[\\left(\\frac{2m E_{n,l}}{k^2 \\hbar^2} \\right) (kr)^2 - l^2\\right]J_{l}(kr) \\right) = 0\n$$\nReferring back to the Bessel equation, it is clear that this equation is satisfied when \n$$\n\\frac{2m E_{n,l}}{k^2 \\hbar^2} = 1\n$$\nor, equivalently,\n$$\nE_{n,l} = \\frac{\\hbar^2 k^2}{2m}\n$$\nwhere $k$ is chosen so that $J_l(ka) = 0$. If we label the zeros of the Bessel functions,\n$$\nJ_l(x_{n,l}) = 0 \\qquad \\qquad n=1,2,3,\\ldots \\\\\nx_{1,l} \\lt x_{2,l} \\lt x_{3,l} \\lt \\cdots\n$$\nthen \n$$\nk_{n,l} = \\frac{x_{n,l}}{a}\n$$\nand the energies of the particle-in-a-disk are\n$$\nE_{n,l} = \\frac{\\hbar^2 x_{n,l}^2}{2ma^2} = \\frac{h^2 x_{n,l}^2}{8 m \\pi^2 a^2}\n$$\nand the eigenfunctions of the particle-in-a-disk are:\n$$\n\\psi_{n,l}(r,\\theta) \\propto J_{l}\\left(\\frac{x_{n,l}r}{a} \\right) e^{i l \\theta}\n$$\n", "_____no_output_____" ], [ "### Eigenvalues and Eigenfunctions for a Particle Confined to a Circular Disk\n![Vibrations of a Circular Drum-Head](https://upload.wikimedia.org/wikipedia/commons/b/bc/Vibrating_drum_Bessel_function.gif \"An eigenfunction of the Particle-in-a-Circle. CC-SA4 license by Sławomir Biały at English Wikipedia\")\nThe energies of a particle confined to a circular disk of radius $a$ are:\n$$\nE_{n,l} = \\frac{\\hbar^2 x_{n,l}^2}{2ma^2} = \\frac{h^2 x_{n,l}^2}{8 m \\pi^2 a^2} \\qquad \\qquad n=1,2,\\ldots; \\quad l=0,\\pm 1,\\pm 2, \\ldots\n$$\nand its eigenfunctions are:\n$$\n\\psi_{n,l}(r,\\theta) \\propto J_{l}\\left(\\frac{x_{n,l}r}{a} \\right) e^{i l \\theta}\n$$\nwhere $x_{n,l}$ are the zeros of the Bessel function, $J_l(x_{n,l}) = 0$. The first zero is $x_{1,0} = 2.4048$. These solutions are exactly the resonant energies and modes that are associated with the vibration of a circular drum whose membrane has uniform thickness/density. \n\nYou can find elegant video animations of the eigenvectors of the particle-in-a-circle at the following links:\n- [Interactive Demonstration of the States of a Particle-in-a-Circular-Disk](https://demonstrations.wolfram.com/ParticleInAnInfiniteCircularWell/)\n- [Movie animation of the quantum states of a particle-in-a-circular-disk](https://www.reddit.com/r/dataisbeautiful/comments/mfx5og/first_70_states_of_a_particle_trapped_in_a/?utm_source=share&utm_medium=web2x&context=3)\n\nA subtle result, [originally proposed by Bourget](https://en.wikipedia.org/wiki/Bessel_function#Bourget's_hypothesis), is that no two Bessel functions ever have the same zeros, which means that the values of $\\{x_{n,l} \\}$ are all distinct. A corollary of this is that eigenvalues of the particle confined to a circular disk are either nondegenerate ($l=0$) or doubly degenerate ($|l| /ge 1$). There are no accidental degeneracies for a particle in a circular disk. \n\nThe energies of an electron confined to a circular disk with radius $a$ Bohr are: \n$$\nE_{n,l} = \\tfrac{x_{n,l}^2}{2a^2}\n$$\nThe following code block computes these energies. ", "_____no_output_____" ] ], [ [ "\nfrom scipy import constants\nfrom scipy import special\nimport ipywidgets as widgets\nimport mpmath", "_____no_output_____" ], [ "#The next few lines just set up the sliders for setting parameters.\n#Principle quantum number slider:\nn = widgets.IntSlider(\n value=1,\n min=1,\n max=10,\n step=1,\n description='n (princ. #):',\n disabled=False,\n continuous_update=True,\n orientation='horizontal',\n readout=True,\n readout_format='d')\n\n#Angular quantum number slider:\nl = widgets.IntSlider(\n value=0,\n min=-10,\n max=10,\n step=1,\n description='l (ang. #):',\n disabled=False,\n continuous_update=True,\n orientation='horizontal',\n readout=True,\n readout_format='d')\n\n#Box length slider:\na = widgets.FloatSlider(\n value=1,\n min=.01,\n max=10.0,\n step=0.01,\n description='a (length):',\n disabled=False,\n continuous_update=True,\n orientation='horizontal',\n readout=True,\n readout_format='.2f',\n)\n\n# Define a function for the energy (in a.u.) of a particle in a circular disk\n# with length a, principle quantum number n, and angular quantum number l\n# The length is input in Bohr (atomic units).\ndef compute_energy_disk(n, l, a):\n \"Compute 1-dimensional particle-in-a-spherical-ball energy.\"\n #Compute the first n zeros of the Bessel function\n zeros = special.jn_zeros(l,n)\n #Compute the energy from the n-th zero.\n return (zeros[-1])**2/ (2 * a**2)\n\n#This next bit of code just prints out the energy in atomic units\ndef print_energy_disk(a, n, l):\n print(f'The energy of an electron confined to a disk with radius {a:.2f} a.u.,'\n f' principle quantum number {n}, and angular quantum number {l}'\n f' is {compute_energy_disk(n, l, a):.3f} a.u..')\n\nout = widgets.interactive_output(print_energy_disk, {'a': a, 'n': n, 'l': l})\n\nwidgets.VBox([widgets.VBox([a, n, l]),out]) ", "_____no_output_____" ] ], [ [ "## Particle-in-a-Spherical Ball\n\n### The Schr&ouml;dinger equation for a particle confined to a spherical ball\n![Quantum Dot](https://upload.wikimedia.org/wikipedia/commons/thumb/7/75/Colloidal_nanoparticle_of_lead_sulfide_%28selenide%29_with_complete_passivation.png/842px-Colloidal_nanoparticle_of_lead_sulfide_%28selenide%29_with_complete_passivation.png \"A quantum dot is a model for a particle spherically confined. CC-SA3 licensed by Zherebetskyy\")\n\nThe final model we will consider for now is a particle confined to a spherical ball with radius $a$,\n$$ \n\\left(-\\frac{\\hbar^2}{2m} \\nabla^2 + V(x,y,z) \\right)\\psi(x,y,z) = E \\psi(x,y,z)\n$$\nwhere \n$$\nV(x,y,z) = \n\\begin{cases}\n 0 & \\sqrt{x^2 + y^2 + z^2} \\lt a\\\\\n +\\infty & a \\leq \\sqrt{x^2 + y^2 + z^2}\n\\end{cases}\n$$\nHowever, it is more useful to write this in spherical polar coordinates (i.e., $r,\\theta, \\phi$): \n\\begin{align}\nx &= r \\sin \\theta \\cos \\phi\\\\\ny &= r \\sin \\theta \\sin \\phi\\\\\nz &= r cos \\theta \\\\\n\\\\\nr &= \\sqrt{x^2 + y^2 + z^2} \\\\\n\\theta &= \\arccos{\\tfrac{z}{r}} \\\\\n\\phi &= \\arctan{\\tfrac{y}{x}}\n\\end{align}\nbecause the potential depends only on the distance from the center of the system, \n$$ \n\\left(-\\frac{\\hbar^2}{2m} \\nabla^2 + V(r) \\right)\\psi(r,\\theta, \\phi) = E \\psi(r,\\theta, \\phi)\n$$\nwhere \n$$\nV(r) = \n\\begin{cases}\n 0 & r \\lt a\\\\\n +\\infty & a \\leq r\n\\end{cases}\n$$", "_____no_output_____" ], [ "### The Schr&ouml;dinger Equation in Spherical Coordinates\nIn order to solve the Schr&ouml;dinger equation for a particle in a spherical ball, we need to rewrite the Laplacian, $\\nabla^2 = \\frac{d^2}{dx^2} + \\frac{d^2}{dy^2} + \\frac{d^2}{dz^2}$ in polar coordinates. A meticulous derivation of the [Laplacian](https://en.wikipedia.org/wiki/Laplace_operator) and its [eigenfunctions](http://galileo.phys.virginia.edu/classes/252/Classical_Waves/Classical_Waves.html) The result is that: \n$$\n\\nabla^2 = \\frac{1}{r^2}\\frac{d}{dr}r^2\\frac{d}{dr} + \\frac{1}{r^2 \\sin \\theta}\\frac{d}{d\\theta}\\sin\\theta\\frac{d}{d\\theta} + \\frac{1}{r^2 \\sin^2 \\theta} \\frac{d^2}{d\\phi^2}\n$$\nwhich can be rewritten in a more familiar form as:\n$$\n\\nabla^2 = \\frac{d^2}{dr^2}+ \\frac{2}{r}\\frac{d}{dr} + \\frac{1}{r^2}\\left[\\frac{1}{\\sin \\theta}\\frac{d}{d\\theta}\\sin\\theta\\frac{d}{d\\theta} + \\frac{1}{\\sin^2 \\theta} \\frac{d^2}{d\\phi^2}\\right]\n$$\nInserting this into the Schr&ouml;dinger equation for a particle confined to a spherical potential, $V(r)$, one has:\n$$\n\\left({} -\\frac{\\hbar^2}{2m} \\left( \\frac{d^2}{dr^2}\n+ \\frac{2}{r} \\frac{d}{dr}\\right) \n - \\frac{\\hbar^2}{2mr^2}\\left[\\frac{1}{\\sin \\theta}\\frac{d}{d\\theta}\\sin\\theta\\frac{d}{d\\theta} \n+ \\frac{1}{\\sin^2 \\theta} \\frac{d^2}{d\\phi^2}\\right] \\\\ \n + V(r) \\right)\\psi_{n,l,m_l}(r,\\theta,\\phi) \n= E_{n,l,m_l}\\psi_{n,l,m_l}(r,\\theta,\\phi)\n$$\nThe solutions of the Schr&ouml;dinger equation are characterized by three quantum numbers because this equation is 3-dimensional.\n\nRecall that the classical equation for the kinetic energy of a set of points rotating around the origin, in spherical coordinates, is:\n$$\nT = \\sum_{i=1}^{N_{\\text{particles}}} \\frac{p_{r;i}^2}{2m_i} + \\frac{\\mathbf{L}_i \\cdot \\mathbf{L}_i}{2m_i r_i^2} \n$$\nwhere $p_{r,i}$ and $\\mathbf{L}_i$ are the radial and [angular momenta](https://en.wikipedia.org/wiki/Angular_momentum#In_Hamiltonian_formalism) of the $i^{\\text{th}}$ particle, respectively. It's apparent, then, that the quantum-mechanical operator for the square of the angular momentum is:\n$$\n\\hat{L}^2 = - \\hbar^2 \\left[\\frac{1}{\\sin \\theta}\\frac{d}{d\\theta}\\sin\\theta\\frac{d}{d\\theta} \n+ \\frac{1}{\\sin^2 \\theta} \\frac{d^2}{d\\phi^2}\\right]\n$$\n\nThe Schr&ouml;dinger equation for a spherically-symmetric system is thus,\n$$\n\\left(-\\frac{\\hbar^2}{2m} \\left( \\frac{d^2}{dr^2}\n+ \\frac{2}{r} \\frac{d}{dr}\\right) \n + \\frac{\\hat{L}^2}{2mr^2} + V(r) \\right)\n \\psi_{n,l,m_l}(r,\\theta,\\phi) \n= E_{n,l,m_l}\\psi_{n,l,m_l}(r,\\theta,\\phi)\n$$\n", "_____no_output_____" ], [ "### The Angular Wavefunction in Spherical Coordinates\n![Spherical Harmonics](https://upload.wikimedia.org/wikipedia/commons/thumb/6/62/Spherical_Harmonics.png/1024px-Spherical_Harmonics.png \"Representation of the real spherical harmonics, licensed CC-SA3 by Inigo.quilez\")\n\nThe Schr&ouml;dinger equation for a spherically-symmetric system can be solved by separation of variables. If one compares to the result in polar coordinates, it is already clear that the angular wavefunction has the form $\\Theta{\\theta,\\phi} = P(\\theta)e^{im_l\\phi}$. From this starting point we could deduce the eigenfunctions of $\\hat{L}^2$, but instead we will just present the eigenfunctions and eigenvalues,\n$$\n\\hat{L}^2 Y_l^{m_l} (\\theta, \\phi) = \\hbar^2 l(l+1)Y_l^{m_l} (\\theta, \\phi) \\qquad l=0,1,2,\\ldots m_l=0, \\pm 1, \\ldots, \\pm l\n$$\nThe functions [$Y_l^{m_l} (\\theta, \\phi)$](https://en.wikipedia.org/wiki/Spherical_harmonics) are called [spherical harmonics](https://mathworld.wolfram.com/SphericalHarmonic.html), and they are the fundamental vibrational modes of the surface of a spherical membrane. Note that these functions resemble s-orbitals ($l=0$), p-orbitals ($l=1$), d-orbitals ($l=2$), etc., and that the number of choices for $m_l$, $2l+1$, is equal to the number of $l$-type orbitals.\n", "_____no_output_____" ], [ "### The Radial Schr&ouml;dinger equation in Spherical Coordinates\nUsing separation of variables, we write the wavefunction as:\n$$\n\\psi_{n,l,m_l}(r,\\theta,\\phi) = R_{n,l}(r) Y_l^{m_l}(\\theta,\\phi) \n$$\nInserting this expression into the Schr&ouml;dinger equation, and exploiting the fact that the spherical harmonics are eigenfunctions of $\\hat{L}^2$, one obtains the radial Schr&ouml;dinger equation:\n$$\n\\left(-\\frac{\\hbar^2}{2m} \\left( \\frac{d^2}{dr^2}\n+ \\frac{2}{r} \\frac{d}{dr}\\right) \n + \\frac{\\hbar^2 l(l+1)}{2mr^2} + V(r) \\right)\n R_{n,l}(r) \n= E_{n,l}R_{n,l}(r)\n$$\n\nInside the sphere, $V(r) = 0$. Rearranging the radial Schr&ouml;dinger equation for the interior of the sphere as a homogeneous linear differential equation,\n$$\nr^2 \\frac{d^2R_{n,l}}{dr^2}\n+ 2r \\frac{dR_{n,l}}{dr}\n+ \\left( \\frac{2mr^2E_{n,l}}{\\hbar^2} - l(l+1) \\right)\n R_{n,l}(r) = 0\n$$\nThis equation strongly resembles the differential equations satisfied by the [spherical Bessel functions](https://en.wikipedia.org/wiki/Bessel_function#Spherical_Bessel_functions:_jn,_yn), $j_l(x)$\n$$\nx^2 \\frac{d^2 j_l}{dx^2} + 2x \\frac{dj_l}{dx} + \\left(x^2 - l(l+1) \\right)j_l(x) = 0\n$$\n\nThe spherical Bessel functions are eigenfunctions for the particle-in-a-spherical-ball, but do not satisfy the boundary condition that the wavefunction be zero on the sphere, $R_{n,l}(a) = 0$. To satisfy this constraint, we propose\n$$\nR_{n,l}(r) = j_l(k r)\n$$\nUsing this form in the radial Schr&ouml;dinger equation, we have\n$$\n(kr)^2 \\frac{d^2 j_l(kr)}{d(kr)^2}\n+ 2kr \\frac{d j_l(kr)}{d(kr)}\n+ \\left( \\frac{2m(kr)^2E_{n,l}}{\\hbar^2k^2} - l(l+1) \\right)\n j_l(kr) = 0\n$$\nReferring back to the differential equation satisfied by the spherical Bessel functions, it is clear that this equation is satisfied when \n$$\n\\frac{2m E_{n,l}}{k^2 \\hbar^2} = 1\n$$\nor, equivalently,\n$$\nE_{n,l} = \\frac{\\hbar^2 k^2}{2m}\n$$\nwhere $k$ is chosen so that $j_l(ka) = 0$. If we label the zeros of the spherical Bessel functions,\n$$\nj_l(y_{n,l}) = 0 \\qquad \\qquad n=1,2,3,\\ldots \\\\\ny_{1,l} \\lt y_{2,l} \\lt y_{3,l} \\lt \\cdots\n$$\nthen \n$$\nk_{n,l} = \\frac{y_{n,l}}{a}\n$$\nand the energies of the particle-in-a-ball are\n$$\nE_{n,l} = \\frac{\\hbar^2 y_{n,l}^2}{2ma^2} = \\frac{h^2 y_{n,l}^2}{8 m \\pi^2 a^2}\n$$\nand the eigenfunctions of the particle-in-a-ball are:\n$$\n\\psi_{n,l,m}(r,\\theta,\\phi) \\propto j_l\\left(\\frac{y_{n,l}r}{a} \\right) Y_l^{m_l}(\\theta, \\phi)\n$$\nNotice that the eigenenergies have the same form as those in the particle-in-a-disk and even the same as those for a particle-in-a-one-dimensional-box; the only difference is the identity of the function whose zeros we are considering.", "_____no_output_____" ], [ "## &#x1f4dd; Exercise: Use the equation for the zeros of $\\sin x$ to write the wavefunction and energy for the one-dimensional particle-in-a-box in a form similar to the expressions for the particle-in-a-disk and the particle-in-a-sphere.", "_____no_output_____" ], [ "### Solutions to the Schr&ouml;dinger Equation for a Particle Confined to a Spherical Ball\n![Eigenfunction Animation](https://upload.wikimedia.org/wikipedia/commons/8/86/Hydrogen_Wave.gif \"Schematic of an eigenfunction of a spherically-confined particle, with the n, l, and m quantum numbers specified\")\nThe energies of a particle confined to a spherical ball of radius $a$ are:\n$$\nE_{n,l} = \\frac{\\hbar^2 y_{n,l}^2}{2ma^2} \\qquad n=1,2,\\ldots; \\quad l=0,1,\\ldots; \\quad m=0, \\pm1, \\ldots, \\pm l\n$$\nand its eigenfunctions are:\n$$\n\\psi_{n,l,m}(r,\\theta,\\phi) \\propto j_l\\left(\\frac{y_{n,l}r}{a} \\right) Y_l^{m_l}(\\theta, \\phi)\n$$\nwhere $y_{n,l}$ are the zeros of the spherical Bessel function, $j_l(y_{n,l}) = 0$. The first spherical Bessel function, which corresponds to s-like solutions ($l=0$), is \n$$\nj_l(y) = \\frac{\\sin y}{y}\n$$\nand so \n$$\ny_{n,0} = n \\pi\n$$\nThis gives explicit and useful expressions for the $l=0$ wavefunctions and energies,\n$$\nE_{n,0} = \\frac{h^2 n^2}{8 m a^2}\n$$\nand its eigenfunctions are:\n$$\n\\psi_{n,0,0}(r,\\theta,\\phi) \\propto \\frac{a}{n \\pi r} \\sin \\left( \\frac{n \\pi r}{a} \\right)\n$$\nNotice that the $l=0$ energies are the same as in the one-dimensional particle-in-a-box and the eigenfunctions are very similar. \n\nIn atomic units, the energies of an electron confined to a spherical ball with radius $a$ Bohr are: \n$$\nE_{n,l} = \\tfrac{y_{n,l}^2}{2a^2}\n$$\nThe following code block computes these energies. It uses the relationship between the spherical Bessel functions and the ordinary Bessel functions,\n$$\nj_l(x) = \\sqrt{\\frac{\\pi}{2x}} J_{l+\\tfrac{1}{2}}(x)\n$$\nwhich indicates that the zeros of $j_l(x)$ and $J_{l+\\tfrac{1}{2}}(x)$ occur the same places.", "_____no_output_____" ] ], [ [ "#The next few lines just set up the sliders for setting parameters.\n#Principle quantum number slider:\nn = widgets.IntSlider(\n value=1,\n min=1,\n max=10,\n step=1,\n description='n (princ. #):',\n disabled=False,\n continuous_update=True,\n orientation='horizontal',\n readout=True,\n readout_format='d')\n\n#Angular quantum number slider:\nl = widgets.IntSlider(\n value=0,\n min=-10,\n max=10,\n step=1,\n description='l (ang. #):',\n disabled=False,\n continuous_update=True,\n orientation='horizontal',\n readout=True,\n readout_format='d')\n\n#Box length slider:\na = widgets.FloatSlider(\n value=1,\n min=.01,\n max=10.0,\n step=0.01,\n description='a (length):',\n disabled=False,\n continuous_update=True,\n orientation='horizontal',\n readout=True,\n readout_format='.2f',\n)\n\n# Define a function for the energy (in a.u.) of a particle in a spherical ball\n# with length a, principle quantum number n, and angular quantum number l\n# The length is input in Bohr (atomic units).\ndef compute_energy_ball(n, l, a):\n \"Compute 1-dimensional particle-in-a-spherical-ball energy.\"\n #Compute the energy from the n-th zero.\n return float((mpmath.besseljzero(l+0.5,n))**2/ (2 * a**2))\n\n#This next bit of code just prints out the energy in atomic units\ndef print_energy_ball(a, n, l):\n print(f'The energy of an electron confined to a ball with radius {a:.2f} a.u.,'\n f' principle quantum number {n}, and angular quantum number {l}'\n f' is {compute_energy_ball(n, l, a):5.2f} a.u..')\n \nout = widgets.interactive_output(print_energy_ball, {'a': a, 'n': n, 'l': l})\n\nwidgets.VBox([widgets.VBox([a, n, l]),out]) ", "_____no_output_____" ] ], [ [ "## &#x1f4dd; Exercise: For the hydrogen atom, the 2s orbital ($n=2$, $l=0$) and 2p orbitals ($n=2$,$l=1$,$m_l=-1,0,1$) have the same energy. Is this true for the particle-in-a-ball?", "_____no_output_____" ], [ "## &#x1fa9e; Self-Reflection\n- Can you think of other physical or chemical systems where a multi-dimensional particle-in-a-box Hamiltonian would be appropriate? What shape would the box be? \n- Can you think of another chemical system where separation of variables would be useful?\n- Explain why separation of variables is consistent with the Born Postulate that the square-magnitude of a particle's wavefunction is the probability distribution function for the particle.\n- What is the expression for the zero-point energy and ground-state wavefunction of an electron in a 4-dimensional box? Can you identify some states of the 4-dimensional box with especially high degeneracy?\n- What is the degeneracy of the k-th excited state of a particle confined to a circular disk? What is the degeneracy of the k-th excited state of a particle confined in a spherical ball?\n- Write a Python function that computes the normalization constant for the particle-in-a-disk and the particle-in-a-sphere.\n\n## &#x1f914; Thought-Provoking Questions\n- How would you write the Hamiltonian for two electrons confined to a box? Could you solve this system with separation of variables? Why or why not? \n- Write the time-independent Schr&ouml;dinger equation for an electron in an cylindrical box. What are its eigenfunctions and eigenvalues? \n- What would the time-independent Schr&ouml;dinger equation for electrons in an elliptical box look like? (You may find it useful to reference [elliptical](https://en.wikipedia.org/wiki/Elliptic_coordinate_system) and [ellipsoidal](https://en.wikipedia.org/wiki/Ellipsoidal_coordinates) coordinates.\n- Construct an example of a four-fold *accidental* degeneracy for a particle in a 2-dimensional rectangular (not square!) box. \n- If there is any degenerate state (either accidental or due to symmetry) for the multi-dimensional particle-in-a-box, then there are always an infinite number of other degenerate states. Why?\n- Consider an electron confined to a circular harmonic well, $V(r) = k r^2$. What is the angular kinetic energy and angular wavefunction for this system? \n\n## &#x1f501; Recapitulation\n- Write the Hamiltonian, time-independent Schr&ouml;dinger equation, eigenfunctions, and eigenvalues for two-dimensional and three-dimensional particles in a box.\n- What is the definition of degeneracy? How does an \"accidental\" degeneracy differ from an ordinary degeneracy? \n- What is the zero-point energy for an electron in a circle and an electron in a sphere? \n- What are the spherical harmonics? \n- Describe the technique of separation of variables? When can it be applied?\n- What is the Laplacian operator in Cartesian coordinates? In spherical coordinates?\n- What are *boundary conditions* and how are they important in quantum mechanics?\n\n## &#x1f52e; Next Up...\n- 1-electron atoms\n- Approximate methods for quantum mechanics\n- Multielectron particle-in-a-box\n- Postulates of Quantum Mechanics\n\n## &#x1f4da; References\nMy favorite sources for this material are:\n- [Randy's book](https://github.com/PaulWAyers/IntroQChem/blob/main/documents/DumontBook.pdf?raw=true) (See Chapter 3)\n- Also see my (pdf) class [notes]\n(https://github.com/PaulWAyers/IntroQChem/blob/main/documents/PinBox.pdf?raw=true).\n- [McQuarrie and Simon summary](https://chem.libretexts.org/Bookshelves/Physical_and_Theoretical_Chemistry_Textbook_Maps/Map%3A_Physical_Chemistry_(McQuarrie_and_Simon)/03%3A_The_Schrodinger_Equation_and_a_Particle_in_a_Box)\n- [Wolfram solutions for particle in a circle](https://demonstrations.wolfram.com/ParticleInAnInfiniteCircularWell/)\n- [Meticulous solution for a particle confined to a circular disk](https://opencommons.uconn.edu/cgi/viewcontent.cgi?article=1013&context=chem_educ)\n- [General discussion of the particle-in-a-region, which is the same as the classical wave equation](http://galileo.phys.virginia.edu/classes/252/Classical_Waves/Classical_Waves.html)\n- [More on the radial Schr&ouml;dinger equation](https://quantummechanics.ucsd.edu/ph130a/130_notes/node222.html)\n- Python tutorial ([part 1](https://physicspython.wordpress.com/2020/05/28/the-problem-of-the-hydrogen-atom-part-1/) and [part 2](https://physicspython.wordpress.com/2020/06/04/the-problem-of-the-hydrogen-atom-part-2/)) on the Hydrogen atom.\n\nThere are also some excellent wikipedia articles:\n- [Particle in a Sphere](https://en.wikipedia.org/wiki/Particle_in_a_spherically_symmetric_potential)\n- [Other exactly solvable models](https://en.wikipedia.org/wiki/List_of_quantum-mechanical_systems_with_analytical_solutions)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cb6545696a3f4c87328949acd4f1500737fdfe31
20,832
ipynb
Jupyter Notebook
Main.ipynb
robertosousa1/dimensionality-reduction
385c2a8a16ffb155d05666516ba80854920a8d4c
[ "MIT" ]
1
2020-06-06T05:25:12.000Z
2020-06-06T05:25:12.000Z
Main.ipynb
robertosousa1/dimensionality-reduction
385c2a8a16ffb155d05666516ba80854920a8d4c
[ "MIT" ]
null
null
null
Main.ipynb
robertosousa1/dimensionality-reduction
385c2a8a16ffb155d05666516ba80854920a8d4c
[ "MIT" ]
null
null
null
30.017291
284
0.409322
[ [ [ "# Challenge\n\nIn this challenge, we will practice on dimensionality reduction with PCA and selection of variables with RFE. We will use the _data set_ [Fifa 2019](https://www.kaggle.com/karangadiya/fifa19), originally containing 89 variables from over 18 thousand players of _game_ FIFA 2019.", "_____no_output_____" ], [ "## _Setup_ ", "_____no_output_____" ] ], [ [ "from math import sqrt\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats as sct\nimport seaborn as sns\nimport statsmodels.api as sm\nimport statsmodels.stats as st\nfrom sklearn.decomposition import PCA\n\nfrom loguru import logger\n\nfrom IPython import get_ipython", "_____no_output_____" ], [ "%matplotlib inline\n\nfrom IPython.core.pylabtools import figsize\n\n\nfigsize(12, 8)\n\nsns.set()", "_____no_output_____" ], [ "fifa = pd.read_csv(\"fifa.csv\")", "_____no_output_____" ], [ "columns_to_drop = [\"Unnamed: 0\", \"ID\", \"Name\", \"Photo\", \"Nationality\", \"Flag\",\n \"Club\", \"Club Logo\", \"Value\", \"Wage\", \"Special\", \"Preferred Foot\",\n \"International Reputation\", \"Weak Foot\", \"Skill Moves\", \"Work Rate\",\n \"Body Type\", \"Real Face\", \"Position\", \"Jersey Number\", \"Joined\",\n \"Loaned From\", \"Contract Valid Until\", \"Height\", \"Weight\", \"LS\",\n \"ST\", \"RS\", \"LW\", \"LF\", \"CF\", \"RF\", \"RW\", \"LAM\", \"CAM\", \"RAM\", \"LM\",\n \"LCM\", \"CM\", \"RCM\", \"RM\", \"LWB\", \"LDM\", \"CDM\", \"RDM\", \"RWB\", \"LB\", \"LCB\",\n \"CB\", \"RCB\", \"RB\", \"Release Clause\"\n]\n\ntry:\n fifa.drop(columns_to_drop, axis=1, inplace=True)\nexcept KeyError:\n logger.warning(f\"Columns already dropped\")", "_____no_output_____" ] ], [ [ "## Starts analysis", "_____no_output_____" ] ], [ [ "fifa.head()", "_____no_output_____" ], [ "fifa.shape", "_____no_output_____" ], [ "fifa.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 18207 entries, 0 to 18206\nData columns (total 37 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Age 18207 non-null int64 \n 1 Overall 18207 non-null int64 \n 2 Potential 18207 non-null int64 \n 3 Crossing 18159 non-null float64\n 4 Finishing 18159 non-null float64\n 5 HeadingAccuracy 18159 non-null float64\n 6 ShortPassing 18159 non-null float64\n 7 Volleys 18159 non-null float64\n 8 Dribbling 18159 non-null float64\n 9 Curve 18159 non-null float64\n 10 FKAccuracy 18159 non-null float64\n 11 LongPassing 18159 non-null float64\n 12 BallControl 18159 non-null float64\n 13 Acceleration 18159 non-null float64\n 14 SprintSpeed 18159 non-null float64\n 15 Agility 18159 non-null float64\n 16 Reactions 18159 non-null float64\n 17 Balance 18159 non-null float64\n 18 ShotPower 18159 non-null float64\n 19 Jumping 18159 non-null float64\n 20 Stamina 18159 non-null float64\n 21 Strength 18159 non-null float64\n 22 LongShots 18159 non-null float64\n 23 Aggression 18159 non-null float64\n 24 Interceptions 18159 non-null float64\n 25 Positioning 18159 non-null float64\n 26 Vision 18159 non-null float64\n 27 Penalties 18159 non-null float64\n 28 Composure 18159 non-null float64\n 29 Marking 18159 non-null float64\n 30 StandingTackle 18159 non-null float64\n 31 SlidingTackle 18159 non-null float64\n 32 GKDiving 18159 non-null float64\n 33 GKHandling 18159 non-null float64\n 34 GKKicking 18159 non-null float64\n 35 GKPositioning 18159 non-null float64\n 36 GKReflexes 18159 non-null float64\ndtypes: float64(34), int64(3)\nmemory usage: 5.1 MB\n" ], [ "fifa.isna().sum()", "_____no_output_____" ], [ "fifa = fifa.dropna()\nfifa.isna().sum()", "_____no_output_____" ] ], [ [ "## Question 1\n\nWhich fraction of the variance can be explained by the first main component of `fifa`? Respond as a single float (between 0 and 1) rounded to three decimal places.", "_____no_output_____" ] ], [ [ "def q1():\n pca = PCA(n_components = 1).fit(fifa)\n return round(float(pca.explained_variance_ratio_), 3)\nq1()", "_____no_output_____" ] ], [ [ "## Question 2\n\nHow many major components do we need to explain 95% of the total variance? Answer as a single integer scalar.", "_____no_output_____" ] ], [ [ "def q2():\n pca_095 = PCA(n_components=0.95)\n X_reduced = pca_095.fit_transform(fifa)\n return X_reduced.shape[1]\nq2()", "_____no_output_____" ] ], [ [ "## Question 3\n\nWhat are the coordinates (first and second main components) of the `x` point below? The vector below is already centered. Be careful to __not__ center the vector again (for example, by invoking `PCA.transform ()` on it). Respond as a float tuple rounded to three decimal places.", "_____no_output_____" ] ], [ [ "x = [0.87747123, -1.24990363, -1.3191255, -36.7341814,\n -35.55091139, -37.29814417, -28.68671182, -30.90902583,\n -42.37100061, -32.17082438, -28.86315326, -22.71193348,\n -38.36945867, -20.61407566, -22.72696734, -25.50360703,\n 2.16339005, -27.96657305, -33.46004736, -5.08943224,\n -30.21994603, 3.68803348, -36.10997302, -30.86899058,\n -22.69827634, -37.95847789, -22.40090313, -30.54859849,\n -26.64827358, -19.28162344, -34.69783578, -34.6614351,\n 48.38377664, 47.60840355, 45.76793876, 44.61110193,\n 49.28911284\n]", "_____no_output_____" ], [ "def q3():\n pca_q3 = PCA(n_components = 2)\n pca_q3.fit(fifa)\n return tuple(np.round(pca_q3.components_.dot(x),3))\nq3()", "_____no_output_____" ] ], [ [ "## Question 4\n\nPerforms RFE with linear regression estimator to select five variables, eliminating them one by one. What are the selected variables? Respond as a list of variable names.", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LinearRegression\nfrom sklearn.feature_selection import RFE\n\ndef q4():\n x = fifa.drop('Overall', axis=1)\n y = fifa['Overall']\n reg = LinearRegression().fit(x,y)\n rfe = RFE(reg, n_features_to_select=5).fit(x, y)\n nom_var = x.loc[:,rfe.get_support()].columns\n return list(nom_var)\nq4()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
cb654a11cfed58ca44918bd46746b2afdc3533bd
978
ipynb
Jupyter Notebook
Read.ipynb
AjeeshSMohan/it-cert-automation-practice
a31512065e0c1e4b34ce77106df13d0213418665
[ "Apache-2.0" ]
null
null
null
Read.ipynb
AjeeshSMohan/it-cert-automation-practice
a31512065e0c1e4b34ce77106df13d0213418665
[ "Apache-2.0" ]
null
null
null
Read.ipynb
AjeeshSMohan/it-cert-automation-practice
a31512065e0c1e4b34ce77106df13d0213418665
[ "Apache-2.0" ]
null
null
null
23.285714
243
0.507157
[ [ [ "<a href=\"https://colab.research.google.com/github/AjeeshSMohan/it-cert-automation-practice/blob/master/Read.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "import cv2", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code" ] ]
cb654e85c28464b5d51efc034ef746a1ec5706f0
803
ipynb
Jupyter Notebook
tests/integration/notebooks/failed/pyspark.ipynb
hyades910739/nbsexy
a08c438a613bf288e69ea13a1a4fb7115fea003b
[ "MIT" ]
7
2022-03-10T02:27:54.000Z
2022-03-11T00:58:54.000Z
tests/integration/notebooks/failed/pyspark.ipynb
hyades910739/nbsexy
a08c438a613bf288e69ea13a1a4fb7115fea003b
[ "MIT" ]
null
null
null
tests/integration/notebooks/failed/pyspark.ipynb
hyades910739/nbsexy
a08c438a613bf288e69ea13a1a4fb7115fea003b
[ "MIT" ]
null
null
null
18.25
48
0.537983
[ [ [ "import pyspark", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
cb6551b30ef314d3ac51ad7dfaa48d837ac2cefd
41,257
ipynb
Jupyter Notebook
nbs/06_cli.ipynb
jcornford/nbdev
a7a7c08b2f4d4f5234a4a122a40173e2d389b99d
[ "Apache-2.0" ]
null
null
null
nbs/06_cli.ipynb
jcornford/nbdev
a7a7c08b2f4d4f5234a4a122a40173e2d389b99d
[ "Apache-2.0" ]
null
null
null
nbs/06_cli.ipynb
jcornford/nbdev
a7a7c08b2f4d4f5234a4a122a40173e2d389b99d
[ "Apache-2.0" ]
null
null
null
39.069129
490
0.582786
[ [ [ "from nbdev import *\n%nbdev_default_export cli", "Cells will be exported to nbdev.cli,\nunless a different module is specified after an export flag: `%nbdev_export special.module`\n" ] ], [ [ "# Command line functions\n\n> Console commands added by the nbdev library", "_____no_output_____" ] ], [ [ "%nbdev_export\nfrom nbdev.imports import *\nfrom nbdev.export import *\nfrom nbdev.sync import *\nfrom nbdev.merge import *\nfrom nbdev.export2html import *\nfrom nbdev.test import *\nfrom fastscript import call_parse,Param,bool_arg", "_____no_output_____" ] ], [ [ "`nbdev` comes with the following commands. To use any of them, you must be in one of the subfolders of your project: they will search for the `settings.ini` recursively in the parent directory but need to access it to be able to work. Their names all begin with nbdev so you can easily get a list with tab completion.\n- `nbdev_build_docs` builds the documentation from the notebooks\n- `nbdev_build_lib` builds the library from the notebooks\n- `nbdev_bump_version` increments version in `settings.py` by one\n- `nbdev_clean_nbs` removes all superfluous metadata form the notebooks, to avoid merge conflicts\n- `nbdev_detach` exports cell attachments to `dest` and updates references\n- `nbdev_diff_nbs` gives you the diff between the notebooks and the exported library\n- `nbdev_fix_merge` will fix merge conflicts in a notebook file\n- `nbdev_install_git_hooks` installs the git hooks that use the last two command automatically on each commit/merge\n- `nbdev_nb2md` converts a notebook to a markdown file\n- `nbdev_new` creates a new nbdev project\n- `nbdev_read_nbs` reads all notebooks to make sure none are broken\n- `nbdev_test_nbs` runs tests in notebooks\n- `nbdev_trust_nbs` trusts all notebooks (so that the HTML content is shown)\n- `nbdev_update_lib` propagates any change in the library back to the notebooks\n- `nbdev_upgrade` updates an existing nbdev project to use the latest features", "_____no_output_____" ], [ "## Migrate from comment flags to magic flags", "_____no_output_____" ] ], [ [ "%nbdev_export\nimport re,nbformat\nfrom nbdev.export import _mk_flag_re, _re_all_def\nfrom nbdev.flags import parse_line", "_____no_output_____" ] ], [ [ "### Migrating notebooks\n\nRun `nbdev_upgrade` from the command line to update code cells in notebooks that use comment flags like\n\n```python\n#export special.module\n```\n\nto use magic flags\n\n```python\n%nbdev_export special.module\n```\n\nTo make the magic flags work, `nbdev_upgrade` might need to add a new code cell to the top of the notebook\n\n```python\nfrom nbdev import *\n```\n\n### Hiding the `from nbdev import *` cell\n\nnbdev does not treat `from nbdev import *` as special, but this cell can be hidden from the docs by combining it with `%nbdev_default_export`. e.g. \n```python\nfrom nbdev import *\n%nbdev_default_export my_module\n```\nthis works because nbdev will hide any code cell containing the `%nbdev_default_export` flag.\n\nIf you don't need `%nbdev_default_export` in your notebook you can: use the hide input [jupyter extension](https://github.com/ipython-contrib/jupyter_contrib_nbextensions) or edit cell metadata to include `\"hide_input\": true`", "_____no_output_____" ] ], [ [ "%nbdev_export_internal\ndef _code_patterns_and_replace_fns():\n \"Return a list of pattern/function tuples that can migrate flags used in code cells\"\n patterns_and_replace_fns = []\n\n def _replace_fn(magic, m):\n \"Return a magic flag for a comment flag matched in `m`\"\n if not m.groups() or not m.group(1): return f'%{magic}'\n return f'%{magic}' if m.group(1) is None else f'%{magic} {m.group(1)}'\n\n def _add_pattern_and_replace_fn(comment_flag, magic_flag, n_params=(0,1)):\n \"Add a pattern/function tuple to go from comment to magic flag\"\n pattern = _mk_flag_re(False, comment_flag, n_params, \"\")\n # note: fn has to be single arg so we can use it in `pattern.sub` calls later\n patterns_and_replace_fns.append((pattern, partial(_replace_fn, magic_flag)))\n\n _add_pattern_and_replace_fn('default_exp', 'nbdev_default_export', 1)\n _add_pattern_and_replace_fn('exports', 'nbdev_export_and_show')\n _add_pattern_and_replace_fn('exporti', 'nbdev_export_internal')\n _add_pattern_and_replace_fn('export', 'nbdev_export')\n _add_pattern_and_replace_fn('hide_input', 'nbdev_hide_input', 0)\n _add_pattern_and_replace_fn('hide_output', 'nbdev_hide_output', 0)\n _add_pattern_and_replace_fn('hide', 'nbdev_hide', 0) # keep at index 6 - see _migrate2magic\n _add_pattern_and_replace_fn('default_cls_lvl', 'nbdev_default_class_level', 1)\n _add_pattern_and_replace_fn('collapse[_-]output', 'nbdev_collapse_output', 0)\n _add_pattern_and_replace_fn('collapse[_-]show', 'nbdev_collapse_input open', 0)\n _add_pattern_and_replace_fn('collapse[_-]hide', 'nbdev_collapse_input', 0)\n _add_pattern_and_replace_fn('collapse', 'nbdev_collapse_input', 0)\n for flag in Config().get('tst_flags', '').split('|'):\n if flag.strip():\n _add_pattern_and_replace_fn(f'all_{flag}', f'nbdev_{flag}_test all', 0)\n _add_pattern_and_replace_fn(flag, f'nbdev_{flag}_test', 0)\n patterns_and_replace_fns.append(\n (_re_all_def, lambda m: '%nbdev_add2all ' + ','.join(parse_line(m.group(1)))))\n return patterns_and_replace_fns", "_____no_output_____" ], [ "%nbdev_export_internal\nclass CellMigrator():\n \"Can migrate a cell using `patterns_and_replace_fns`\"\n def __init__(self, patterns_and_replace_fns):\n self.patterns_and_replace_fns,self.upd_count,self.first_cell=patterns_and_replace_fns,0,None\n def __call__(self, cell):\n if self.first_cell is None: self.first_cell = cell\n for pattern, replace_fn in self.patterns_and_replace_fns:\n source=cell.source\n cell.source=pattern.sub(replace_fn, source)\n if source!=cell.source: self.upd_count+=1", "_____no_output_____" ], [ "%nbdev_export_internal\ndef _migrate2magic(nb):\n \"Migrate a single notebook\"\n # migrate #hide in markdown\n m=CellMigrator(_code_patterns_and_replace_fns()[6:7])\n [m(cell) for cell in nb.cells if cell.cell_type=='markdown']\n # migrate everything in code_patterns_and_replace_fns in code cells\n m=CellMigrator(_code_patterns_and_replace_fns())\n [m(cell) for cell in nb.cells if cell.cell_type=='code']\n imp,fc='from nbdev import *',m.first_cell\n if m.upd_count!=0 and fc is not None and imp not in fc.get('source', ''):\n nb.cells.insert(0, nbformat.v4.new_code_cell(imp, metadata={'hide_input': True}))\n NotebookNotary().sign(nb)\n return nb", "_____no_output_____" ], [ "%nbdev_hide\ndef remove_line(starting_with, from_string):\n result=[]\n for line in from_string.split('\\n'):\n if not line.strip().startswith(starting_with):\n result.append(line)\n return '\\n'.join(result)\n\ntest_lines = 'line1\\n%magic\\n#comment\\n123\\n %magic\\n # comment'\ntest_eq('line1\\n%magic\\n123\\n %magic', remove_line('#', test_lines))\ntest_eq('line1\\n123', remove_line('%', 'line1\\n%magic\\n123\\n %magic'))", "_____no_output_____" ], [ "%nbdev_hide\ndef remove_comments_and_magics(string):\n return remove_line('#', remove_line('%', string))\n\ntest_eq('line1\\n123', remove_comments_and_magics(test_lines))", "_____no_output_____" ], [ "%nbdev_hide\ndef test_migrate2magic(fname):\n \"Check that nothing other that comments and magics in code cells have been changed\"\n nb=read_nb(fname)\n nb_migrated=_migrate2magic(read_nb(fname))\n test_eq(len(nb.cells)+1, len(nb_migrated.cells))\n test_eq('from nbdev import *', nb_migrated.cells[0].source)\n for i in range(len(nb.cells)):\n cell, cell_migrated=nb.cells[i], nb_migrated.cells[i+1]\n if cell.cell_type=='code':\n cell.source=remove_comments_and_magics(cell.source)\n cell_migrated.source=remove_comments_and_magics(cell_migrated.source)\n test_eq(cell, cell_migrated)\n \ntest_migrate2magic('../test/00_export.ipynb')\ntest_migrate2magic('../test/07_clean.ipynb')\n\ndef test_migrate2magic_noop(fname):\n \"Check that nothing is changed if there are no comment flags in a notebook\"\n nb=read_nb(fname)\n nb_migrated=_migrate2magic(read_nb(fname))\n test_eq(nb, nb_migrated)\n \ntest_migrate2magic_noop('99_search.ipynb')", "_____no_output_____" ], [ "%nbdev_hide\nsources=['#export aaa\\nimport io,sys,json,glob\\n#collapse-OUTPUT\\nfrom fastscript ...',\n '%nbdev_export aaa\\nimport io,sys,json,glob\\n%nbdev_collapse_output\\nfrom fastscript ...',\n '#EXPORT\\n # collapse\\nimport io,sys,json,glob',\n '%nbdev_export\\n%nbdev_collapse_input\\nimport io,sys,json,glob',\n '#exportS\\nimport io,sys,json,glob\\n#colLApse_show',\n '%nbdev_export_and_show\\nimport io,sys,json,glob\\n%nbdev_collapse_input open',\n ' # collapse-show \\n#exporti\\nimport io,sys,json,glob',\n '%nbdev_collapse_input open\\n%nbdev_export_internal\\nimport io,sys,json,glob',\n '#export\\t\\tspecial.module \\nimport io,sys,json,glob',\n '%nbdev_export special.module\\nimport io,sys,json,glob',\n '#exports special.module\\nimport io,sys,json,glob',\n '%nbdev_export_and_show special.module\\nimport io,sys,json,glob',\n '#EXPORT special.module\\nimport io,sys,json,glob',\n '%nbdev_export special.module\\nimport io,sys,json,glob',\n '#exportI \\t \\tspecial.module\\n# collapse_hide \\nimport io,sys,json,glob',\n '%nbdev_export_internal special.module\\n%nbdev_collapse_input\\nimport io,sys,json,glob',\n '# export \\nimport io,sys,json,glob',\n '%nbdev_export\\nimport io,sys,json,glob',\n ' # export\\nimport io,sys,json,glob',\n '%nbdev_export\\nimport io,sys,json,glob',\n '#default_cls_lvl ',\n '#default_cls_lvl ',\n '#default_cls_lvl 3 another',\n '#default_cls_lvl 3 another',\n '#default_cls_lvl 3',\n '%nbdev_default_class_level 3',\n 'from nbdev import *\\n # default_cls_lvl 3',\n 'from nbdev import *\\n%nbdev_default_class_level 3',\n ' # Collapse-Hide \\n # EXPORTS\\nimport io,sys,json,glob',\n '%nbdev_collapse_input\\n%nbdev_export_and_show\\nimport io,sys,json,glob',\n ' # exporti\\nimport io,sys,json,glob',\n '%nbdev_export_internal\\nimport io,sys,json,glob',\n 'import io,sys,json,glob\\n#export aaa\\nfrom fastscript import call_pars...',\n 'import io,sys,json,glob\\n%nbdev_export aaa\\nfrom fastscript import call_pars...',\n '#fastai2\\nsome test code',\n '%nbdev_fastai2_test\\nsome test code',\n '#fastai2 extra_comment\\nsome test code', # test flags with \"parameters\" won't get migrated\n '#fastai2 extra_comment\\nsome test code',\n '# all_fastai2 \\nsome test code',\n '%nbdev_fastai2_test all\\nsome test code',\n '# all_fastai2 extra_comment \\nsome test code',\n '# all_fastai2 extra_comment \\nsome test code',\n '#COLLAPSE_OUTPUT\\nprint(\"lotsofoutput\")',\n '%nbdev_collapse_output\\nprint(\"lotsofoutput\")',\n ' # hide\\n#fastai2\\ndef some_test():\\n...',\n '%nbdev_hide\\n%nbdev_fastai2_test\\ndef some_test():\\n...',\n '#comment\\n# export \\n_all_ = [\"a\",bb, \"CCC\" , \\'d\\'] \\nmore code',\n '#comment\\n%nbdev_export\\n%nbdev_add2all \"a\",bb,\"CCC\",\\'d\\' \\nmore code']\nnb=nbformat.v4.new_notebook()\nnb_expected=nbformat.v4.new_notebook()\nnb_expected.cells.append(nbformat.v4.new_code_cell('from nbdev import *', metadata={'hide_input': True}))\nfor cells, source in zip([nb.cells,nb_expected.cells]*(len(sources)//2), sources):\n cells.append(nbformat.v4.new_code_cell(source))\nnb_migrated=_migrate2magic(nb)\nfor cell_expected, cell_migrated in zip(nb_expected.cells, nb_migrated.cells):\n test_eq(cell_expected, cell_migrated)", "_____no_output_____" ], [ "%nbdev_hide\n# hide is the only flag that we migrate in markdown\nsources=['#export aaa\\nimport io,sys,json,glob\\n#collapse-OUTPUT\\nfrom fastscript ...',\n '#export aaa\\nimport io,sys,json,glob\\n#collapse-OUTPUT\\nfrom fastscript ...',\n '#exportI \\t \\tspecial.module\\n# collapse_hide \\nimport io,sys,json,glob',\n '#exportI \\t \\tspecial.module\\n# collapse_hide \\nimport io,sys,json,glob',\n 'some text\\n#hide\\nwill still be hidden',\n 'some text\\n%nbdev_hide\\nwill still be hidden',\n ' # Collapse-Hide \\n # EXPORTS\\nimport io,sys,json,glob',\n ' # Collapse-Hide \\n # EXPORTS\\nimport io,sys,json,glob',\n ' # hide\\n\\n\\n#fastai2\\ndef some_test():\\n...',\n '%nbdev_hide\\n\\n\\n#fastai2\\ndef some_test():\\n...']\nnb=nbformat.v4.new_notebook()\nnb_expected=nbformat.v4.new_notebook()\nfor cells, source in zip([nb.cells,nb_expected.cells]*(len(sources)//2), sources):\n cells.append(nbformat.v4.new_markdown_cell(source))\nnb_migrated=_migrate2magic(nb)\nfor cell_expected, cell_migrated in zip(nb_expected.cells, nb_migrated.cells):\n test_eq(cell_expected, cell_migrated)", "_____no_output_____" ] ], [ [ "## Add css for \"collapse\" components\n\nIf you want to use collapsable cells in your HTML docs, you need to style the details tag in customstyles.css. `_add_collapse_css` will do this for you, if the details tag is not already styled.", "_____no_output_____" ] ], [ [ "%nbdev_export_internal\n_details_description_css = \"\"\"\\n\n/*Added by nbdev add_collapse_css*/\ndetails.description[open] summary::after {\n content: attr(data-open);\n}\n\ndetails.description:not([open]) summary::after {\n content: attr(data-close);\n}\n\ndetails.description summary {\n text-align: right;\n font-size: 15px;\n color: #337ab7;\n cursor: pointer;\n}\n\ndetails + div.output_wrapper {\n /* show/hide code */\n margin-top: 25px;\n}\n\ndiv.input + details {\n /* show/hide output */\n margin-top: -25px;\n}\n/*End of section added by nbdev add_collapse_css*/\"\"\"\n\ndef _add_collapse_css(doc_path=None):\n \"Update customstyles.css so that collapse components can be used in HTML pages\"\n fn = (Path(doc_path) if doc_path else Config().doc_path/'css')/'customstyles.css'\n with open(fn) as f:\n if 'details.description' in f.read():\n print('details.description already styled in customstyles.css, no changes made')\n else:\n with open(fn, 'a') as f: f.write(_details_description_css)\n print('details.description styles added to customstyles.css')", "_____no_output_____" ], [ "%nbdev_hide\nwith open('/tmp/customstyles.css', 'w') as f:\n f.write('/*test file*/')\n_add_collapse_css('/tmp') # details.description styles added ...\nwith open('/tmp/customstyles.css') as f:\n test_eq(''.join(['/*test file*/', _details_description_css]), f.read())\nwith open('/tmp/customstyles.css', 'a') as f:\n f.write('\\nmore things added after')\n_add_collapse_css('/tmp') # details.description already styled ...\nwith open('/tmp/customstyles.css') as f:\n test_eq(''.join(['/*test file*/', _details_description_css, '\\nmore things added after']), f.read())", "details.description styles added to customstyles.css\ndetails.description already styled in customstyles.css, no changes made\n" ] ], [ [ "## Upgrading existing nbdev projects to use new features", "_____no_output_____" ] ], [ [ "%nbdev_export\n@call_parse\ndef nbdev_upgrade(migrate2magic:Param(\"Migrate all notebooks in `nbs_path` to use magic flags\", bool_arg)=True, \n add_collapse_css:Param(\"Add css for \\\"#collapse\\\" components\", bool_arg)=True):\n \"Update an existing nbdev project to use the latest features\"\n if migrate2magic:\n for fname in Config().nbs_path.glob('*.ipynb'):\n print('Migrating', fname)\n nbformat.write(_migrate2magic(read_nb(fname)), str(fname), version=4)\n if add_collapse_css: _add_collapse_css()", "_____no_output_____" ] ], [ [ "- `migrate2magic` reads *all* notebooks in `nbs_path` and migrates them in-place\n- `add_collapse_css` updates `customstyles.css` so that \"collapse\" components can be used in HTML pages", "_____no_output_____" ], [ "## Navigating from notebooks to script and back", "_____no_output_____" ] ], [ [ "%nbdev_export\n@call_parse\ndef nbdev_build_lib(fname:Param(\"A notebook name or glob to convert\", str)=None):\n \"Export notebooks matching `fname` to python modules\"\n write_tmpls()\n notebook2script(fname=fname)", "_____no_output_____" ] ], [ [ "By default (`fname` left to `None`), the whole library is built from the notebooks in the `lib_folder` set in your `settings.ini`.", "_____no_output_____" ] ], [ [ "%nbdev_export\n@call_parse\ndef nbdev_update_lib(fname:Param(\"A notebook name or glob to convert\", str)=None):\n \"Propagates any change in the modules matching `fname` to the notebooks that created them\"\n script2notebook(fname=fname)", "_____no_output_____" ] ], [ [ "By default (`fname` left to `None`), the whole library is treated. Note that this tool is only designed for small changes such as typo or small bug fixes. You can't add new cells in notebook from the library.", "_____no_output_____" ] ], [ [ "%nbdev_export\n@call_parse\ndef nbdev_diff_nbs(): \n \"Prints the diff between an export of the library in notebooks and the actual modules\"\n diff_nb_script()", "_____no_output_____" ] ], [ [ "## Extracting tests", "_____no_output_____" ] ], [ [ "%nbdev_export\ndef _test_one(fname, flags=None, verbose=True):\n print(f\"testing: {fname}\")\n start = time.time()\n try: \n test_nb(fname, flags=flags)\n return True,time.time()-start\n except Exception as e: \n if \"Kernel died before replying to kernel_info\" in str(e):\n time.sleep(random.random())\n _test_one(fname, flags=flags)\n if verbose: print(f'Error in {fname}:\\n{e}')\n return False,time.time()-start", "_____no_output_____" ], [ "%nbdev_export\n@call_parse\ndef nbdev_test_nbs(fname:Param(\"A notebook name or glob to convert\", str)=None,\n flags:Param(\"Space separated list of flags\", str)=None,\n n_workers:Param(\"Number of workers to use\", int)=None,\n verbose:Param(\"Print errors along the way\", bool)=True,\n timing:Param(\"Timing each notebook to see the ones are slow\", bool)=False):\n \"Test in parallel the notebooks matching `fname`, passing along `flags`\"\n if flags is not None: flags = flags.split(' ')\n if fname is None: \n files = [f for f in Config().nbs_path.glob('*.ipynb') if not f.name.startswith('_')]\n else: files = glob.glob(fname)\n files = [Path(f).absolute() for f in sorted(files)]\n if len(files)==1 and n_workers is None: n_workers=0\n # make sure we are inside the notebook folder of the project\n os.chdir(Config().nbs_path)\n results = parallel(_test_one, files, flags=flags, verbose=verbose, n_workers=n_workers)\n passed,times = [r[0] for r in results],[r[1] for r in results]\n if all(passed): print(\"All tests are passing!\")\n else:\n msg = \"The following notebooks failed:\\n\"\n raise Exception(msg + '\\n'.join([f.name for p,f in zip(passed,files) if not p]))\n if timing:\n for i,t in sorted(enumerate(times), key=lambda o:o[1], reverse=True): \n print(f\"Notebook {files[i].name} took {int(t)} seconds\")", "_____no_output_____" ] ], [ [ "By default (`fname` left to `None`), the whole library is tested from the notebooks in the `lib_folder` set in your `settings.ini`.", "_____no_output_____" ], [ "## Building documentation", "_____no_output_____" ], [ "The following functions complete the ones in `export2html` to fully build the documentation of your library.", "_____no_output_____" ] ], [ [ "%nbdev_export\n_re_index = re.compile(r'^(?:\\d*_|)index\\.ipynb$')", "_____no_output_____" ], [ "%nbdev_export\ndef make_readme():\n \"Convert the index notebook to README.md\"\n index_fn = None\n for f in Config().nbs_path.glob('*.ipynb'):\n if _re_index.match(f.name): index_fn = f\n assert index_fn is not None, \"Could not locate index notebook\"\n print(f\"converting {index_fn} to README.md\")\n convert_md(index_fn, Config().config_file.parent, jekyll=False)\n n = Config().config_file.parent/index_fn.with_suffix('.md').name\n shutil.move(n, Config().config_file.parent/'README.md')\n if Path(Config().config_file.parent/'PRE_README.md').is_file():\n with open(Config().config_file.parent/'README.md', 'r') as f: readme = f.read()\n with open(Config().config_file.parent/'PRE_README.md', 'r') as f: pre_readme = f.read()\n with open(Config().config_file.parent/'README.md', 'w') as f: f.write(f'{pre_readme}\\n{readme}')", "_____no_output_____" ], [ "%nbdev_export\n@call_parse\ndef nbdev_build_docs(fname:Param(\"A notebook name or glob to convert\", str)=None,\n force_all:Param(\"Rebuild even notebooks that haven't changed\", bool)=False,\n mk_readme:Param(\"Also convert the index notebook to README\", bool)=True,\n n_workers:Param(\"Number of workers to use\", int)=None):\n \"Build the documentation by converting notebooks mathing `fname` to html\"\n notebook2html(fname=fname, force_all=force_all, n_workers=n_workers)\n if fname is None: make_sidebar()\n if mk_readme: make_readme()", "_____no_output_____" ] ], [ [ "By default (`fname` left to `None`), the whole documentation is build from the notebooks in the `lib_folder` set in your `settings.ini`, only converting the ones that have been modified since the their corresponding html was last touched unless you pass `force_all=True`. The index is also converted to make the README file, unless you pass along `mk_readme=False`.", "_____no_output_____" ] ], [ [ "%nbdev_export\n@call_parse\ndef nbdev_nb2md(fname:Param(\"A notebook file name to convert\", str),\n dest:Param(\"The destination folder\", str)='.',\n img_path:Param(\"Folder to export images to\")=\"\",\n jekyll:Param(\"To use jekyll metadata for your markdown file or not\", bool_arg)=False,):\n \"Convert the notebook in `fname` to a markdown file\"\n nb_detach_cells(fname, dest=img_path)\n convert_md(fname, dest, jekyll=jekyll, img_path=img_path)", "_____no_output_____" ], [ "%nbdev_export\n@call_parse\ndef nbdev_detach(path_nb:Param(\"Path to notebook\"),\n dest:Param(\"Destination folder\", str)=\"\",\n use_img:Param(\"Convert markdown images to img tags\", bool_arg)=False):\n \"Export cell attachments to `dest` and update references\"\n nb_detach_cells(path_nb, dest=dest, use_img=use_img)", "_____no_output_____" ] ], [ [ "## Other utils", "_____no_output_____" ] ], [ [ "%nbdev_export\n@call_parse\ndef nbdev_read_nbs(fname:Param(\"A notebook name or glob to convert\", str)=None):\n \"Check all notebooks matching `fname` can be opened\"\n files = Config().nbs_path.glob('**/*.ipynb') if fname is None else glob.glob(fname)\n for nb in files:\n try: _ = read_nb(nb)\n except Exception as e:\n print(f\"{nb} is corrupted and can't be opened.\")\n raise e", "_____no_output_____" ] ], [ [ "By default (`fname` left to `None`), the all the notebooks in `lib_folder` are checked.", "_____no_output_____" ] ], [ [ "%nbdev_export\n@call_parse\ndef nbdev_trust_nbs(fname:Param(\"A notebook name or glob to convert\", str)=None,\n force_all:Param(\"Trust even notebooks that haven't changed\", bool)=False):\n \"Trust noteboks matching `fname`\"\n check_fname = Config().nbs_path/\".last_checked\"\n last_checked = os.path.getmtime(check_fname) if check_fname.exists() else None\n files = Config().nbs_path.glob('**/*.ipynb') if fname is None else glob.glob(fname)\n for fn in files:\n if last_checked and not force_all:\n last_changed = os.path.getmtime(fn)\n if last_changed < last_checked: continue\n nb = read_nb(fn)\n if not NotebookNotary().check_signature(nb): NotebookNotary().sign(nb)\n check_fname.touch(exist_ok=True)", "_____no_output_____" ] ], [ [ "By default (`fname` left to `None`), the all the notebooks in `lib_folder` are trusted. To speed things up, only the ones touched since the last time this command was run are trusted unless you pass along `force_all=True`.", "_____no_output_____" ] ], [ [ "%nbdev_export\n@call_parse\ndef nbdev_fix_merge(fname:Param(\"A notebook filename to fix\", str),\n fast:Param(\"Fast fix: automatically fix the merge conflicts in outputs or metadata\", bool)=True,\n trust_us:Param(\"Use local outputs/metadata when fast mergning\", bool)=True):\n \"Fix merge conflicts in notebook `fname`\"\n fix_conflicts(fname, fast=fast, trust_us=trust_us)", "_____no_output_____" ] ], [ [ "When you have merge conflicts after a `git pull`, the notebook file will be broken and won't open in jupyter notebook anymore. This command fixes this by changing the notebook to a proper json file again and add markdown cells to signal the conflict, you just have to open that notebook again and look for `>>>>>>>` to see those conflicts and manually fix them. The old broken file is copied with a `.ipynb.bak` extension, so is still accessible in case the merge wasn't sucessful.\n\nMoreover, if `fast=True`, conflicts in outputs and metadata will automatically be fixed by using the local version if `trust_us=True`, the remote one if `trust_us=False`. With this option, it's very likely you won't have anything to do, unless there is a real conflict.", "_____no_output_____" ] ], [ [ "%nbdev_export\ndef bump_version(version, part=2):\n version = version.split('.')\n version[part] = str(int(version[part]) + 1)\n for i in range(part+1, 3): version[i] = '0'\n return '.'.join(version)", "_____no_output_____" ], [ "test_eq(bump_version('0.1.1' ), '0.1.2')\ntest_eq(bump_version('0.1.1', 1), '0.2.0')", "_____no_output_____" ], [ "%nbdev_export\n@call_parse\ndef nbdev_bump_version(part:Param(\"Part of version to bump\", int)=2):\n \"Increment version in `settings.py` by one\"\n cfg = Config()\n print(f'Old version: {cfg.version}')\n cfg.d['version'] = bump_version(Config().version, part)\n cfg.save()\n update_version()\n print(f'New version: {cfg.version}')", "_____no_output_____" ] ], [ [ "## Git hooks", "_____no_output_____" ] ], [ [ "%nbdev_export\nimport subprocess", "_____no_output_____" ], [ "%nbdev_export\n@call_parse\ndef nbdev_install_git_hooks():\n \"Install git hooks to clean/trust notebooks automatically\"\n try: path = Config().config_file.parent\n except: path = Path.cwd()\n fn = path/'.git'/'hooks'/'post-merge'\n #Trust notebooks after merge\n with open(fn, 'w') as f:\n f.write(\"\"\"#!/bin/bash\necho \"Trusting notebooks\"\nnbdev_trust_nbs\n\"\"\"\n )\n os.chmod(fn, os.stat(fn).st_mode | stat.S_IEXEC)\n #Clean notebooks on commit/diff\n with open(path/'.gitconfig', 'w') as f:\n f.write(\"\"\"# Generated by nbdev_install_git_hooks\n#\n# If you need to disable this instrumentation do:\n#\n# git config --local --unset include.path\n#\n# To restore the filter\n#\n# git config --local include.path .gitconfig\n#\n# If you see notebooks not stripped, checked the filters are applied in .gitattributes\n#\n[filter \"clean-nbs\"]\n clean = nbdev_clean_nbs --read_input_stream True\n smudge = cat\n required = true\n[diff \"ipynb\"]\n textconv = nbdev_clean_nbs --disp True --fname\n\"\"\")\n cmd = \"git config --local include.path ../.gitconfig\"\n print(f\"Executing: {cmd}\")\n result = subprocess.run(cmd.split(), shell=False, check=False, stderr=subprocess.PIPE)\n if result.returncode == 0:\n print(\"Success: hooks are installed and repo's .gitconfig is now trusted\")\n else:\n print(\"Failed to trust repo's .gitconfig\")\n if result.stderr: print(f\"Error: {result.stderr.decode('utf-8')}\")\n try: nb_path = Config().nbs_path\n except: nb_path = Path.cwd()\n with open(nb_path/'.gitattributes', 'w') as f:\n f.write(\"\"\"**/*.ipynb filter=clean-nbs\n**/*.ipynb diff=ipynb\n\"\"\"\n )", "_____no_output_____" ] ], [ [ "This command installs git hooks to make sure notebooks are cleaned before you commit them to GitHub and automatically trusted at each merge. To be more specific, this creates:\n- an executable '.git/hooks/post-merge' file that contains the command `nbdev_trust_nbs`\n- a `.gitconfig` file that uses `nbev_clean_nbs` has a filter/diff on all notebook files inside `nbs_folder` and a `.gitattributes` file generated in this folder (copy this file in other folders where you might have notebooks you want cleaned as well)", "_____no_output_____" ], [ "## Starting a new project", "_____no_output_____" ] ], [ [ "%nbdev_export\n_template_git_repo = \"https://github.com/fastai/nbdev_template.git\"", "_____no_output_____" ], [ "%nbdev_export\n@call_parse\ndef nbdev_new(name: Param(\"A directory to create the project in\", str),\n template_git_repo: Param(\"url to template repo\", str)=_template_git_repo):\n \"Create a new nbdev project with a given name.\"\n \n path = Path(f\"./{name}\").absolute()\n \n if path.is_dir():\n print(f\"Directory {path} already exists. Aborting.\")\n return\n \n print(f\"Creating a new nbdev project {name}.\")\n \n def rmtree_onerror(func, path, exc_info):\n \"Use with `shutil.rmtree` when you need to delete files/folders that might be read-only.\"\n os.chmod(path, stat.S_IWRITE)\n func(path)\n \n try:\n subprocess.run(['git', 'clone', f'{template_git_repo}', f'{path}'], check=True, timeout=5000)\n # Note: on windows, .git is created with a read-only flag \n shutil.rmtree(path/\".git\", onerror=rmtree_onerror)\n subprocess.run(\"git init\".split(), cwd=path, check=True)\n subprocess.run(\"git add .\".split(), cwd=path, check=True)\n subprocess.run(\"git commit -am \\\"Initial\\\"\".split(), cwd=path, check=True)\n \n print(f\"Created a new repo for project {name}. Please edit settings.ini and run nbdev_build_lib to get started.\")\n except Exception as e:\n print(\"An error occured while copying nbdev project template:\")\n print(e)\n if os.path.isdir(path): \n try:\n shutil.rmtree(path, onerror=rmtree_onerror)\n except Exception as e2:\n print(f\"An error occured while cleaning up. Failed to delete {path}:\")\n print(e2)", "_____no_output_____" ] ], [ [ "`nbdev_new` is a command line tool that creates a new nbdev project based on the [nbdev_template repo](https://github.com/fastai/nbdev_template). You can use a custom template by passing in `template_git_repo`. It'll initialize a new git repository and commit the new project.\n\nAfter you run `nbdev_new`, please edit `settings.ini` and run `nbdev_build_lib`.", "_____no_output_____" ], [ "## Export -", "_____no_output_____" ] ], [ [ "%nbdev_hide\nnotebook2script()", "Converted 00_export.ipynb.\nConverted 01_sync.ipynb.\nConverted 02_showdoc.ipynb.\nConverted 03_export2html.ipynb.\nConverted 04_test.ipynb.\nConverted 05_merge.ipynb.\nConverted 06_cli.ipynb.\nConverted 07_clean.ipynb.\nConverted 08_flag_tests.ipynb.\nConverted 99_search.ipynb.\nConverted index.ipynb.\nConverted tutorial.ipynb.\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "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", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ] ]
cb6553624d1307ab87357f5f6405e61306451352
308,069
ipynb
Jupyter Notebook
ETL_Practice.ipynb
selango007/Movies-ETL
4fd7a046deeaec33a7db899bc0481148b2466da6
[ "MIT" ]
null
null
null
ETL_Practice.ipynb
selango007/Movies-ETL
4fd7a046deeaec33a7db899bc0481148b2466da6
[ "MIT" ]
null
null
null
ETL_Practice.ipynb
selango007/Movies-ETL
4fd7a046deeaec33a7db899bc0481148b2466da6
[ "MIT" ]
null
null
null
49.496947
17,460
0.551811
[ [ [ "import json\nimport pandas as pd\nimport numpy as np\nimport re", "_____no_output_____" ], [ "file_dir = '/Users/sivaelango/desktop/Analysis Projects/Movies-ETL'", "_____no_output_____" ], [ "with open(f'{file_dir}/wikipedia-movies.json', mode='r') as file:\n wiki_movies_raw = json.load(file)", "_____no_output_____" ], [ "len(wiki_movies_raw)", "_____no_output_____" ], [ "# First 5 records\nwiki_movies_raw[:5]", "_____no_output_____" ], [ "# Last 5 records\nwiki_movies_raw[-5:]", "_____no_output_____" ], [ "# Some records in the middle\nwiki_movies_raw[3600:3605]", "_____no_output_____" ], [ "kaggle_metadata = pd.read_csv(f'{file_dir}/movies_metadata.csv', low_memory=False)\nratings = pd.read_csv(f'{file_dir}/ratings.csv')", "_____no_output_____" ], [ "kaggle_metadata.sample(n=5)", "_____no_output_____" ], [ "ratings.sample(n=5)", "_____no_output_____" ], [ "wiki_movies_df = pd.DataFrame(wiki_movies_raw)\nwiki_movies_df.head()", "_____no_output_____" ], [ "wiki_movies_df.columns.tolist()", "_____no_output_____" ], [ "wiki_movies = [movie for movie in wiki_movies_raw\n if ('Director' in movie or 'Directed by' in movie)\n and 'imdb_link' in movie]\nlen(wiki_movies)", "_____no_output_____" ], [ "wiki_movies_df = pd.DataFrame(wiki_movies)\nwiki_movies_df.head()", "_____no_output_____" ], [ "wiki_movies = [movie for movie in wiki_movies_raw\n if ('Director' in movie or 'Directed by' in movie)\n and 'imdb_link' in movie\n and 'No. of episodes' not in movie]", "_____no_output_____" ], [ "wiki_movies_df = pd.DataFrame(wiki_movies)\nwiki_movies_df.head()", "_____no_output_____" ], [ "wiki_movies_df[wiki_movies_df['Arabic'].notnull()]", "_____no_output_____" ], [ "wiki_movies_df[wiki_movies_df['Arabic'].notnull()]['url']", "_____no_output_____" ], [ "sorted(wiki_movies_df.columns.tolist())", "_____no_output_____" ], [ "def clean_movie(movie):\n movie = dict(movie) #create a non-destructive copy\n alt_titles = {}\n \n for key in ['Also known as','Arabic','Cantonese','Chinese','French',\n 'Hangul','Hebrew','Hepburn','Japanese','Literally',\n 'Mandarin','McCune–Reischauer','Original title','Polish',\n 'Revised Romanization','Romanized','Russian',\n 'Simplified','Traditional','Yiddish']:\n if key in movie:\n alt_titles[key] = movie[key]\n movie.pop(key)\n if len(alt_titles) > 0:\n movie['alt_titles'] = alt_titles\n \n # merge column names\n def change_column_name(old_name, new_name):\n if old_name in movie:\n movie[new_name] = movie.pop(old_name)\n change_column_name('Adaptation by', 'Writer(s)')\n change_column_name('Country of origin', 'Country')\n change_column_name('Directed by', 'Director')\n change_column_name('Distributed by', 'Distributor')\n change_column_name('Edited by', 'Editor(s)')\n change_column_name('Length', 'Running time')\n change_column_name('Original release', 'Release date')\n change_column_name('Music by', 'Composer(s)')\n change_column_name('Produced by', 'Producer(s)')\n change_column_name('Producer', 'Producer(s)')\n change_column_name('Productioncompanies ', 'Production company(s)')\n change_column_name('Productioncompany ', 'Production company(s)')\n change_column_name('Released', 'Release Date')\n change_column_name('Release Date', 'Release date')\n change_column_name('Screen story by', 'Writer(s)')\n change_column_name('Screenplay by', 'Writer(s)')\n change_column_name('Story by', 'Writer(s)')\n change_column_name('Theme music composer', 'Composer(s)')\n change_column_name('Written by', 'Writer(s)')\n \n return movie", "_____no_output_____" ], [ "clean_movies = [clean_movie(movie) for movie in wiki_movies]", "_____no_output_____" ], [ "wiki_movies_df = pd.DataFrame(clean_movies)\nsorted(wiki_movies_df.columns.tolist())", "_____no_output_____" ], [ "wiki_movies_df['imdb_id'] = wiki_movies_df['imdb_link'].str.extract(r'(tt\\d{7})')", "_____no_output_____" ], [ "wiki_movies_df['imdb_id']", "_____no_output_____" ], [ "wiki_movies_df.drop_duplicates(subset='imdb_id', inplace=True)\nprint(len(wiki_movies_df))\nwiki_movies_df.head()", "7033\n" ], [ "[[column,wiki_movies_df[column].isnull().sum()] for column in wiki_movies_df.columns]", "_____no_output_____" ], [ "wiki_columns_to_keep = [column for column in wiki_movies_df.columns if wiki_movies_df[column].isnull().sum() < len(wiki_movies_df) * 0.9]\nwiki_movies_df = wiki_movies_df[wiki_columns_to_keep]", "_____no_output_____" ], [ "wiki_movies_df.dtypes", "_____no_output_____" ], [ "box_office = wiki_movies_df['Box office'].dropna()", "_____no_output_____" ], [ "def is_not_a_string(x):\n return type(x) != str", "_____no_output_____" ], [ "box_office[box_office.map(is_not_a_string)]", "_____no_output_____" ], [ "lambda x: type(x) != str", "_____no_output_____" ], [ "box_office[box_office.map(lambda x: type(x) != str)]", "_____no_output_____" ], [ "box_office = box_office.apply(lambda x: ' '.join(x) if type(x) == list else x)", "_____no_output_____" ], [ "form_one = r'\\$\\d+\\.?\\d*\\s*[mb]illion'\nbox_office.str.contains(form_one, flags=re.IGNORECASE, na=False).sum()", "_____no_output_____" ], [ "form_two = r'\\$\\d{1,3}(?:,\\d{3})+'\nbox_office.str.contains(form_two, flags=re.IGNORECASE, na=False).sum()", "_____no_output_____" ], [ "matches_form_one = box_office.str.contains(form_one, flags=re.IGNORECASE, na=False)\nmatches_form_two = box_office.str.contains(form_two, flags=re.IGNORECASE, na=False)", "_____no_output_____" ], [ "box_office[~matches_form_one & ~matches_form_two]", "_____no_output_____" ], [ "form_one = r'\\$\\s*\\d+\\.?\\d*\\s*[mb]illion'\nform_two = r'\\$\\\\s*d{1,3}(?:,\\d{3})+(?!\\s[mb]illion)'\nmatches_form_one = box_office.str.contains(form_one, flags=re.IGNORECASE, na=False)\nmatches_form_two = box_office.str.contains(form_two, flags=re.IGNORECASE, na=False)\nbox_office[~matches_form_one & ~matches_form_two]", "_____no_output_____" ], [ "box_office = box_office.str.replace(r'\\$.*[-—–](?![a-z])', '$', regex=True)", "_____no_output_____" ], [ "form_one = r'\\$\\s*\\d+\\.?\\d*\\s*[mb]illi?on'", "_____no_output_____" ], [ "box_office.str.extract(f'({form_one}|{form_two})')", "_____no_output_____" ], [ "def parse_dollars(s):\n # if s is not a string, return NaN\n if type(s) != str:\n return np.nan\n\n # if input is of the form $###.# million\n if re.match(r'\\$\\s*\\d+\\.?\\d*\\s*milli?on', s, flags=re.IGNORECASE):\n\n # remove dollar sign and \" million\"\n s = re.sub('\\$|\\s|[a-zA-Z]','', s)\n\n # convert to float and multiply by a million\n value = float(s) * 10**6\n\n # return value\n return value\n\n # if input is of the form $###.# billion\n elif re.match(r'\\$\\s*\\d+\\.?\\d*\\s*billi?on', s, flags=re.IGNORECASE):\n\n # remove dollar sign and \" billion\"\n s = re.sub('\\$|\\s|[a-zA-Z]','', s)\n\n # convert to float and multiply by a billion\n value = float(s) * 10**9\n\n # return value\n return value\n\n # if input is of the form $###,###,###\n elif re.match(r'\\$\\s*\\d{1,3}(?:[,\\.]\\d{3})+(?!\\s[mb]illion)', s, flags=re.IGNORECASE):\n\n # remove dollar sign and commas\n s = re.sub('\\$|,','', s)\n\n # convert to float\n value = float(s)\n\n # return value\n return value\n\n # otherwise, return NaN\n else:\n return np.nan", "_____no_output_____" ], [ "wiki_movies_df['box_office'] = box_office.str.extract(f'({form_one}|{form_two})', flags=re.IGNORECASE)[0].apply(parse_dollars)", "_____no_output_____" ], [ "wiki_movies_df['box_office']", "_____no_output_____" ], [ "wiki_movies_df.drop('Box office', axis=1, inplace=True)", "_____no_output_____" ], [ "budget = wiki_movies_df['Budget'].dropna()", "_____no_output_____" ], [ "budget = budget.map(lambda x: ' '.join(x) if type(x) == list else x)", "_____no_output_____" ], [ "budget = budget.str.replace(r'\\$.*[-—–](?![a-z])', '$', regex=True)", "_____no_output_____" ], [ "matches_form_one = budget.str.contains(form_one, flags=re.IGNORECASE, na=False)\nmatches_form_two = budget.str.contains(form_two, flags=re.IGNORECASE, na=False)\nbudget[~matches_form_one & ~matches_form_two]", "_____no_output_____" ], [ "budget = budget.str.replace(r'\\[\\d+\\]\\s*', '')\nbudget[~matches_form_one & ~matches_form_two]", "<ipython-input-51-a146e32379e0>:1: FutureWarning: The default value of regex will change from True to False in a future version.\n budget = budget.str.replace(r'\\[\\d+\\]\\s*', '')\n" ], [ "wiki_movies_df['budget'] = budget.str.extract(f'({form_one}|{form_two})', flags=re.IGNORECASE)[0].apply(parse_dollars)", "_____no_output_____" ], [ "wiki_movies_df.drop('Budget', axis=1, inplace=True)", "_____no_output_____" ], [ "release_date = wiki_movies_df['Release date'].dropna().apply(lambda x: ' '.join(x) if type(x) == list else x)", "_____no_output_____" ], [ "date_form_one = r'(?:January|February|March|April|May|June|July|August|September|October|November|December)\\s[123]?\\d,\\s\\d{4}'\ndate_form_two = r'\\d{4}.[01]\\d.[0123]\\d'\ndate_form_three = r'(?:January|February|March|April|May|June|July|August|September|October|November|December)\\s\\d{4}'\ndate_form_four = r'\\d{4}'", "_____no_output_____" ], [ "release_date.str.extract(f'({date_form_one}|{date_form_two}|{date_form_three}|{date_form_four})', flags=re.IGNORECASE)", "_____no_output_____" ], [ "wiki_movies_df['release_date'] = pd.to_datetime(release_date.str.extract(f'({date_form_one}|{date_form_two}|{date_form_three}|{date_form_four})')[0], infer_datetime_format=True)", "_____no_output_____" ], [ "running_time = wiki_movies_df['Running time'].dropna().apply(lambda x: ' '.join(x) if type(x) == list else x)", "_____no_output_____" ], [ "running_time.str.contains(r'^\\d*\\s*minutes$', flags=re.IGNORECASE, na=False).sum()", "_____no_output_____" ], [ "running_time[running_time.str.contains(r'^\\d*\\s*minutes$', flags=re.IGNORECASE, na=False) != True]", "_____no_output_____" ], [ "running_time.str.contains(r'^\\d*\\s*m', flags=re.IGNORECASE, na=False).sum()", "_____no_output_____" ], [ "running_time[running_time.str.contains(r'^\\d*\\s*m', flags=re.IGNORECASE, na=False) != True]", "_____no_output_____" ], [ "running_time_extract = running_time.str.extract(r'(\\d+)\\s*ho?u?r?s?\\s*(\\d*)|(\\d+)\\s*m')", "_____no_output_____" ], [ "running_time_extract = running_time_extract.apply(lambda col: pd.to_numeric(col, errors='coerce')).fillna(0)", "_____no_output_____" ], [ "wiki_movies_df['running_time'] = running_time_extract.apply(lambda row: row[0]*60 + row[1] if row[2] == 0 else row[2], axis=1)", "_____no_output_____" ], [ "wiki_movies_df.drop('Running time', axis=1, inplace=True)", "_____no_output_____" ], [ "kaggle_metadata.dtypes", "_____no_output_____" ], [ "kaggle_metadata['adult'].value_counts()", "_____no_output_____" ], [ "kaggle_metadata[~kaggle_metadata['adult'].isin(['True','False'])]", "_____no_output_____" ], [ "kaggle_metadata = kaggle_metadata[kaggle_metadata['adult'] == 'False'].drop('adult',axis='columns')", "_____no_output_____" ], [ "kaggle_metadata['video'].value_counts()", "_____no_output_____" ], [ "kaggle_metadata['video'] == 'True'", "_____no_output_____" ], [ "kaggle_metadata['video'] = kaggle_metadata['video'] == 'True'", "_____no_output_____" ], [ "kaggle_metadata['budget'] = kaggle_metadata['budget'].astype(int)\nkaggle_metadata['id'] = pd.to_numeric(kaggle_metadata['id'], errors='raise')\nkaggle_metadata['popularity'] = pd.to_numeric(kaggle_metadata['popularity'], errors='raise')", "_____no_output_____" ], [ "kaggle_metadata['release_date'] = pd.to_datetime(kaggle_metadata['release_date'])", "_____no_output_____" ], [ "ratings.info(null_counts=True)", "<ipython-input-76-ed915c4d3989>:1: FutureWarning: null_counts is deprecated. Use show_counts instead\n ratings.info(null_counts=True)\n" ], [ "pd.to_datetime(ratings['timestamp'], unit='s')", "_____no_output_____" ], [ "ratings['timestamp'] = pd.to_datetime(ratings['timestamp'], unit='s')", "_____no_output_____" ], [ "pd.options.display.float_format = '{:20,.2f}'.format\nratings['rating'].plot(kind='hist')\nratings['rating'].describe()", "_____no_output_____" ], [ "movies_df = pd.merge(wiki_movies_df, kaggle_metadata, on='imdb_id', suffixes=['_wiki','_kaggle'])", "_____no_output_____" ], [ "movies_df[['title_wiki','title_kaggle']]", "_____no_output_____" ], [ "movies_df[movies_df['title_wiki'] != movies_df['title_kaggle']][['title_wiki','title_kaggle']]", "_____no_output_____" ], [ "# Show any rows where title_kaggle is empty\nmovies_df[(movies_df['title_kaggle'] == '') | (movies_df['title_kaggle'].isnull())]", "_____no_output_____" ], [ "movies_df.fillna(0).plot(x='running_time', y='runtime', kind='scatter')", "_____no_output_____" ], [ "movies_df.fillna(0).plot(x='budget_wiki',y='budget_kaggle', kind='scatter')", "_____no_output_____" ], [ "movies_df.fillna(0).plot(x='box_office', y='revenue', kind='scatter')", "_____no_output_____" ], [ "movies_df.fillna(0)[movies_df['box_office'] < 10**9].plot(x='box_office', y='revenue', kind='scatter')", "_____no_output_____" ], [ "movies_df[['release_date_wiki','release_date_kaggle']].plot(x='release_date_wiki', y='release_date_kaggle', style='.')", "_____no_output_____" ], [ "movies_df[(movies_df['release_date_wiki'] > '1996-01-01') & (movies_df['release_date_kaggle'] < '1965-01-01')]", "_____no_output_____" ], [ "movies_df[(movies_df['release_date_wiki'] > '1996-01-01') & (movies_df['release_date_kaggle'] < '1965-01-01')].index", "_____no_output_____" ], [ "movies_df = movies_df.drop(movies_df[(movies_df['release_date_wiki'] > '1996-01-01') & (movies_df['release_date_kaggle'] < '1965-01-01')].index)", "_____no_output_____" ], [ "movies_df[movies_df['release_date_wiki'].isnull()]", "_____no_output_____" ], [ "movies_df['Language'].value_counts()", "_____no_output_____" ], [ "movies_df['Language'].apply(lambda x: tuple(x) if type(x) == list else x).value_counts(dropna=False)", "_____no_output_____" ], [ "movies_df['original_language'].value_counts(dropna=False)", "_____no_output_____" ], [ "movies_df[['Production company(s)','production_companies']]", "_____no_output_____" ], [ "movies_df.drop(columns=['title_wiki','release_date_wiki','Language','Production company(s)'], inplace=True)", "_____no_output_____" ], [ "def fill_missing_kaggle_data(df, kaggle_column, wiki_column):\n df[kaggle_column] = df.apply(\n lambda row: row[wiki_column] if row[kaggle_column] == 0 else row[kaggle_column]\n , axis=1)\n df.drop(columns=wiki_column, inplace=True)", "_____no_output_____" ], [ "fill_missing_kaggle_data(movies_df, 'runtime', 'running_time')\nfill_missing_kaggle_data(movies_df, 'budget_kaggle', 'budget_wiki')\nfill_missing_kaggle_data(movies_df, 'revenue', 'box_office')\nmovies_df", "_____no_output_____" ], [ "for col in movies_df.columns:\n lists_to_tuples = lambda x: tuple(x) if type(x) == list else x\n value_counts = movies_df[col].apply(lists_to_tuples).value_counts(dropna=False)\n num_values = len(value_counts)\n if num_values == 1:\n print(col)", "video\n" ], [ "movies_df['video'].value_counts(dropna=False)", "_____no_output_____" ], [ "movies_df = movies_df.loc[:, ['imdb_id','id','title_kaggle','original_title','tagline','belongs_to_collection','url','imdb_link',\n 'runtime','budget_kaggle','revenue','release_date_kaggle','popularity','vote_average','vote_count',\n 'genres','original_language','overview','spoken_languages','Country',\n 'production_companies','production_countries','Distributor',\n 'Producer(s)','Director','Starring','Cinematography','Editor(s)','Writer(s)','Composer(s)','Based on'\n ]]", "_____no_output_____" ], [ "movies_df.rename({'id':'kaggle_id',\n 'title_kaggle':'title',\n 'url':'wikipedia_url',\n 'budget_kaggle':'budget',\n 'release_date_kaggle':'release_date',\n 'Country':'country',\n 'Distributor':'distributor',\n 'Producer(s)':'producers',\n 'Director':'director',\n 'Starring':'starring',\n 'Cinematography':'cinematography',\n 'Editor(s)':'editors',\n 'Writer(s)':'writers',\n 'Composer(s)':'composers',\n 'Based on':'based_on'\n }, axis='columns', inplace=True)", "_____no_output_____" ], [ "rating_counts = ratings.groupby(['movieId','rating'], as_index=False).count()", "_____no_output_____" ], [ "rating_counts = ratings.groupby(['movieId','rating'], as_index=False).count() \\\n .rename({'userId':'count'}, axis=1)", "_____no_output_____" ], [ "rating_counts = ratings.groupby(['movieId','rating'], as_index=False).count() \\\n .rename({'userId':'count'}, axis=1) \\\n .pivot(index='movieId',columns='rating', values='count')", "_____no_output_____" ], [ "rating_counts.columns = ['rating_' + str(col) for col in rating_counts.columns]", "_____no_output_____" ], [ "movies_with_ratings_df = pd.merge(movies_df, rating_counts, left_on='kaggle_id', right_index=True, how='left')\n", "_____no_output_____" ], [ "movies_with_ratings_df[rating_counts.columns] = movies_with_ratings_df[rating_counts.columns].fillna(0)", "_____no_output_____" ], [ "from sqlalchemy import create_engine", "_____no_output_____" ], [ "#\"postgres://[user]:[password]@[location]:[port]/[database]\"\nfrom config import db_password", "_____no_output_____" ], [ "db_string = f\"postgresql://postgres:{db_password}@127.0.0.1:5432/movie_data\"", "_____no_output_____" ], [ "engine = create_engine(db_string)", "_____no_output_____" ], [ "movies_df.to_sql(name='movies', con=engine)", "_____no_output_____" ], [ "rows_imported = 0\nfor data in pd.read_csv(f'{file_dir}/ratings.csv', chunksize=1000000):\n\n print(f'importing rows {rows_imported} to {rows_imported + len(data)}...', end='')\n data.to_sql(name='ratings', con=engine, if_exists='append')\n rows_imported += len(data)\n\n print(f'Done.')", "importing rows 0 to 1000000...Done.\nimporting rows 1000000 to 2000000...Done.\nimporting rows 2000000 to 3000000...Done.\nimporting rows 3000000 to 4000000...Done.\nimporting rows 4000000 to 5000000...Done.\nimporting rows 5000000 to 6000000...Done.\nimporting rows 6000000 to 7000000...Done.\nimporting rows 7000000 to 8000000...Done.\nimporting rows 8000000 to 9000000...Done.\nimporting rows 9000000 to 10000000...Done.\nimporting rows 10000000 to 11000000...Done.\nimporting rows 11000000 to 12000000...Done.\nimporting rows 12000000 to 13000000...Done.\nimporting rows 13000000 to 14000000...Done.\nimporting rows 14000000 to 15000000...Done.\nimporting rows 15000000 to 16000000...Done.\nimporting rows 16000000 to 17000000...Done.\nimporting rows 17000000 to 18000000...Done.\nimporting rows 18000000 to 19000000...Done.\nimporting rows 19000000 to 20000000...Done.\nimporting rows 20000000 to 21000000...Done.\nimporting rows 21000000 to 22000000...Done.\nimporting rows 22000000 to 23000000...Done.\nimporting rows 23000000 to 24000000...Done.\nimporting rows 24000000 to 25000000...Done.\nimporting rows 25000000 to 26000000...Done.\nimporting rows 26000000 to 26024289...Done.\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "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", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb65669cdbdf689c4dad40895f8e76d85e510ae1
19,514
ipynb
Jupyter Notebook
notebooks/Evolution_walk_through.ipynb
Dheeru66k/DataScience_COVID19_analysis
49d1fabaeb7f4ddacc2361fd5f586066116ef25f
[ "FTL" ]
null
null
null
notebooks/Evolution_walk_through.ipynb
Dheeru66k/DataScience_COVID19_analysis
49d1fabaeb7f4ddacc2361fd5f586066116ef25f
[ "FTL" ]
null
null
null
notebooks/Evolution_walk_through.ipynb
Dheeru66k/DataScience_COVID19_analysis
49d1fabaeb7f4ddacc2361fd5f586066116ef25f
[ "FTL" ]
null
null
null
34.355634
208
0.506611
[ [ [ "import os\nif os.path.split(os.getcwd())[-1]=='notebooks':\n os.chdir(\"../\")\n\n'Your base path is at: '+os.path.split(os.getcwd())[-1]", "_____no_output_____" ] ], [ [ "# Update Data", "_____no_output_____" ] ], [ [ "# %load src/data/get_data.py\n\nimport subprocess\nimport os\n\nimport pandas as pd\nimport numpy as np\n\nfrom datetime import datetime\n\nimport requests\nimport json\n\ndef get_johns_hopkins():\n ''' Get data by a git pull request, the source code has to be pulled first\n Result is stored in the predifined csv structure\n '''\n git_pull = subprocess.Popen( \"/usr/bin/git pull\" ,\n cwd = os.path.dirname( 'data/raw/COVID-19/' ),\n shell = True,\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE )\n (out, error) = git_pull.communicate()\n\n\n print(\"Error : \" + str(error))\n print(\"out : \" + str(out))\n\n\ndef get_current_data_germany():\n ''' Get current data from germany, attention API endpoint not too stable\n Result data frame is stored as pd.DataFrame\n\n '''\n # 16 states\n #data=requests.get('https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/Coronaf%C3%A4lle_in_den_Bundesl%C3%A4ndern/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json')\n\n # 400 regions / Landkreise\n data=requests.get('https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json')\n\n json_object=json.loads(data.content)\n full_list=[]\n for pos,each_dict in enumerate (json_object['features'][:]):\n full_list.append(each_dict['attributes'])\n\n pd_full_list=pd.DataFrame(full_list)\n pd_full_list.to_csv('data/processed/COVID_final_set.csv',sep=';')\n print(' Number of regions rows: '+str(pd_full_list.shape[0]))\n\nif __name__ == '__main__':\n get_johns_hopkins()\n get_current_data_germany()\n", "Error : b'The system cannot find the path specified.\\r\\n'\nout : b''\n Number of regions rows: 412\n" ] ], [ [ "# 2. Process pipeline \n", "_____no_output_____" ] ], [ [ "# %load src/data/process_JH_data.py\nimport pandas as pd\nimport numpy as np\n\nfrom datetime import datetime\n\n\ndef store_relational_JH_data():\n ''' Transformes the COVID data in a relational data set\n\n '''\n\n data_path='data/raw/COVID-19/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv'\n pd_raw=pd.read_csv(data_path)\n\n pd_data_base=pd_raw.rename(columns={'Country/Region':'country',\n 'Province/State':'state'})\n\n pd_data_base['state']=pd_data_base['state'].fillna('no')\n\n pd_data_base=pd_data_base.drop(['Lat','Long'],axis=1)\n\n\n pd_relational_model=pd_data_base.set_index(['state','country']) \\\n .T \\\n .stack(level=[0,1]) \\\n .reset_index() \\\n .rename(columns={'level_0':'date',\n 0:'confirmed'},\n )\n\n pd_relational_model['date']=pd_relational_model.date.astype('datetime64[ns]')\n\n pd_relational_model.to_csv('data/processed/COVID_final_set.csv',sep=';',index=False)\n print(' Number of rows stored: '+str(pd_relational_model.shape[0]))\n\nif __name__ == '__main__':\n\n store_relational_JH_data()\n", " Number of rows stored: 56658\n" ] ], [ [ "# 3. Filter and Doubling rate Calculation", "_____no_output_____" ] ], [ [ "# %load src/features/build_features.py\n\nimport numpy as np\nfrom sklearn import linear_model\nreg = linear_model.LinearRegression(fit_intercept=True)\nimport pandas as pd\n\nfrom scipy import signal\n\n\ndef get_doubling_time_via_regression(in_array):\n ''' Use a linear regression to approximate the doubling rate\n\n Parameters:\n ----------\n in_array : pandas.series\n\n Returns:\n ----------\n Doubling rate: double\n '''\n\n y = np.array(in_array)\n X = np.arange(-1,2).reshape(-1, 1)\n\n assert len(in_array)==3\n reg.fit(X,y)\n intercept=reg.intercept_\n slope=reg.coef_\n\n return intercept/slope\n\n\ndef savgol_filter(df_input,column='confirmed',window=5):\n ''' Savgol Filter which can be used in groupby apply function (data structure kept)\n\n parameters:\n ----------\n df_input : pandas.series\n column : str\n window : int\n used data points to calculate the filter result\n\n Returns:\n ----------\n df_result: pd.DataFrame\n the index of the df_input has to be preserved in result\n '''\n\n degree=1\n df_result=df_input\n\n filter_in=df_input[column].fillna(0) # attention with the neutral element here\n\n result=signal.savgol_filter(np.array(filter_in),\n window, # window size used for filtering\n 1)\n df_result[str(column+'_filtered')]=result\n return df_result\n\ndef rolling_reg(df_input,col='confirmed'):\n ''' Rolling Regression to approximate the doubling time'\n\n Parameters:\n ----------\n df_input: pd.DataFrame\n col: str\n defines the used column\n Returns:\n ----------\n result: pd.DataFrame\n '''\n days_back=3\n result=df_input[col].rolling(\n window=days_back,\n min_periods=days_back).apply(get_doubling_time_via_regression,raw=False)\n\n\n\n return result\n\n\n\n\ndef calc_filtered_data(df_input,filter_on='confirmed'):\n ''' Calculate savgol filter and return merged data frame\n\n Parameters:\n ----------\n df_input: pd.DataFrame\n filter_on: str\n defines the used column\n Returns:\n ----------\n df_output: pd.DataFrame\n the result will be joined as a new column on the input data frame\n '''\n\n must_contain=set(['state','country',filter_on])\n assert must_contain.issubset(set(df_input.columns)), ' Erro in calc_filtered_data not all columns in data frame'\n\n df_output=df_input.copy() # we need a copy here otherwise the filter_on column will be overwritten\n\n pd_filtered_result=df_output[['state','country',filter_on]].groupby(['state','country']).apply(savgol_filter)#.reset_index()\n\n #print('--+++ after group by apply')\n #print(pd_filtered_result[pd_filtered_result['country']=='Germany'].tail())\n\n #df_output=pd.merge(df_output,pd_filtered_result[['index',str(filter_on+'_filtered')]],on=['index'],how='left')\n df_output=pd.merge(df_output,pd_filtered_result[[str(filter_on+'_filtered')]],left_index=True,right_index=True,how='left')\n #print(df_output[df_output['country']=='Germany'].tail())\n return df_output.copy()\n\n\n\n\n\ndef calc_doubling_rate(df_input,filter_on='confirmed'):\n ''' Calculate approximated doubling rate and return merged data frame\n\n Parameters:\n ----------\n df_input: pd.DataFrame\n filter_on: str\n defines the used column\n Returns:\n ----------\n df_output: pd.DataFrame\n the result will be joined as a new column on the input data frame\n '''\n\n must_contain=set(['state','country',filter_on])\n assert must_contain.issubset(set(df_input.columns)), ' Erro in calc_filtered_data not all columns in data frame'\n\n\n pd_DR_result= df_input.groupby(['state','country']).apply(rolling_reg,filter_on).reset_index()\n\n pd_DR_result=pd_DR_result.rename(columns={filter_on:filter_on+'_DR',\n 'level_2':'index'})\n\n #we do the merge on the index of our big table and on the index column after groupby\n df_output=pd.merge(df_input,pd_DR_result[['index',str(filter_on+'_DR')]],left_index=True,right_on=['index'],how='left')\n df_output=df_output.drop(columns=['index'])\n\n\n return df_output\n\n\nif __name__ == '__main__':\n test_data_reg=np.array([2,4,6])\n result=get_doubling_time_via_regression(test_data_reg)\n print('the test slope is: '+str(result))\n\n pd_JH_data=pd.read_csv('data/processed/COVID_relational_confirmed.csv',sep=';',parse_dates=[0])\n pd_JH_data=pd_JH_data.sort_values('date',ascending=True).copy()\n\n #test_structure=pd_JH_data[((pd_JH_data['country']=='US')|\n # (pd_JH_data['country']=='Germany'))]\n\n pd_result_larg=calc_filtered_data(pd_JH_data)\n pd_result_larg=calc_doubling_rate(pd_result_larg)\n pd_result_larg=calc_doubling_rate(pd_result_larg,'confirmed_filtered')\n\n\n mask=pd_result_larg['confirmed']>100\n pd_result_larg['confirmed_filtered_DR']=pd_result_larg['confirmed_filtered_DR'].where(mask, other=np.NaN)\n pd_result_larg.to_csv('data/processed/COVID_final_set.csv',sep=';',index=False)\n print(pd_result_larg.tail())\n", "the test slope is: [2.]\n date state country confirmed confirmed_filtered confirmed_DR \\\n20234 2020-08-21 no Barbados 157.0 157.2 156.000000 \n20447 2020-08-21 no Belarus 70111.0 70089.0 451.316129 \n20660 2020-08-21 no Belgium 80894.0 80796.6 113.333804 \n17678 2020-08-21 no Albania 8119.0 8120.8 51.895765 \n56657 2020-08-21 no Zimbabwe 5815.0 5854.0 66.678295 \n\n confirmed_filtered_DR \n20234 119.923077 \n20447 529.575322 \n20660 133.638560 \n17678 51.291050 \n56657 41.389573 \n" ] ], [ [ "# Visual Board", "_____no_output_____" ] ], [ [ "# %load src/visualization/visualize.py\nimport pandas as pd\nimport numpy as np\n\nimport dash\ndash.__version__\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output,State\n\nimport plotly.graph_objects as go\n\nimport os\nprint(os.getcwd())\ndf_input_large=pd.read_csv('data/processed/COVID_final_set.csv',sep=';')\n\n\nfig = go.Figure()\n\napp = dash.Dash()\napp.layout = html.Div([\n\n dcc.Markdown('''\n # Applied Data Science on COVID-19 data\n\n Goal of the project is to teach data science by applying a cross industry standard process,\n it covers the full walkthrough of: automated data gathering, data transformations,\n filtering and machine learning to approximating the doubling time, and\n (static) deployment of responsive dashboard.\n\n '''),\n\n dcc.Markdown('''\n ## Multi-Select Country for visualization\n '''),\n\n\n dcc.Dropdown(\n id='country_drop_down',\n options=[ {'label': each,'value':each} for each in df_input_large['country'].unique()],\n value=['US', 'Germany','Italy'], # which are pre-selected\n multi=True\n ),\n\n dcc.Markdown('''\n ## Select Timeline of confirmed COVID-19 cases or the approximated doubling time\n '''),\n\n\n dcc.Dropdown(\n id='doubling_time',\n options=[\n {'label': 'Timeline Confirmed ', 'value': 'confirmed'},\n {'label': 'Timeline Confirmed Filtered', 'value': 'confirmed_filtered'},\n {'label': 'Timeline Doubling Rate', 'value': 'confirmed_DR'},\n {'label': 'Timeline Doubling Rate Filtered', 'value': 'confirmed_filtered_DR'},\n ],\n value='confirmed',\n multi=False\n ),\n\n dcc.Graph(figure=fig, id='main_window_slope')\n])\n\n\n\[email protected](\n Output('main_window_slope', 'figure'),\n [Input('country_drop_down', 'value'),\n Input('doubling_time', 'value')])\ndef update_figure(country_list,show_doubling):\n\n\n if 'doubling_rate' in show_doubling:\n my_yaxis={'type':\"log\",\n 'title':'Approximated doubling rate over 3 days (larger numbers are better #stayathome)'\n }\n else:\n my_yaxis={'type':\"log\",\n 'title':'Confirmed infected people (source johns hopkins csse, log-scale)'\n }\n\n\n traces = []\n for each in country_list:\n\n df_plot=df_input_large[df_input_large['country']==each]\n\n if show_doubling=='doubling_rate_filtered':\n df_plot=df_plot[['state','country','confirmed','confirmed_filtered','confirmed_DR','confirmed_filtered_DR','date']].groupby(['country','date']).agg(np.mean).reset_index()\n else:\n df_plot=df_plot[['state','country','confirmed','confirmed_filtered','confirmed_DR','confirmed_filtered_DR','date']].groupby(['country','date']).agg(np.sum).reset_index()\n #print(show_doubling)\n\n\n traces.append(dict(x=df_plot.date,\n y=df_plot[show_doubling],\n mode='markers+lines',\n opacity=0.9,\n name=each\n )\n )\n\n return {\n 'data': traces,\n 'layout': dict (\n width=1280,\n height=720,\n\n xaxis={'title':'Timeline',\n 'tickangle':-45,\n 'nticks':20,\n 'tickfont':dict(size=14,color=\"#7f7f7f\"),\n },\n\n yaxis=my_yaxis\n )\n }\n\nif __name__ == '__main__':\n\n app.run_server(debug=True, use_reloader=False)\n", "D:\\Data_Science\\ads_covid-19\nDash is running on http://127.0.0.1:8050/\n\n Warning: This is a development server. Do not use app.run_server\n in production, use a production WSGI server like gunicorn instead.\n\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb657fef868300e7989c9856fae649824a9383e7
21,278
ipynb
Jupyter Notebook
tutorials/Using_a_pretrained_model_for_inference.ipynb
stjordanis/vissl
8800989f9bf073693b777c14ea01b585d4b306d6
[ "MIT" ]
3
2021-07-08T15:06:49.000Z
2021-08-13T18:55:02.000Z
tutorials/Using_a_pretrained_model_for_inference.ipynb
stjordanis/vissl
8800989f9bf073693b777c14ea01b585d4b306d6
[ "MIT" ]
2
2021-07-25T15:46:07.000Z
2021-08-11T10:08:53.000Z
tutorials/Using_a_pretrained_model_for_inference.ipynb
stjordanis/vissl
8800989f9bf073693b777c14ea01b585d4b306d6
[ "MIT" ]
2
2021-07-08T15:15:55.000Z
2021-08-25T14:16:01.000Z
42.051383
256
0.572375
[ [ [ "# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.", "_____no_output_____" ] ], [ [ "# Loading a pre-trained model in inference mode\n\nIn this tutorial, we will show how to instantiate a model pre-trained with VISSL to use it in inference mode to extract features from its trunk.\n\nWe will concentrate on loading a model pre-trained via SimCLR to use it in inference mode and extract features from an image, but this whole training is portable to any another pre-training methods (MoCo, SimSiam, SwAV, etc).\n\nThrough it, we will show:\n\n1. How to instantiate a model associated to a pre-training configuration\n2. Load the weights of the pre-trained model (taking the weights from our Model Zoo)\n3. Use it to extract features associated to the VISSL Logo\n\n**NOTE:** For a tutorial focused on how to use VISSL to schedule a feature extraction job, please refer to [the dedicated tutorial](https://colab.research.google.com/github/facebookresearch/vissl/blob/stable/tutorials/Feature_Extraction.ipynb)\n\n**NOTE:** Please ensure your Collab Notebook has GPU available: `Edit -> Notebook Settings -> select GPU`.\n\n**NOTE:** You can make a copy of this tutorial by `File -> Open in playground mode` and make changes there. DO NOT request access to this tutorial.\n", "_____no_output_____" ], [ "## Install VISSL\n\nWe will start this tutorial by installing VISSL, following the instructions [here](https://github.com/facebookresearch/vissl/blob/master/INSTALL.md#install-vissl-pip-package).", "_____no_output_____" ] ], [ [ "# Install: PyTorch (we assume 1.5.1 but VISSL works with all PyTorch versions >=1.4)\n!pip install torch==1.5.1+cu101 torchvision==0.6.1+cu101 -f https://download.pytorch.org/whl/torch_stable.html\n\n# install opencv\n!pip install opencv-python\n\n# install apex by checking system settings: cuda version, pytorch version, python version\nimport sys\nimport torch\nversion_str=\"\".join([\n f\"py3{sys.version_info.minor}_cu\",\n torch.version.cuda.replace(\".\",\"\"),\n f\"_pyt{torch.__version__[0:5:2]}\"\n])\nprint(version_str)\n\n# install apex (pre-compiled with optimizer C++ extensions and CUDA kernels)\n!pip install -f https://dl.fbaipublicfiles.com/vissl/packaging/apexwheels/{version_str}/download.html apex\n\n# install VISSL\n!pip install vissl", "Looking in links: https://download.pytorch.org/whl/torch_stable.html\nCollecting torch==1.5.1+cu101\n Using cached https://download.pytorch.org/whl/cu101/torch-1.5.1%2Bcu101-cp37-cp37m-linux_x86_64.whl\nRequirement already satisfied: torchvision==0.6.1+cu101 in /usr/local/lib/python3.7/dist-packages (0.6.1+cu101)\nRequirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from torch==1.5.1+cu101) (0.16.0)\nRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torch==1.5.1+cu101) (1.19.5)\nRequirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.7/dist-packages (from torchvision==0.6.1+cu101) (7.0.0)\n\u001b[31mERROR: torchtext 0.9.0 has requirement torch==1.8.0, but you'll have torch 1.5.1+cu101 which is incompatible.\u001b[0m\n\u001b[31mERROR: fairscale 0.3.2 has requirement torch>=1.6.0, but you'll have torch 1.5.1+cu101 which is incompatible.\u001b[0m\nInstalling collected packages: torch\n Found existing installation: torch 1.8.0\n Uninstalling torch-1.8.0:\n Successfully uninstalled torch-1.8.0\nSuccessfully installed torch-1.5.1+cu101\n" ] ], [ [ "VISSL should be successfuly installed by now and all the dependencies should be available.", "_____no_output_____" ] ], [ [ "import vissl\nimport tensorboard\nimport apex\nimport torch", "_____no_output_____" ] ], [ [ "## Loading a VISSL SimCLR pre-trained model\n", "_____no_output_____" ], [ "## Download the configuration\n\nVISSL provides yaml configuration files for training a SimCLR model [here](https://github.com/facebookresearch/vissl/tree/master/configs/config/pretrain/simclr). We will start by fetching the configuration files we need.", "_____no_output_____" ] ], [ [ "!mkdir -p configs/config/simclr\n!mkdir -p vissl/config\n!wget -q -O configs/config/simclr/simclr_8node_resnet.yaml https://raw.githubusercontent.com/facebookresearch/vissl/master/configs/config/pretrain/simclr/simclr_8node_resnet.yaml\n!wget -q -O vissl/config/defaults.yaml https://raw.githubusercontent.com/facebookresearch/vissl/master/vissl/config/defaults.yaml", "_____no_output_____" ] ], [ [ "\n\n```\n# This is formatted as code\n```\n\n## Download the ResNet-50 weights from the Model Zoo", "_____no_output_____" ] ], [ [ "!wget -q -O resnet_simclr.torch https://dl.fbaipublicfiles.com/vissl/model_zoo/simclr_rn101_1000ep_simclr_8node_resnet_16_07_20.35063cea/model_final_checkpoint_phase999.torch", "_____no_output_____" ] ], [ [ "## Create the model associated to the configuration\n\nLoad the configuration and merge it with the default configuration.", "_____no_output_____" ] ], [ [ "from omegaconf import OmegaConf\nfrom vissl.utils.hydra_config import AttrDict\n\nconfig = OmegaConf.load(\"configs/config/simclr/simclr_8node_resnet.yaml\")\ndefault_config = OmegaConf.load(\"vissl/config/defaults.yaml\")\ncfg = OmegaConf.merge(default_config, config)", "_____no_output_____" ] ], [ [ "Edit the configuration to freeze the trunk (inference mode) and ask for the extraction of the last layer feature.", "_____no_output_____" ] ], [ [ "cfg = AttrDict(cfg)\ncfg.config.MODEL.WEIGHTS_INIT.PARAMS_FILE = \"resnet_simclr.torch\"\ncfg.config.MODEL.FEATURE_EVAL_SETTINGS.EVAL_MODE_ON = True\ncfg.config.MODEL.FEATURE_EVAL_SETTINGS.FREEZE_TRUNK_ONLY = True\ncfg.config.MODEL.FEATURE_EVAL_SETTINGS.EXTRACT_TRUNK_FEATURES_ONLY = True\ncfg.config.MODEL.FEATURE_EVAL_SETTINGS.SHOULD_FLATTEN_FEATS = False\ncfg.config.MODEL.FEATURE_EVAL_SETTINGS.LINEAR_EVAL_FEAT_POOL_OPS_MAP = [[\"res5avg\", [\"Identity\", []]]]", "_____no_output_____" ] ], [ [ "And then build the model:", "_____no_output_____" ] ], [ [ "from vissl.models import build_model\n\nmodel = build_model(cfg.config.MODEL, cfg.config.OPTIMIZER)", "_____no_output_____" ] ], [ [ "## Loading the pre-trained weights", "_____no_output_____" ] ], [ [ "from classy_vision.generic.util import load_checkpoint\nfrom vissl.utils.checkpoint import init_model_from_weights\n\nweights = load_checkpoint(checkpoint_path=cfg.config.MODEL.WEIGHTS_INIT.PARAMS_FILE)\n\ninit_model_from_weights(\n config=cfg.config,\n model=model,\n state_dict=weights,\n state_dict_key_name=\"classy_state_dict\",\n skip_layers=[], # Use this if you do not want to load all layers\n)\n\nprint(\"Loaded...\")", "Loaded...\n" ] ], [ [ "## Trying the model on the VISSL Logo", "_____no_output_____" ] ], [ [ "!wget -q -O test_image.jpg https://raw.githubusercontent.com/facebookresearch/vissl/master/.github/logo/Logo_Color_Light_BG.png", "_____no_output_____" ], [ "from PIL import Image\nimport torchvision.transforms as transforms\n\nimage = Image.open(\"test_image.jpg\")\nimage = image.convert(\"RGB\")\n\npipeline = transforms.Compose([\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n])\nx = pipeline(image)\n\nfeatures = model(x.unsqueeze(0))", "_____no_output_____" ] ], [ [ "The output is a list with as many representation layers as required in the configuration (in our case, `cfg.config.MODEL.FEATURE_EVAL_SETTINGS.LINEAR_EVAL_FEAT_POOL_OPS_MAP` asks for one representation layer, so we have just one output.", "_____no_output_____" ] ], [ [ "features[0].shape", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cb6585aea528c26ccda0ff6b784894de02e867cf
50,896
ipynb
Jupyter Notebook
notebooks/sandbox.ipynb
paultanger/CampsitePredict
1985d3a207a724e278ab8a00c56560af45c14e92
[ "MIT" ]
null
null
null
notebooks/sandbox.ipynb
paultanger/CampsitePredict
1985d3a207a724e278ab8a00c56560af45c14e92
[ "MIT" ]
2
2020-08-29T01:02:04.000Z
2020-08-29T18:03:22.000Z
notebooks/sandbox.ipynb
paultanger/CampsitePredict
1985d3a207a724e278ab8a00c56560af45c14e92
[ "MIT" ]
null
null
null
299.388235
44,416
0.893921
[ [ [ "# generic imports\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy import stats\n# notebook settings\n%config IPCompleter.greedy=True\n%load_ext autoreload\n%autoreload 2 \n# precision and plot settings\nnum_precision = 3\nnp.set_printoptions(precision=num_precision, suppress=True)\npd.set_option('display.float_format', lambda x: f'{x:,.{num_precision}f}')\npd.set_option(\"display.precision\", num_precision)\npd.set_option('display.max_columns', None)\n\nplt.style.use('tableau-colorblind10')\nplt.rcParams['figure.figsize'] = [10, 6]\nplt.rcParams['font.size'] = 16\nplt.rcParams['legend.fontsize'] = 'large'\nplt.rcParams['figure.titlesize'] = 'medium'\nplt.rcParams['lines.linewidth'] = 2", "_____no_output_____" ], [ "data = pd.read_csv('../data/phase2_tasks.csv', keep_default_na=False)", "_____no_output_____" ], [ "#data", "_____no_output_____" ], [ "fig, ax = plt.subplots(1, figsize=(10,10))\ndata.plot.scatter(x='difficulty (10=hard)', y='value (10=valuable)', ax=ax, style=\"o\", s=50)\nax.set_xlim(2, 10)\nax.set_ylim(2, 10)\nfor i, (x , y) in enumerate(zip(data['difficulty (10=hard)'], data['value (10=valuable)'])):\n label = data['plot_label'][i]\n# label = \"{:.2f}\".format(y)\n # this method is called for each point\n plt.annotate(label, # this is the text\n (x, y), # this is the point to label\n textcoords=\"offset points\", # how to position the text\n xytext=(0,10), # distance from text to points (x,y)\n ha='center',\n fontsize='small'); # horizontal alignment can be left, right or center\nfig.tight_layout()\nplt.savefig('../images/phase2_priorities.png')", "_____no_output_____" ], [ "print(data.drop('plot_label', axis=1).to_markdown(index=False))", "| task | detail | notes | to do | difficulty (10=hard) | value (10=valuable) |\n|:-----------------------------------------------|:-------------------------------|:-------------------------------------------|:---------------|-----------------------:|----------------------:|\n| pull more images | more data more diversity | setup colab to run it | yes Sunday | 3 | 8 |\n| pull info deleted / closed | examine viability of this data | | yes Sunday | 4 | 5 |\n| sobel transformation | improve model? | write function | yes Monday | 5 | 3 |\n| transfer learning models | improve model? | | eval if needed | 7 | 5 |\n| object detection | new feature | chapter 14.. 489 485… YOLO.. Look once.. | maybe | 9 | 9 |\n| multiclassification | include other cols like binary | | yes Tuesday | 4 | 7 |\n| implement class weights | improve model? | | eval if needed | 4 | 6 |\n| NLP with higher level tokens than words | improve model? | | maybe | 6 | 6 |\n| specific camp and not camp images | new feature | | maybe | 8 | 4 |\n| Utilize NLP topics to aid image classification | new feature | | yes Monday | 8 | 7 |\n| moderator review app | new feature | | yes Wednesday | 6 | 9 |\n" ], [ "pd.__version__", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
cb6585bab73e5ff124d7afaad2bcf5c9e58f2538
990
ipynb
Jupyter Notebook
DDQN2.ipynb
ThaoNguyen1314/Bot.github.io
4cb8099854a83fc7c20e5d2e33cd2a32b372cd3a
[ "MIT" ]
null
null
null
DDQN2.ipynb
ThaoNguyen1314/Bot.github.io
4cb8099854a83fc7c20e5d2e33cd2a32b372cd3a
[ "MIT" ]
null
null
null
DDQN2.ipynb
ThaoNguyen1314/Bot.github.io
4cb8099854a83fc7c20e5d2e33cd2a32b372cd3a
[ "MIT" ]
null
null
null
23.023256
230
0.50303
[ [ [ "<a href=\"https://colab.research.google.com/github/ThaoNguyen1314/Bot.github.io/blob/main/DDQN2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code" ] ]
cb658c452e888bbb8809fec6fc4b43d91398bfa2
954,343
ipynb
Jupyter Notebook
time-series/lstm-forecasting.ipynb
DeloitteHux/tensor-house
8e9fb7685e33ed159b3bb1ff05eeb3db42dd2ee6
[ "Apache-2.0" ]
1
2021-07-28T10:32:46.000Z
2021-07-28T10:32:46.000Z
time-series/lstm-forecasting.ipynb
mmg-3/tensor-house
04cc8d299de5f5ceff4de8287ca824eaa21f8823
[ "Apache-2.0" ]
null
null
null
time-series/lstm-forecasting.ipynb
mmg-3/tensor-house
04cc8d299de5f5ceff4de8287ca824eaa21f8823
[ "Apache-2.0" ]
null
null
null
1,441.60574
336,192
0.953366
[ [ [ "# Enterprise Time Series Forecasting and Decomposition Using LSTM\n\nThis notebook is a tutorial on time series forecasting and decomposition using LSTM.\n* First, we generate a signal (time series) that includes several components that are commonly found in enterprise applications: trend, seasonality, covariates, and covariates with memory effects.\n* Second, we fit a basic LSTM model, produce the forecast, and introspect the evolution of the hidden state of the model.\n* Third, we fit the LSTM with attention model and visualize attention weights that provide some insights into the memory effects.\n\n## Detailed Description\nPlease see blog post [D006](https://github.com/ikatsov/tensor-house/blob/master/resources/descriptions.md) for more details. \n\n## Data\nThis notebook generates synthetic data internally, no external datset are used.\n\n---", "_____no_output_____" ], [ "# Step 1: Generate the Data\n\nWe generate a time series that includes a trend, seasonality, covariates, and covariates. This signals mimics some of the effects usually found in sales data (cannibalization, halo, pull forward, and other effects). The covariates are just independent variables, but they can enter the signal in two modes:\n* Linear. The covariate series is directly added to the main signal with some coeffecient. E.g. the link function is indentity.\n* Memory. The covariate is transformed using a link function that include some delay and can be nonlinear. We use a simple smoothing filter as a link function. We observe the original covariate, but the link function is unknown. ", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport datetime\nimport collections\nfrom matplotlib import pylab as plt\nplt.style.use('ggplot')\nimport seaborn as sns\nimport matplotlib.dates as mdates\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\npd.options.mode.chained_assignment = None\n\nimport tensorflow as tf\nfrom sklearn import preprocessing\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import LSTM, Dense, Input \nfrom tensorflow.keras.layers import Lambda, RepeatVector, Permute, Flatten, Activation, Multiply\nfrom tensorflow.keras.constraints import NonNeg\nfrom tensorflow.keras import backend as K\n\nfrom tensorflow.keras.regularizers import l1\nfrom tensorflow.keras.layers import LSTM\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\n \ndef step_series(n, mean, scale, n_steps):\n s = np.zeros(n)\n step_idx = np.random.randint(0, n, n_steps)\n value = mean\n for t in range(n):\n s[t] = value\n if t in step_idx:\n value = mean + scale * np.random.randn()\n return s\n\ndef linear_link(x): \n return x\n\ndef mem_link(x, length = 50):\n mfilter = np.exp(np.linspace(-10, 0, length))\n return np.convolve(x, mfilter/np.sum(mfilter), mode='same')\n\ndef create_signal(links = [linear_link, linear_link]):\n days_year = 365\n quaters_year = 4\n days_week = 7\n \n # three years of data, daily resolution\n idx = pd.date_range(start='2017-01-01', end='2020-01-01', freq='D') \n\n df = pd.DataFrame(index=idx, dtype=float)\n df = df.fillna(0.0)\n \n n = len(df.index)\n trend = np.zeros(n)\n seasonality = np.zeros(n)\n for t in range(n):\n trend[t] = 2.0 * t/n\n seasonality[t] = 4.0 * np.sin(np.pi * t/days_year*quaters_year)\n \n covariates = [step_series(n, 0, 1.0, 80), step_series(n, 0, 1.0, 80)]\n covariate_links = [ links[i](covariates[i]) for i in range(2) ]\n \n noise = 0.5 * np.random.randn(n)\n \n signal = trend + seasonality + np.sum(covariate_links, axis=0) + noise\n \n df['signal'], df['trend'], df['seasonality'], df['noise'] = signal, trend, seasonality, noise\n for i in range(2):\n df[f'covariate_0{i+1}'] = covariates[i]\n df[f'covariate_0{i+1}_link'] = covariate_links[i]\n \n return df\n\ndf = create_signal()\nfig, ax = plt.subplots(len(df.columns), figsize=(20, 15))\nfor i, c in enumerate(df.columns):\n ax[i].plot(df.index, df[c])\n ax[i].set_title(c)\n\nplt.tight_layout()\nplt.show()", "_____no_output_____" ] ], [ [ "# Step 2: Define and Fit the Basic LSTM Model\n\nWe fit LSTM model that consumes patches of the observed signal and covariates, i.e. each input sample is a matrix where rows are time steps and columns are observed metrics (signal, covariate, and calendar features).", "_____no_output_____" ] ], [ [ "#\n# engineer features and create input tensors\n#\ndef prepare_features_rnn(df): \n df_rnn = df[['signal', 'covariate_01', 'covariate_02']]\n df_rnn['year'] = df_rnn.index.year\n df_rnn['month'] = df_rnn.index.month\n df_rnn['day_of_year'] = df_rnn.index.dayofyear\n \n def normalize(df):\n x = df.values \n min_max_scaler = preprocessing.MinMaxScaler()\n x_scaled = min_max_scaler.fit_transform(x)\n return pd.DataFrame(x_scaled, index=df.index, columns=df.columns)\n\n return normalize(df_rnn)\n \n#\n# train-test split and adjustments\n#\ndef train_test_split(df, train_ratio, forecast_days_ahead, n_time_steps, time_step_interval): \n\n # lenght of the input time window for each sample (the offset of the oldest sample in the input)\n input_window_size = n_time_steps*time_step_interval\n\n split_t = int(len(df)*train_ratio)\n x_train, y_train = [], []\n x_test, y_test = [], []\n y_col_idx = list(df.columns).index('signal')\n for i in range(input_window_size, len(df)):\n t_start = df.index[i - input_window_size]\n t_end = df.index[i]\n \n # we zero out last forecast_days_ahead signal observations, but covariates are assumed to be known\n x_t = df[t_start:t_end:time_step_interval].values.copy()\n if time_step_interval <= forecast_days_ahead:\n x_t[-int((forecast_days_ahead) / time_step_interval):, y_col_idx] = 0\n \n y_t = df.iloc[i]['signal']\n \n if i < split_t:\n x_train.append(x_t)\n y_train.append(y_t)\n else:\n x_test.append(x_t)\n y_test.append(y_t) \n \n return np.stack(x_train), np.hstack(y_train), np.stack(x_test), np.hstack(y_test)\n\n#\n# parameters\n#\nn_time_steps = 40 # lenght of LSTM input in samples\ntime_step_interval = 2 # sampling interval, days\nhidden_units = 8 # LSTM state dimensionality\nforecast_days_ahead = 7\ntrain_ratio = 0.8\n\n#\n# generate data and fit the model\n#\ndf = create_signal()\ndf_rnn = prepare_features_rnn(df)\nx_train, y_train, x_test, y_test = train_test_split(df_rnn, train_ratio, forecast_days_ahead, n_time_steps, time_step_interval)\n\nprint(f'Input tensor shape {x_train.shape}')\n\nn_samples = x_train.shape[0]\nn_features = x_train.shape[2]\n\ninput_model = Input(shape=(n_time_steps, n_features))\nlstm_state_seq, state_h, state_c = LSTM(hidden_units, return_sequences=True, return_state=True)(input_model)\noutput_dense = Dense(1)(state_c)\nmodel_lstm = Model(inputs=input_model, outputs=output_dense)\n\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\nmodel_lstm.compile(loss='mean_squared_error', metrics=['mean_absolute_percentage_error'], optimizer='RMSprop')\nmodel_lstm.summary()\nmodel_lstm.fit(x_train, y_train, epochs=20, batch_size=4, validation_data=(x_test, y_test), use_multiprocessing=True, verbose=1)\nscore = model_lstm.evaluate(x_test, y_test, verbose=0) \nprint('Test MSE:', score[0]) \nprint('Test MAPE:', score[1])", "Input tensor shape (796, 41, 6)\nModel: \"functional_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 40, 6)] 0 \n_________________________________________________________________\nlstm (LSTM) [(None, 40, 8), (None, 8) 480 \n_________________________________________________________________\ndense (Dense) (None, 1) 9 \n=================================================================\nTotal params: 489\nTrainable params: 489\nNon-trainable params: 0\n_________________________________________________________________\nEpoch 1/20\n199/199 [==============================] - 2s 9ms/step - loss: 0.0443 - mean_absolute_percentage_error: 135541.7031 - val_loss: 0.0111 - val_mean_absolute_percentage_error: 22.2035\nEpoch 2/20\n199/199 [==============================] - 1s 7ms/step - loss: 0.0134 - mean_absolute_percentage_error: 90105.8125 - val_loss: 0.0108 - val_mean_absolute_percentage_error: 20.5822\nEpoch 3/20\n199/199 [==============================] - 1s 7ms/step - loss: 0.0063 - mean_absolute_percentage_error: 148959.5625 - val_loss: 0.0040 - val_mean_absolute_percentage_error: 13.3330\nEpoch 4/20\n199/199 [==============================] - 1s 7ms/step - loss: 0.0039 - mean_absolute_percentage_error: 113662.0000 - val_loss: 0.0037 - val_mean_absolute_percentage_error: 10.9933\nEpoch 5/20\n199/199 [==============================] - 1s 7ms/step - loss: 0.0033 - mean_absolute_percentage_error: 101148.6328 - val_loss: 0.0039 - val_mean_absolute_percentage_error: 11.1413\nEpoch 6/20\n199/199 [==============================] - 2s 8ms/step - loss: 0.0031 - mean_absolute_percentage_error: 139972.2188 - val_loss: 0.0021 - val_mean_absolute_percentage_error: 9.0054\nEpoch 7/20\n199/199 [==============================] - 2s 11ms/step - loss: 0.0028 - mean_absolute_percentage_error: 103846.0000 - val_loss: 0.0063 - val_mean_absolute_percentage_error: 13.9849\nEpoch 8/20\n199/199 [==============================] - 2s 8ms/step - loss: 0.0026 - mean_absolute_percentage_error: 90294.8125 - val_loss: 0.0047 - val_mean_absolute_percentage_error: 13.6537\nEpoch 9/20\n199/199 [==============================] - 1s 7ms/step - loss: 0.0024 - mean_absolute_percentage_error: 98722.0781 - val_loss: 0.0042 - val_mean_absolute_percentage_error: 12.7327\nEpoch 10/20\n199/199 [==============================] - 1s 7ms/step - loss: 0.0023 - mean_absolute_percentage_error: 68499.7188 - val_loss: 0.0051 - val_mean_absolute_percentage_error: 13.6249\nEpoch 11/20\n199/199 [==============================] - 2s 8ms/step - loss: 0.0021 - mean_absolute_percentage_error: 84607.8203 - val_loss: 0.0020 - val_mean_absolute_percentage_error: 9.4657\nEpoch 12/20\n199/199 [==============================] - 1s 7ms/step - loss: 0.0022 - mean_absolute_percentage_error: 66879.0312 - val_loss: 0.0035 - val_mean_absolute_percentage_error: 10.3418\nEpoch 13/20\n199/199 [==============================] - 1s 7ms/step - loss: 0.0020 - mean_absolute_percentage_error: 77705.5781 - val_loss: 0.0016 - val_mean_absolute_percentage_error: 8.0591\nEpoch 14/20\n199/199 [==============================] - 1s 7ms/step - loss: 0.0019 - mean_absolute_percentage_error: 55856.9336 - val_loss: 0.0016 - val_mean_absolute_percentage_error: 7.8036\nEpoch 15/20\n199/199 [==============================] - 1s 7ms/step - loss: 0.0019 - mean_absolute_percentage_error: 56749.0938 - val_loss: 0.0026 - val_mean_absolute_percentage_error: 8.9563\nEpoch 16/20\n199/199 [==============================] - 1s 7ms/step - loss: 0.0017 - mean_absolute_percentage_error: 62305.7891 - val_loss: 0.0014 - val_mean_absolute_percentage_error: 7.6600\nEpoch 17/20\n199/199 [==============================] - 1s 7ms/step - loss: 0.0017 - mean_absolute_percentage_error: 71059.7266 - val_loss: 0.0021 - val_mean_absolute_percentage_error: 9.3004\nEpoch 18/20\n199/199 [==============================] - 1s 7ms/step - loss: 0.0016 - mean_absolute_percentage_error: 42330.2109 - val_loss: 0.0030 - val_mean_absolute_percentage_error: 10.4733\nEpoch 19/20\n199/199 [==============================] - 2s 8ms/step - loss: 0.0016 - mean_absolute_percentage_error: 43206.3906 - val_loss: 0.0028 - val_mean_absolute_percentage_error: 10.8260\nEpoch 20/20\n199/199 [==============================] - 2s 8ms/step - loss: 0.0016 - mean_absolute_percentage_error: 5500.9253 - val_loss: 0.0016 - val_mean_absolute_percentage_error: 7.5576\nTest MSE: 0.0016421948093920946\nTest MAPE: 7.557589530944824\n" ] ], [ [ "# Step 3: Visualize the Forecast and Evolution of the Hidden State\n\nWe first plot the forecast to show that models fits well. Next, we visualize how individual components of the hidden state evolve over time:\n* We can see that some states actually extract seasonal and trend components, but this is not guaranteed. \n* We also overlay plots with covariates, to check if there are any correlation between states and covariates. We see that states do not correlate much with the covariate patterns.", "_____no_output_____" ] ], [ [ "input_window_size = n_time_steps*time_step_interval\nx = np.vstack([x_train, x_test])\ny_hat = model_lstm.predict(x)\nforecast = np.append(np.zeros(input_window_size), y_hat) \n\n#\n# plot the forecast\n#\nfig, ax = plt.subplots(1, figsize=(20, 5))\nax.plot(df_rnn.index, forecast, label=f'Forecast ({forecast_days_ahead} days ahead)')\nax.plot(df_rnn.index, df_rnn['signal'], label='Signal')\nax.axvline(x=df.index[int(len(df) * train_ratio)], linestyle='--')\nax.legend()\nplt.show()\n\n#\n# plot the evolution of the LSTM state \n#\nlstm_state_tap = Model(model_lstm.input, lstm_state_seq)\nlstm_state_trace = lstm_state_tap.predict(x)\n\nstate_series = lstm_state_trace[:, -1, :].T\nfig, ax = plt.subplots(len(state_series), figsize=(20, 15))\nfor i, state in enumerate(state_series):\n ax[i].plot(df_rnn.index[:len(state)], state, label=f'State dimension {i}')\n for j in [1, 2]:\n ax[i].plot(df_rnn.index[:len(state)], df_rnn[f'covariate_0{j}'][:len(state)], color='#bbbbbb', label=f'Covariate 0{j}')\n\n ax[i].legend(loc='upper right')\nplt.show()", "_____no_output_____" ] ], [ [ "# Step 4: Define and Fit LSTM with Attention (LSTM-A) Model\n\nWe fit the LSTM with attention model to analyze the contribution of individual time steps from input patches. It can help to reconstruct the (unknown) memory link function. ", "_____no_output_____" ] ], [ [ "#\n# parameters\n#\nn_time_steps = 5 # lenght of LSTM input in samples\ntime_step_interval = 10 # sampling interval, days\nhidden_units = 256 # LSTM state dimensionality\nforecast_days_ahead = 14\ntrain_ratio = 0.8\n\ndef fit_lstm_a(df, train_verbose = 0, score_verbose = 0):\n df_rnn = prepare_features_rnn(df)\n\n x_train, y_train, x_test, y_test = train_test_split(df_rnn, train_ratio, forecast_days_ahead, n_time_steps, time_step_interval)\n\n n_steps = x_train.shape[0]\n n_features = x_train.shape[2]\n\n #\n # define the model: LSTM with attention \n #\n main_input = Input(shape=(n_steps, n_features))\n activations = LSTM(hidden_units, recurrent_dropout=0.1, return_sequences=True)(main_input)\n\n attention = Dense(1, activation='tanh')(activations)\n attention = Flatten()(attention)\n attention = Activation('softmax', name = 'attention_weigths')(attention)\n attention = RepeatVector(hidden_units * 1)(attention)\n attention = Permute([2, 1])(attention)\n\n weighted_activations = Multiply()([activations, attention])\n weighted_activations = Lambda(lambda xin: K.sum(xin, axis=-2), output_shape=(hidden_units,))(weighted_activations)\n\n main_output = Dense(1, activation='sigmoid')(weighted_activations)\n\n model_attn = Model(inputs=main_input, outputs=main_output)\n\n #\n # fit the model\n #\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n model_attn.compile(optimizer='rmsprop', loss='mean_squared_error', metrics=['mean_absolute_percentage_error']) \n history = model_attn.fit(x_train, y_train, batch_size=4, epochs=30, verbose=train_verbose, validation_data=(x_test, y_test)) \n score = model_attn.evaluate(x_test, y_test, verbose=0) \n if score_verbose > 0:\n print(f'Test MSE [{score[0]}], MAPE [{score[1]}]')\n\n return model_attn, df_rnn, x_train, x_test\n\ndf = create_signal(links = [linear_link, linear_link])\nmodel_attn, df_rnn, x_train, x_test = fit_lstm_a(df, train_verbose = 1, score_verbose = 1)", "Epoch 1/30\n207/207 [==============================] - 3s 17ms/step - loss: 0.0531 - mean_absolute_percentage_error: 554625.5625 - val_loss: 0.0354 - val_mean_absolute_percentage_error: 51.5320\nEpoch 2/30\n207/207 [==============================] - 3s 16ms/step - loss: 0.0267 - mean_absolute_percentage_error: 415985.8125 - val_loss: 0.0247 - val_mean_absolute_percentage_error: 45.0028\nEpoch 3/30\n207/207 [==============================] - 3s 15ms/step - loss: 0.0194 - mean_absolute_percentage_error: 315432.1562 - val_loss: 0.0214 - val_mean_absolute_percentage_error: 43.1922\nEpoch 4/30\n207/207 [==============================] - 3s 15ms/step - loss: 0.0156 - mean_absolute_percentage_error: 210736.5000 - val_loss: 0.0192 - val_mean_absolute_percentage_error: 36.7590\nEpoch 5/30\n207/207 [==============================] - 3s 15ms/step - loss: 0.0150 - mean_absolute_percentage_error: 197102.4844 - val_loss: 0.0151 - val_mean_absolute_percentage_error: 30.5381\nEpoch 6/30\n207/207 [==============================] - 3s 14ms/step - loss: 0.0128 - mean_absolute_percentage_error: 230763.5625 - val_loss: 0.0130 - val_mean_absolute_percentage_error: 30.0115\nEpoch 7/30\n207/207 [==============================] - 3s 14ms/step - loss: 0.0115 - mean_absolute_percentage_error: 157021.1562 - val_loss: 0.0283 - val_mean_absolute_percentage_error: 35.5017\nEpoch 8/30\n207/207 [==============================] - 3s 14ms/step - loss: 0.0112 - mean_absolute_percentage_error: 190294.4062 - val_loss: 0.0162 - val_mean_absolute_percentage_error: 36.7094\nEpoch 9/30\n207/207 [==============================] - 3s 14ms/step - loss: 0.0100 - mean_absolute_percentage_error: 139721.3438 - val_loss: 0.0099 - val_mean_absolute_percentage_error: 27.9008\nEpoch 10/30\n207/207 [==============================] - 3s 14ms/step - loss: 0.0088 - mean_absolute_percentage_error: 152096.2031 - val_loss: 0.0187 - val_mean_absolute_percentage_error: 40.2046\nEpoch 11/30\n207/207 [==============================] - 3s 14ms/step - loss: 0.0077 - mean_absolute_percentage_error: 121705.4141 - val_loss: 0.0100 - val_mean_absolute_percentage_error: 27.0696\nEpoch 12/30\n207/207 [==============================] - 3s 16ms/step - loss: 0.0066 - mean_absolute_percentage_error: 170348.6719 - val_loss: 0.0067 - val_mean_absolute_percentage_error: 16.7347\nEpoch 13/30\n207/207 [==============================] - 4s 17ms/step - loss: 0.0054 - mean_absolute_percentage_error: 150606.1250 - val_loss: 0.0062 - val_mean_absolute_percentage_error: 20.2170\nEpoch 14/30\n207/207 [==============================] - 3s 17ms/step - loss: 0.0050 - mean_absolute_percentage_error: 179741.5469 - val_loss: 0.0125 - val_mean_absolute_percentage_error: 30.2266\nEpoch 15/30\n207/207 [==============================] - 3s 17ms/step - loss: 0.0047 - mean_absolute_percentage_error: 135016.8281 - val_loss: 0.0042 - val_mean_absolute_percentage_error: 14.7045\nEpoch 16/30\n207/207 [==============================] - 3s 16ms/step - loss: 0.0046 - mean_absolute_percentage_error: 165125.8438 - val_loss: 0.0038 - val_mean_absolute_percentage_error: 13.8870\nEpoch 17/30\n207/207 [==============================] - 3s 16ms/step - loss: 0.0041 - mean_absolute_percentage_error: 147541.7500 - val_loss: 0.0043 - val_mean_absolute_percentage_error: 15.7311\nEpoch 18/30\n207/207 [==============================] - 4s 17ms/step - loss: 0.0039 - mean_absolute_percentage_error: 102583.0781 - val_loss: 0.0052 - val_mean_absolute_percentage_error: 15.9809\nEpoch 19/30\n207/207 [==============================] - 3s 15ms/step - loss: 0.0040 - mean_absolute_percentage_error: 109036.5156 - val_loss: 0.0086 - val_mean_absolute_percentage_error: 19.8476\nEpoch 20/30\n207/207 [==============================] - 3s 15ms/step - loss: 0.0038 - mean_absolute_percentage_error: 125796.0547 - val_loss: 0.0053 - val_mean_absolute_percentage_error: 15.0676\nEpoch 21/30\n207/207 [==============================] - 3s 15ms/step - loss: 0.0036 - mean_absolute_percentage_error: 93179.3828 - val_loss: 0.0032 - val_mean_absolute_percentage_error: 13.7895\nEpoch 22/30\n207/207 [==============================] - 4s 20ms/step - loss: 0.0036 - mean_absolute_percentage_error: 167399.2188 - val_loss: 0.0029 - val_mean_absolute_percentage_error: 13.8099\nEpoch 23/30\n207/207 [==============================] - 3s 17ms/step - loss: 0.0035 - mean_absolute_percentage_error: 160599.3594 - val_loss: 0.0026 - val_mean_absolute_percentage_error: 13.1479\nEpoch 24/30\n207/207 [==============================] - 3s 17ms/step - loss: 0.0034 - mean_absolute_percentage_error: 144749.8281 - val_loss: 0.0028 - val_mean_absolute_percentage_error: 13.4400\nEpoch 25/30\n207/207 [==============================] - 4s 18ms/step - loss: 0.0034 - mean_absolute_percentage_error: 188223.5781 - val_loss: 0.0039 - val_mean_absolute_percentage_error: 13.9034\nEpoch 26/30\n207/207 [==============================] - 3s 17ms/step - loss: 0.0034 - mean_absolute_percentage_error: 131071.7188 - val_loss: 0.0029 - val_mean_absolute_percentage_error: 13.2374\nEpoch 27/30\n207/207 [==============================] - 3s 16ms/step - loss: 0.0033 - mean_absolute_percentage_error: 121069.7266 - val_loss: 0.0072 - val_mean_absolute_percentage_error: 19.0120\nEpoch 28/30\n207/207 [==============================] - 3s 15ms/step - loss: 0.0032 - mean_absolute_percentage_error: 121252.3906 - val_loss: 0.0032 - val_mean_absolute_percentage_error: 13.2904\nEpoch 29/30\n207/207 [==============================] - 3s 15ms/step - loss: 0.0032 - mean_absolute_percentage_error: 127607.8750 - val_loss: 0.0034 - val_mean_absolute_percentage_error: 13.7815\nEpoch 30/30\n207/207 [==============================] - 3s 15ms/step - loss: 0.0030 - mean_absolute_percentage_error: 144656.9062 - val_loss: 0.0029 - val_mean_absolute_percentage_error: 14.1534\nTest MSE [0.002931196242570877], MAPE [14.153406143188477]\n" ], [ "input_window_size = n_time_steps*time_step_interval\nx = np.vstack([x_train, x_test])\ny_hat = model_attn.predict(x)\nforecast = np.append(np.zeros(input_window_size), y_hat) \n\n#\n# plot the forecast\n#\nfig, ax = plt.subplots(1, figsize=(20, 5))\nax.plot(df_rnn.index, forecast, label=f'Forecast ({forecast_days_ahead} days ahead)')\nax.plot(df_rnn.index, df_rnn['signal'], label='Signal')\nax.axvline(x=df.index[int(len(df) * train_ratio)], linestyle='--')\nax.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "# Step 5: Analyze LSTM-A Model\n\nThe LSTM with attention model allows to extract the matrix of attention weights. For each time step, we have a vector of weights where each weight corresponds to one time step (lag) in the input patch.\n* For the linear link, only the contemporaneous covariates/features have high contribution weights.\n* For the memory link, the \"LSTMogram\" is more blurred becasue lagged samples have high contribution as well.", "_____no_output_____" ] ], [ [ "#\n# evaluate atention weights for each time step\n#\nattention_model = Model(inputs=model_attn.input, outputs=model_attn.get_layer('attention_weigths').output)\na = attention_model.predict(x_train)\nprint(f'Weight matrix shape {a.shape}')\n\nfig, ax = plt.subplots(1, figsize=(10, 2))\nax.imshow(a.T, cmap='viridis', interpolation='nearest', aspect='auto')\nax.grid(None)", "Weight matrix shape (826, 6)\n" ], [ "#\n# generate multiple datasets and perform LSTM-A analysis for each of them\n#\nn_evaluations = 4\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\nfig, ax = plt.subplots(n_evaluations, 2, figsize=(16, n_evaluations * 2))\nfor j, link in enumerate([linear_link, mem_link]):\n for i in range(n_evaluations):\n print(f'Evaluating LSTMogram for link [{link.__name__}], trial [{i}]...')\n df = create_signal(links = [link, link])\n model_attn, df_rnn, x_train, _ = fit_lstm_a(df, score_verbose = 0)\n \n attention_model = Model(inputs=model_attn.input, outputs=model_attn.get_layer('attention_weigths').output)\n a = attention_model.predict(x_train)\n ax[i, j].imshow(a.T, cmap='viridis', interpolation='nearest', aspect='auto')\n ax[i, j].grid(None)", "Evaluating LSTMogram for link [linear_link], trial [0]...\nEvaluating LSTMogram for link [linear_link], trial [1]...\nEvaluating LSTMogram for link [linear_link], trial [2]...\nEvaluating LSTMogram for link [linear_link], trial [3]...\nEvaluating LSTMogram for link [mem_link], trial [0]...\nEvaluating LSTMogram for link [mem_link], trial [1]...\nEvaluating LSTMogram for link [mem_link], trial [2]...\nEvaluating LSTMogram for link [mem_link], trial [3]...\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cb65908fed768ab1802dc0668bfea37835c41148
3,145
ipynb
Jupyter Notebook
research/archive/12.0-Combine-NLP-ECON.ipynb
Chaoste/nlp-stocks
8d90cfde13080d2fb87d7b045a03794400fb15f0
[ "MIT" ]
5
2019-02-15T16:49:30.000Z
2020-08-04T11:56:37.000Z
research/archive/12.0-Combine-NLP-ECON.ipynb
Chaoste/nlp-stocks
8d90cfde13080d2fb87d7b045a03794400fb15f0
[ "MIT" ]
10
2020-01-28T22:33:27.000Z
2022-02-10T00:19:25.000Z
research/archive/12.0-Combine-NLP-ECON.ipynb
Chaoste/nlp-stocks
8d90cfde13080d2fb87d7b045a03794400fb15f0
[ "MIT" ]
2
2019-08-27T19:15:52.000Z
2020-11-30T06:39:18.000Z
26.652542
161
0.578696
[ [ [ "import pyxdameraulevenshtein", "_____no_output_____" ], [ "import sys\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm_notebook as tqdm\nfrom matplotlib import pyplot as plt\nimport itertools\n\nsys.path.append(\"..\") # Adds higher directory to python modules path for importing from src dir\nfrom src.datasets import NyseStocksDataset, NyseSecuritiesDataset\nfrom src.econometric_utils import *\n# from statsmodels.tsa.stattools import grangercausalitytests\n\n%matplotlib inline\n%load_ext autotime\n%load_ext autoreload\n%autoreload 2", "_____no_output_____" ], [ "ds = NyseStocksDataset('OCMvOC-3C', file_path='../data/nyse/prices-split-adjusted.csv', features=['open', 'close', 'movement', 'vix_open', 'vix_close'])\nsecurities = NyseSecuritiesDataset(file_path='../data/nyse/securities.csv')\nds.load()\nsecurities.load()", "_____no_output_____" ], [ "# features = pd.read_csv('cointegration.csv', index_col=0)\ncoints = pd.read_csv('cointegration-10-to-12.csv', index_col=0).stack()\ncoocs = pd.read_csv('cooccurrences.csv', index_col=0).stack().astype(float)", "_____no_output_____" ], [ "features = pd.merge(coocs.reset_index(), coints.reset_index(), on=['level_0', 'level_1'], how='outer').set_index(['level_0', 'level_1']).fillna(0)\nfeatures.columns = ['cooccurrence', 'cointegration']\n# features.cointegration = [int(y <= 0.1) for y in x.cointegration]\n# features.cooccurrence = [int(y >= 1) for y in x.cooccurrence]\n# features.corr()\n# sklearn.metrics.confusion_matrix(x.cointegration, x.cooccurrence)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
cb65aac90a560c51b2b6b61691bcb1393b33384d
7,606
ipynb
Jupyter Notebook
dssg/data-exploration/osm-data.ipynb
sunayana/WRI_WellBeing_Data_Layer
6931e3d585b8b4fde39481f12ad4adb42222908c
[ "MIT" ]
3
2021-10-01T09:27:38.000Z
2022-02-22T22:53:09.000Z
dssg/data-exploration/osm-data.ipynb
sunayana/WRI_WellBeing_Data_Layer
6931e3d585b8b4fde39481f12ad4adb42222908c
[ "MIT" ]
11
2021-04-19T11:56:57.000Z
2021-05-07T14:47:48.000Z
dssg/data-exploration/osm-data.ipynb
sunayana/WRI_WellBeing_Data_Layer
6931e3d585b8b4fde39481f12ad4adb42222908c
[ "MIT" ]
5
2021-04-13T14:45:51.000Z
2021-05-03T14:42:10.000Z
27.261649
400
0.590718
[ [ [ "# OSM Data Exploration\n\n## Extraction of districts from shape files\nFor our experiments we consider two underdeveloped districts Araria, Bihar and Namsai, Arunachal Pradesh, the motivation of this comes from this [dna](https://www.dnaindia.com/india/report-out-of-niti-aayog-s-20-most-underdeveloped-districts-19-are-ruled-by-bjp-or-its-allies-2598984) news article, quoting a Niti Aayog Report. We also consider a developed city Bangalore in the south of India.", "_____no_output_____" ] ], [ [ "import os\nfrom dotenv import load_dotenv\nload_dotenv()\n# Read India shape file with level 2 (contains district level administrative boundaries)\nindia_shape = os.environ.get(\"DATA_DIR\") + \"/gadm36_shp/gadm36_IND_2.shp\"", "_____no_output_____" ], [ "import geopandas as gpd \nindia_gpd = gpd.read_file(india_shape)\n#inspect\nimport matplotlib.pyplot as plt \n%matplotlib inline\nindia_gpd.plot();", "_____no_output_____" ], [ "# Extract Araria district in Bihar state\nararia_gdf = india_gpd[india_gpd['NAME_2'] == 'Araria']\nararia_gdf", "_____no_output_____" ], [ "# Extract two main features of interest\nararia_gdf = araria_gdf[['NAME_2', 'geometry']]\nararia_gdf.plot()", "_____no_output_____" ], [ "# Extract Namsai district in Arunachal Pradesh state. \nnamsai_gdf = india_gpd[india_gpd['NAME_2'] == 'Namsai']\nnamsai_gdf", "_____no_output_____" ], [ "# Extract the two main features\nnamsai_gdf = namsai_gdf[['NAME_2', 'geometry']]\nnamsai_gdf.plot()", "_____no_output_____" ], [ "# Extract Bangalore district \nbangalore_gdf = india_gpd[india_gpd['NAME_2'] == 'Bangalore']\nbangalore_gdf = bangalore_gdf[['NAME_2', 'geometry']]\nbangalore_gdf.plot()", "_____no_output_____" ] ], [ [ "## Creating geographic extracts from OpenStreetMap Data\n\nGiven a geopandas data frame representing a district boundary we find its bounding box", "_____no_output_____" ] ], [ [ "# Get the coordinate system for araria data frame\nararia_gdf.crs", "_____no_output_____" ], [ "araria_bbox = araria_gdf.bounds\nprint(araria_bbox)\ntype(araria_gdf)", "_____no_output_____" ] ], [ [ "## Fetch Open Street Map Data within Boundaries as Data Frame \nWe use 'add_basemap' function of contextily to add a background map to our plot and make sure the added basemap has the same co-ordinate system (crs) as the boundary extracted from the shape file. ", "_____no_output_____" ] ], [ [ "import contextily as ctx \nararia_ax = araria_gdf.plot(figsize=(20, 20), alpha=0.5, edgecolor='k')\nctx.add_basemap(araria_ax, crs=araria_gdf.crs, zoom=12)", "_____no_output_____" ], [ "#Using contextily to download basemaps and store them in standard raster files Store the base maps as tif \nw, s, e, n = (araria_bbox.minx.values[0], araria_bbox.miny.values[0], araria_bbox.maxx.values[0], araria_bbox.maxy.values[0])\n_ = ctx.bounds2raster(w, s, e, n, ll=True, path = os.environ.get(\"OSM_DIR\") + \"araria.tif\", \n source=ctx.providers.CartoDB.Positron)", "_____no_output_____" ], [ "import rasterio\nfrom rasterio.plot import show\nr = rasterio.open(os.environ.get(\"OSM_DIR\") + \"araria.tif\")\nplt.imshow(r.read(1))\n#show(r, 2)\nplt.rcParams[\"figure.figsize\"] = (20, 20)\nplt.rcParams[\"grid.color\"] = 'k'\nplt.rcParams[\"grid.linestyle\"] = \":\"\nplt.rcParams[\"grid.linewidth\"] = 0.5\nplt.rcParams[\"grid.alpha\"] = 0.5\nplt.show()", "_____no_output_____" ] ], [ [ "Other than the raster image tiles of the map there is also the Knots and Edges Model associated with a map, which is the vector data in the geopandas data frame and visualized below", "_____no_output_____" ] ], [ [ "import osmnx as ox\nararia_graph = ox.graph_from_bbox(n, s, e, w)", "_____no_output_____" ], [ "type(araria_graph)", "_____no_output_____" ], [ "araria_fig, araria_ax = ox.plot_graph(araria_graph)\nplt.tight_layout()", "_____no_output_____" ] ], [ [ "The following section deals with creation of GeoDataFrame of OSM entities within a N, S, E, W bounding box and tags which is a dictionary of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. All Open Street Map tags can be found [here](https://wiki.openstreetmap.org/wiki/Map_features)", "_____no_output_____" ] ], [ [ "tags = {'amenity':True, 'building':True, 'emergency':True, 'highway':True, 'footway':True, 'landuse': True, 'water': True}", "_____no_output_____" ], [ "araria_osmdf = ox.geometries.geometries_from_bbox(n, s, e, w, tags=tags)", "_____no_output_____" ], [ "araria_osmdf.head()", "_____no_output_____" ], [ "# Copy the dataframe as a csv\nararia_osmdf.to_csv(os.environ.get(\"OSM_DIR\") + \"araria_osmdf.csv\")", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
cb65b7b96a7ded7e2c136a0c4ce6cc23a8e49e66
13,969
ipynb
Jupyter Notebook
notebooks/trade_demo/archive/21_08_20/Data Owner - Canada.ipynb
Noob-can-Compile/PySyft
156cf93489b16dd0205b0058d4d23d56b3a91ab8
[ "Apache-2.0" ]
8,428
2017-08-10T09:17:49.000Z
2022-03-31T08:20:14.000Z
notebooks/trade_demo/archive/21_08_20/Data Owner - Canada.ipynb
Noob-can-Compile/PySyft
156cf93489b16dd0205b0058d4d23d56b3a91ab8
[ "Apache-2.0" ]
4,779
2017-08-09T23:19:00.000Z
2022-03-29T11:49:36.000Z
notebooks/trade_demo/archive/21_08_20/Data Owner - Canada.ipynb
Noob-can-Compile/PySyft
156cf93489b16dd0205b0058d4d23d56b3a91ab8
[ "Apache-2.0" ]
2,307
2017-08-10T08:52:12.000Z
2022-03-30T05:36:07.000Z
29.721277
215
0.385926
[ [ [ "import pandas as pd\nimport syft as sy", "_____no_output_____" ] ], [ [ "### Loading the dataset", "_____no_output_____" ] ], [ [ "canada_data = pd.read_csv(\"../datasets/ca - feb 2021.csv\")[0:40000]\ncanada_data.head()", "/Users/atrask/opt/anaconda3/envs/syft/lib/python3.7/site-packages/IPython/core/interactiveshell.py:3146: DtypeWarning: Columns (14) have mixed types.Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n" ] ], [ [ "### Logging into the domain", "_____no_output_____" ] ], [ [ "# Let's login into the domain\nca = sy.login(email=\"[email protected]\", password=\"changethis\", port=8081)", "Connecting to http://localhost:8081... done! \t Logging into canada... done!\n" ] ], [ [ "### Upload the dataset to Domain node", "_____no_output_____" ] ], [ [ "# We will upload only the first 40k rows and three columns\n# All these three columns are of `int` type\nsampled_canada_dataset = sy.Tensor(canada_data[[\"Trade Flow Code\", \"Partner Code\", \"Trade Value (US$)\"]].values)\nsampled_canada_dataset.public_shape = sampled_canada_dataset.shape", "_____no_output_____" ], [ "ca.load_dataset(\n assets={\"feb2020-40k\": sampled_canada_dataset},\n name=\"Canada Trade Data - First 40000 rows\",\n description=\"\"\"A collection of reports from Canada's statistics \n bureau about how much it thinks it imports and exports from other countries.\"\"\",\n)", "_____no_output_____" ], [ "ca.datasets", "_____no_output_____" ] ], [ [ "### Create a Data Scientist User", "_____no_output_____" ] ], [ [ "ca.users.create(\n **{\n \"name\": \"Sheldon Cooper\",\n \"email\": \"[email protected]\",\n \"password\": \"bazinga\",\n \"budget\":10\n }\n)", "_____no_output_____" ] ], [ [ "### Accept/Deny Requests to the Domain", "_____no_output_____" ] ], [ [ "ca.requests.pandas", "_____no_output_____" ], [ "ca.requests[-1].accept()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cb65c6568791e70c693ea4a97c50f2a0b75aeed9
10,014
ipynb
Jupyter Notebook
Project_02/My_Notebook/facennScript.ipynb
Escapist-007/ML_Projects
32f6fb58eeac84b786b6a2567ca11a6e0e7f8225
[ "MIT" ]
3
2021-07-03T05:18:20.000Z
2021-10-11T00:05:34.000Z
Project_02/My_Notebook/facennScript.ipynb
Escapist-007/ML_Projects
32f6fb58eeac84b786b6a2567ca11a6e0e7f8225
[ "MIT" ]
null
null
null
Project_02/My_Notebook/facennScript.ipynb
Escapist-007/ML_Projects
32f6fb58eeac84b786b6a2567ca11a6e0e7f8225
[ "MIT" ]
3
2021-02-01T18:44:37.000Z
2021-11-06T03:40:39.000Z
34.891986
126
0.530657
[ [ [ "'''\n Comparing single layer MLP with deep MLP (using TensorFlow)\n'''\n\nimport numpy as np\nfrom scipy.optimize import minimize\nfrom scipy.io import loadmat\nfrom scipy.stats import logistic\nfrom math import sqrt\nimport time\nimport pickle", "_____no_output_____" ], [ "# Do not change this\ndef initializeWeights(n_in,n_out):\n \"\"\"\n # initializeWeights return the random weights for Neural Network given the\n # number of node in the input layer and output layer\n\n # Input:\n # n_in: number of nodes of the input layer\n # n_out: number of nodes of the output layer\n \n # Output: \n # W: matrix of random initial weights with size (n_out x (n_in + 1))\"\"\"\n epsilon = sqrt(6) / sqrt(n_in + n_out + 1);\n W = (np.random.rand(n_out, n_in + 1)*2* epsilon) - epsilon;\n return W", "_____no_output_____" ], [ "def sigmoid(z):\n return (1.0 / (1.0 + np.exp(-z)))", "_____no_output_____" ], [ "def nnObjFunction(params, *args):\n \n n_input, n_hidden, n_class, training_data, training_label, lambdaval = args\n\n w1 = params[0:n_hidden * (n_input + 1)].reshape((n_hidden, (n_input + 1)))\n w2 = params[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1)))\n \n obj_val = 0\n n = training_data.shape[0]\n ''' \n Step 01: Feedforward Propagation \n '''\n \n '''Input Layer --> Hidden Layer\n '''\n # Adding bias node to every training data. Here, the bias value is 1 for every training data\n # A training data is a feature vector X. \n # We have 717 features for every training data\n\n biases1 = np.full((n,1), 1)\n training_data_bias = np.concatenate((biases1, training_data),axis=1)\n \n # aj is the linear combination of input data and weight (w1) at jth hidden node. \n # Here, 1 <= j <= no_of_hidden_units\n aj = np.dot( training_data_bias, np.transpose(w1))\n \n # zj is the output from the hidden unit j after applying sigmoid as an activation function\n zj = sigmoid(aj)\n \n '''Hidden Layer --> Output Layer\n '''\n \n # Adding bias node to every zj. \n \n m = zj.shape[0]\n \n biases2 = np.full((m,1), 1)\n zj_bias = np.concatenate((biases2, zj), axis=1)\n \n # bl is the linear combination of hidden units output and weight(w2) at lth output node. \n # Here, l = 10 as we are classifying 10 digits\n bl = np.dot(zj_bias, np.transpose(w2))\n ol = sigmoid(bl)\n \n ''' \n Step 2: Error Calculation by error function\n '''\n # yl --> Ground truth for every training dataset\n yl = np.full((n, n_class), 0)\n\n for i in range(n):\n trueLabel = training_label[i]\n yl[i][trueLabel] = 1\n \n yl_prime = (1.0-yl)\n ol_prime = (1.0-ol)\n \n lol = np.log(ol)\n lol_prime = np.log(ol_prime)\n \n # Our Error function is \"negative log-likelihood\"\n # We need elementwise multiplication between the matrices\n \n error = np.sum( np.multiply(yl,lol) + np.multiply(yl_prime,lol_prime) )/((-1)*n)\n\n# error = -np.sum( np.sum(yl*lol + yl_prime*lol_prime, 1))/ n\n \n ''' \n Step 03: Gradient Calculation for Backpropagation of error\n '''\n \n delta = ol- yl\n gradient_w2 = np.dot(delta.T, zj_bias)\n \n temp = np.dot(delta,w2) * ( zj_bias * (1.0-zj_bias))\n \n gradient_w1 = np.dot( np.transpose(temp), training_data_bias)\n gradient_w1 = gradient_w1[1:, :]\n \n ''' \n Step 04: Regularization \n '''\n regularization = lambdaval * (np.sum(w1**2) + np.sum(w2**2)) / (2*n)\n obj_val = error + regularization\n \n gradient_w1_reg = (gradient_w1 + lambdaval * w1)/n\n gradient_w2_reg = (gradient_w2 + lambdaval * w2)/n\n\n obj_grad = np.concatenate((gradient_w1_reg.flatten(), gradient_w2_reg.flatten()), 0)\n\n return (obj_val, obj_grad)", "_____no_output_____" ], [ "def nnPredict(w1, w2, training_data):\n\n n = training_data.shape[0]\n\n biases1 = np.full((n,1),1)\n training_data = np.concatenate((biases1, training_data), axis=1)\n\n aj = np.dot(training_data, w1.T)\n zj = sigmoid(aj)\n \n m = zj.shape[0]\n \n biases2 = np.full((m,1), 1)\n zj = np.concatenate((biases2, zj), axis=1)\n\n bl = np.dot(zj, w2.T)\n ol = sigmoid(bl)\n\n labels = np.argmax(ol, axis=1)\n\n return labels", "_____no_output_____" ], [ "\n# Do not change this\ndef preprocess():\n pickle_obj = pickle.load(file=open('face_all.pickle', 'rb'))\n features = pickle_obj['Features']\n labels = pickle_obj['Labels']\n train_x = features[0:21100] / 255\n valid_x = features[21100:23765] / 255\n test_x = features[23765:] / 255\n\n labels = labels[0]\n train_y = labels[0:21100]\n valid_y = labels[21100:23765]\n test_y = labels[23765:]\n return train_x, train_y, valid_x, valid_y, test_x, test_y\n\n\"\"\"**************Neural Network Script Starts here********************************\"\"\"\ntrain_data, train_label, validation_data, validation_label, test_data, test_label = preprocess()\n# Train Neural Network\n\ntrainingStart = time.time()\n# set the number of nodes in input unit (not including bias unit)\nn_input = train_data.shape[1]\n# set the number of nodes in hidden unit (not including bias unit)\nn_hidden = 256\n# set the number of nodes in output unit\nn_class = 2\n\n# initialize the weights into some random matrices\ninitial_w1 = initializeWeights(n_input, n_hidden);\ninitial_w2 = initializeWeights(n_hidden, n_class);\n# unroll 2 weight matrices into single column vector\ninitialWeights = np.concatenate((initial_w1.flatten(), initial_w2.flatten()),0)\n# set the regularization hyper-parameter\nlambdaval = 10;\nargs = (n_input, n_hidden, n_class, train_data, train_label, lambdaval)\n\n#Train Neural Network using fmin_cg or minimize from scipy,optimize module. Check documentation for a working example\nopts = {'maxiter' :50} # Preferred value.\n\nnn_params = minimize(nnObjFunction, initialWeights, jac=True, args=args,method='CG', options=opts)\nparams = nn_params.get('x')\n#Reshape nnParams from 1D vector into w1 and w2 matrices\nw1 = params[0:n_hidden * (n_input + 1)].reshape( (n_hidden, (n_input + 1)))\nw2 = params[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1)))\n\n#Test the computed parameters\npredicted_label = nnPredict(w1,w2,train_data)\n#find the accuracy on Training Dataset\nprint('\\n Training set Accuracy:' + str(100*np.mean((predicted_label == train_label).astype(float))) + '%')\npredicted_label = nnPredict(w1,w2,validation_data)\n#find the accuracy on Validation Dataset\nprint('\\n Validation set Accuracy:' + str(100*np.mean((predicted_label == validation_label).astype(float))) + '%')\npredicted_label = nnPredict(w1,w2,test_data)\n#find the accuracy on Validation Dataset\nprint('\\n Test set Accuracy:' + str(100*np.mean((predicted_label == test_label).astype(float))) + '%')\ntrainingEnd = time.time()\n\nprint('Training Time:',(trainingEnd-trainingStart))", "\n Training set Accuracy:85.77251184834124%\n\n Validation set Accuracy:84.765478424015%\n\n Test set Accuracy:86.26040878122635%\nTraining Time: 48.06817364692688\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
cb65ca8c47e2800220e904d36a324b86a4bef928
38,219
ipynb
Jupyter Notebook
docs/tutorials/basics.ipynb
mganahl/Cirq
f2bf60f31ad247a68589d7c29263a6765fc3f791
[ "Apache-2.0" ]
1
2021-01-05T19:47:55.000Z
2021-01-05T19:47:55.000Z
docs/tutorials/basics.ipynb
mganahl/Cirq
f2bf60f31ad247a68589d7c29263a6765fc3f791
[ "Apache-2.0" ]
4
2021-01-11T10:35:37.000Z
2021-01-28T19:17:02.000Z
docs/tutorials/basics.ipynb
mganahl/Cirq
f2bf60f31ad247a68589d7c29263a6765fc3f791
[ "Apache-2.0" ]
1
2022-01-04T22:00:47.000Z
2022-01-04T22:00:47.000Z
49.894256
12,064
0.683037
[ [ [ "##### Copyright 2020 The Cirq Developers", "_____no_output_____" ] ], [ [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.", "_____no_output_____" ] ], [ [ "# Cirq basics", "_____no_output_____" ], [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://quantumai.google/cirq/tutorials/basics\"><img src=\"https://quantumai.google/site-assets/images/buttons/quantumai_logo_1x.png\" />View on QuantumAI</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorials/basics.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/colab_logo_1x.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/basics.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/github_logo_1x.png\" />View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/basics.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/download_icon_1x.png\" />Download notebook</a>\n </td>\n</table>", "_____no_output_____" ], [ "This tutorial will teach the basics of how to use Cirq. This tutorial will walk through how to use qubits, gates, and operations to create and simulate your first quantum circuit using Cirq. It will briefly introduce devices, unitary matrices, decompositions, and optimizers.\n\nThis tutorial isn’t a quantum computing 101 tutorial, we assume familiarity of quantum computing at about the level of the textbook “Quantum Computation and Quantum Information” by Nielsen and Chuang.\n\nFor more in-depth examples closer to those found in current work, check out our tutorials page.", "_____no_output_____" ], [ "To begin, please follow the instructions for [installing Cirq](../install.md).", "_____no_output_____" ] ], [ [ "try:\n import cirq\nexcept ImportError:\n print(\"installing cirq...\")\n !pip install --quiet cirq\n print(\"installed cirq.\")", "_____no_output_____" ] ], [ [ "## Qubits\n\nThe first part of creating a quantum circuit is to define a set of qubits (also known as a quantum registers) to act on.\n\nCirq has three main ways of defining qubits:\n\n* `cirq.NamedQubit`: used to label qubits by an abstract name\n* `cirq.LineQubit`: qubits labelled by number in a linear array \n* `cirq.GridQubit`: qubits labelled by two numbers in a rectangular lattice.\n\nHere are some examples of defining each type of qubit.", "_____no_output_____" ] ], [ [ "import cirq\n\n# Using named qubits can be useful for abstract algorithms\n# as well as algorithms not yet mapped onto hardware.\nq0 = cirq.NamedQubit('source')\nq1 = cirq.NamedQubit('target')\n\n# Line qubits can be created individually\nq3 = cirq.LineQubit(3)\n\n# Or created in a range\n# This will create LineQubit(0), LineQubit(1), LineQubit(2)\nq0, q1, q2 = cirq.LineQubit.range(3)\n\n# Grid Qubits can also be referenced individually\nq4_5 = cirq.GridQubit(4,5)\n\n# Or created in bulk in a square\n# This will create 16 qubits from (0,0) to (3,3)\nqubits = cirq.GridQubit.square(4)", "_____no_output_____" ] ], [ [ "There are also pre-packaged sets of qubits called [Devices](../devices.md). These are qubits along with a set of rules of how they can be used. A `cirq.Device` can be used to apply adjacency rules and other hardware constraints to a quantum circuit. For our example, we will use the `cirq.google.Foxtail` device that comes with cirq. It is a 2x11 grid that mimics early hardware released by Google.", "_____no_output_____" ] ], [ [ "print(cirq.google.Foxtail)", "(0, 0)───(0, 1)───(0, 2)───(0, 3)───(0, 4)───(0, 5)───(0, 6)───(0, 7)───(0, 8)───(0, 9)───(0, 10)\n│ │ │ │ │ │ │ │ │ │ │\n│ │ │ │ │ │ │ │ │ │ │\n(1, 0)───(1, 1)───(1, 2)───(1, 3)───(1, 4)───(1, 5)───(1, 6)───(1, 7)───(1, 8)───(1, 9)───(1, 10)\n" ] ], [ [ "## Gates and operations\n\nThe next step is to use the qubits to create operations that can be used in our circuit. Cirq has two concepts that are important to understand here:\n\n* A `Gate` is an effect that can be applied to a set of qubits. \n* An `Operation` is a gate applied to a set of qubits.\n\nFor instance, `cirq.H` is the quantum [Hadamard](https://en.wikipedia.org/wiki/Quantum_logic_gate#Hadamard_(H)_gate) and is a `Gate` object. `cirq.H(cirq.LineQubit(1))` is an `Operation` object and is the Hadamard gate applied to a specific qubit (line qubit number 1).\n\nMany textbook gates are included within cirq. `cirq.X`, `cirq.Y`, and `cirq.Z` refer to the single-qubit Pauli gates. `cirq.CZ`, `cirq.CNOT`, `cirq.SWAP` are a few of the common two-qubit gates. `cirq.measure` is a macro to apply a `MeasurementGate` to a set of qubits. You can find more, as well as instructions on how to creats your own custom gates, on the [Gates documentation](../gates.ipynb) page.\n\nMany arithmetic operations can also be applied to gates. Here are some examples:", "_____no_output_____" ] ], [ [ "# Example gates\nnot_gate = cirq.CNOT\npauli_z = cirq.Z\n\n# Using exponentiation to get square root gates\nsqrt_x_gate = cirq.X**0.5\nsqrt_iswap = cirq.ISWAP**0.5\n\n# Some gates can also take parameters\nsqrt_sqrt_y = cirq.YPowGate(exponent=0.25)\n\n# Example operations\nq0, q1 = cirq.LineQubit.range(2)\nz_op = cirq.Z(q0)\nnot_op = cirq.CNOT(q0, q1)\nsqrt_iswap_op = sqrt_iswap(q0, q1)", "_____no_output_____" ] ], [ [ "## Circuits and moments\n\nWe are now ready to construct a quantum circuit. A `Circuit` is a collection of `Moment`s. A `Moment` is a collection of `Operation`s that all act during the same abstract time slice. Each `Operation` must have a disjoint set of qubits from the other `Operation`s in the `Moment`. A `Moment` can be thought of as a vertical slice of a quantum circuit diagram.\n\nCircuits can be constructed in several different ways. By default, cirq will attempt to slide your operation into the earliest possible `Moment` when you insert it.\n", "_____no_output_____" ] ], [ [ "circuit = cirq.Circuit()\n# You can create a circuit by appending to it\ncircuit.append(cirq.H(q) for q in cirq.LineQubit.range(3))\n# All of the gates are put into the same Moment since none overlap\nprint(circuit)", "0: ───H───\n\n1: ───H───\n\n2: ───H───\n" ], [ "# We can also create a circuit directly as well:\nprint(cirq.Circuit(cirq.SWAP(q, q+1) for q in cirq.LineQubit.range(3)))", "0: ───×───────────\n │\n1: ───×───×───────\n │\n2: ───────×───×───\n │\n3: ───────────×───\n" ] ], [ [ "Sometimes, you may not want cirq to automatically shift operations all the way to the left. To construct a circuit without doing this, you can create the circuit moment-by-moment or use a different `InsertStrategy`, explained more in the [Circuit documentation](../circuits.ipynb).", "_____no_output_____" ] ], [ [ "# Creates each gate in a separate moment.\nprint(cirq.Circuit(cirq.Moment([cirq.H(q)]) for q in cirq.LineQubit.range(3)))", "0: ───H───────────\n\n1: ───────H───────\n\n2: ───────────H───\n" ] ], [ [ "### Circuits and devices\n\nOne important consideration when using real quantum devices is that there are often hardware constraints on the circuit. Creating a circuit with a `Device` will allow you to capture some of these requirements. These `Device` objects will validate the operations you add to the circuit to make sure that no illegal operations are added.\n\nLet's look at an example using the Foxtail device.", "_____no_output_____" ] ], [ [ "q0 = cirq.GridQubit(0, 0)\nq1 = cirq.GridQubit(0, 1)\nq2 = cirq.GridQubit(0, 2)\nadjacent_op = cirq.CZ(q0, q1)\nnonadjacent_op = cirq.CZ(q0, q2)\n\n# This is an unconstrained circuit with no device\nfree_circuit = cirq.Circuit()\n# Both operations are allowed:\nfree_circuit.append(adjacent_op)\nfree_circuit.append(nonadjacent_op)\nprint('Unconstrained device:')\nprint(free_circuit)\nprint()\n\n# This is a circuit on the Foxtail device\n# only adjacent operations are allowed.\nprint('Foxtail device:')\nfoxtail_circuit = cirq.Circuit(device=cirq.google.Foxtail)\nfoxtail_circuit.append(adjacent_op)\ntry:\n # Not allowed, will throw exception\n foxtail_circuit.append(nonadjacent_op)\nexcept ValueError as e:\n print('Not allowed. %s' % e)\n", "Unconstrained device:\n(0, 0): ───@───@───\n │ │\n(0, 1): ───@───┼───\n │\n(0, 2): ───────@───\n\nFoxtail device:\nNot allowed. Non-local interaction: cirq.CZ.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 2)).\n" ] ], [ [ "## Simulation\n\nThe results of the application of a quantum circuit can be calculated by a `Simulator`. Cirq comes bundled with a simulator that can calculate the results of circuits up to about a limit of 20 qubits. It can be initialized with `cirq.Simulator()`.\n\nThere are two different approaches to using a simulator:\n\n* `simulate()`: Since we are classically simulating a circuit, a simulator can directly access and view the resulting wave function. This is useful for debugging, learning, and understanding how circuits will function. \n* `run()`: When using actual quantum devices, we can only access the end result of a computation and must sample the results to get a distribution of results. Running the simulator as a sampler mimics this behavior and only returns bit strings as output.\n\nLet's try to simulate a 2-qubit \"Bell State\":", "_____no_output_____" ] ], [ [ "# Create a circuit to generate a Bell State:\n# sqrt(2) * ( |00> + |11> )\nbell_circuit = cirq.Circuit()\nq0, q1 = cirq.LineQubit.range(2)\nbell_circuit.append(cirq.H(q0))\nbell_circuit.append(cirq.CNOT(q0,q1))\n\n# Initialize Simulator\ns=cirq.Simulator()\n\nprint('Simulate the circuit:')\nresults=s.simulate(bell_circuit)\nprint(results)\nprint()\n\n# For sampling, we need to add a measurement at the end\nbell_circuit.append(cirq.measure(q0, q1, key='result'))\n\nprint('Sample the circuit:')\nsamples=s.run(bell_circuit, repetitions=1000)\n# Print a histogram of results\nprint(samples.histogram(key='result'))", "Simulate the circuit:\nmeasurements: (no measurements)\noutput vector: 0.707|00⟩ + 0.707|11⟩\n\nSample the circuit:\nCounter({3: 537, 0: 463})\n" ] ], [ [ "### Using parameter sweeps\n\nCirq circuits allow for gates to have symbols as free parameters within the circuit. This is especially useful for variational algorithms, which vary parameters within the circuit in order to optimize a cost function, but it can be useful in a variety of circumstances.\n\nFor parameters, cirq uses the library `sympy` to add `sympy.Symbol` as parameters to gates and operations. \n\nOnce the circuit is complete, you can fill in the possible values of each of these parameters with a `Sweep`. There are several possibilities that can be used as a sweep:\n\n* `cirq.Points`: A list of manually specified values for one specific symbol as a sequence of floats\n* `cirq.Linspace`: A linear sweep from a starting value to an ending value.\n* `cirq.ListSweep`: A list of manually specified values for several different symbols, specified as a list of dictionaries.\n* `cirq.Zip` and `cirq.Product`: Sweeps can be combined list-wise by zipping them together or through their Cartesian product.\n\nA parameterized circuit and sweep together can be run using the simulator or other sampler by changing `run()` to `run_sweep()` and adding the sweep as a parameter.\n\nHere is an example of sweeping an exponent of a X gate:", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport sympy\n\n# Perform an X gate with variable exponent\nq = cirq.GridQubit(1,1)\ncircuit = cirq.Circuit(cirq.X(q) ** sympy.Symbol('t'),\n cirq.measure(q, key='m'))\n\n# Sweep exponent from zero (off) to one (on) and back to two (off)\nparam_sweep = cirq.Linspace('t', start=0, stop=2, length=200)\n\n# Simulate the sweep\ns = cirq.Simulator()\ntrials = s.run_sweep(circuit, param_sweep, repetitions=1000)\n\n# Plot all the results\nx_data = [trial.params['t'] for trial in trials]\ny_data = [trial.histogram(key='m')[1] / 1000.0 for trial in trials]\nplt.scatter('t','p', data={'t': x_data, 'p': y_data})\n", "_____no_output_____" ] ], [ [ "## Unitary matrices and decompositions\n\nMost quantum operations have a unitary matrix representation. This matrix can be accessed by applying `cirq.unitary()`. This can be applied to gates, operations, and circuits that support this protocol and will return the unitary matrix that represents the object.", "_____no_output_____" ] ], [ [ "print('Unitary of the X gate')\nprint(cirq.unitary(cirq.X))\n\nprint('Unitary of SWAP operator on two qubits.')\nq0, q1 = cirq.LineQubit.range(2)\nprint(cirq.unitary(cirq.SWAP(q0, q1)))\n\nprint('Unitary of a sample circuit')\nprint(cirq.unitary(cirq.Circuit(cirq.X(q0), cirq.SWAP(q0, q1))))", "Unitary of the X gate\n[[0.+0.j 1.+0.j]\n [1.+0.j 0.+0.j]]\nUnitary of SWAP operator on two qubits.\n[[1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n [0.+0.j 0.+0.j 1.+0.j 0.+0.j]\n [0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n [0.+0.j 0.+0.j 0.+0.j 1.+0.j]]\nUnitary of a sample circuit\n[[0.+0.j 0.+0.j 1.+0.j 0.+0.j]\n [1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n [0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n [0.+0.j 1.+0.j 0.+0.j 0.+0.j]]\n" ] ], [ [ "### Decompositions \n\nMany gates can be decomposed into an equivalent circuit with simpler operations and gates. This is called decomposition and can be accomplished with the `cirq.decompose` protocol. \n\nFor instance, a Hadamard H gate can be decomposed into X and Y gates:", "_____no_output_____" ] ], [ [ "print(cirq.decompose(cirq.H(cirq.LineQubit(0))))", "[(cirq.Y**0.5).on(cirq.LineQubit(0)), cirq.XPowGate(exponent=1.0, global_shift=-0.25).on(cirq.LineQubit(0))]\n" ] ], [ [ "Another example is the 3-qubit Toffoli gate, which is equivalent to a controlled-controlled-X gate. Many devices do not support a three qubit gate, so it is important ", "_____no_output_____" ] ], [ [ "q0, q1, q2 = cirq.LineQubit.range(3)\nprint(cirq.Circuit(cirq.decompose(cirq.TOFFOLI(q0, q1, q2))))", "0: ───T────────────────@─────────────────────────────────@─────────────────────────────@────────────────────────────@───────────────────────────────────────\n │ │ │ │\n1: ───T───────Y^-0.5───@───Y^0.5────@───T^-1────Y^-0.5───@────────Y^0.5───@───Y^-0.5───@──────Y^0.5────@───Y^-0.5───@──────Y^0.5────@───────────────────────\n │ │ │ │\n2: ───Y^0.5───X────────T───Y^-0.5───@───Y^0.5───T────────Y^-0.5───────────@───Y^0.5────T^-1───Y^-0.5───@───Y^0.5────T^-1───Y^-0.5───@───Y^0.5───Y^0.5───X───\n" ] ], [ [ "The above decomposes the Toffoli into a simpler set of one-qubit gates and CZ gates at the cost of lengthening the circuit considerably.\n\nSome devices will automatically decompose gates that they do not support. For instance, if we use the `Foxtail` device from above, we can see this in action by adding an unsupported SWAP gate:", "_____no_output_____" ] ], [ [ "swap = cirq.SWAP(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1))\nprint(cirq.Circuit(swap, device=cirq.google.Foxtail))", "(0, 0): ───S^-1───Y^-0.5───@───S^-1───Y^0.5───X^0.5───@───S^-1───X^-0.5───@───S^-1───Z───\n │ │ │\n(0, 1): ───Z──────Y^-0.5───@───S^-1───Y^0.5───X^0.5───@───S^-1───X^-0.5───@───S^-1───S───\n" ] ], [ [ "### Optimizers\n\nThe last concept in this tutorial is the optimizer. An optimizer can take a circuit and modify it. Usually, this will entail combining or modifying operations to make it more efficient and shorter, though an optimizer can, in theory, do any sort of circuit manipulation.\n\nFor example, the `MergeSingleQubitGates` optimizer will take consecutive single-qubit operations and merge them into a single `PhasedXZ` operation.", "_____no_output_____" ] ], [ [ "q=cirq.GridQubit(1, 1)\noptimizer=cirq.MergeSingleQubitGates()\nc=cirq.Circuit(cirq.X(q) ** 0.25, cirq.Y(q) ** 0.25, cirq.Z(q) ** 0.25)\nprint(c)\noptimizer.optimize_circuit(c)\nprint(c)", "(1, 1): ───X^0.25───Y^0.25───T───\n ┌ ┐\n(1, 1): ───│ 0.5 +0.707j -0. -0.5j │───────────\n │ 0.354+0.354j 0.146+0.854j│\n └ ┘\n" ] ], [ [ "Other optimizers can assist in transforming a circuit into operations that are native operations on specific hardware devices. You can find more about optimizers and how to create your own elsewhere in the documentation.", "_____no_output_____" ], [ "## Next steps\n\nAfter completing this tutorial, you should be able to use gates and operations to construct your own quantum circuits, simulate them, and to use sweeps. It should give you a brief idea of the commonly used \n\nThere is much more to learn and try out for those who are interested:\n\n* Learn about the variety of [Gates](../gates.ipynb) available in cirq and more about the different ways to construct [Circuits](../circuits.ipynb)\n* Learn more about [Simulations](../simulation.ipynb) and how it works.\n* Learn about [Noise](../noise.ipynb) and how to utilize multi-level systems using [Qudits](../qudits.ipynb)\n* Dive into some [Examples](_index.yaml) and some in-depth tutorials of how to use cirq.\n\nAlso, join our [cirq-announce mailing list](https://groups.google.com/forum/#!forum/cirq-announce) to hear about changes and releases or go to the [cirq github](https://github.com/quantumlib/Cirq/) to file issues.", "_____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", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cb65db9988d5d97126ecf701ab0a70245aa11a8f
14,359
ipynb
Jupyter Notebook
misc/crawl/test.ipynb
AetherPrior/malaya
45d37b171dff9e92c5d30bd7260b282cd0912a7d
[ "MIT" ]
88
2021-01-06T10:01:31.000Z
2022-03-30T17:34:09.000Z
misc/crawl/test.ipynb
AetherPrior/malaya
45d37b171dff9e92c5d30bd7260b282cd0912a7d
[ "MIT" ]
43
2021-01-14T02:44:41.000Z
2022-03-31T19:47:42.000Z
misc/crawl/test.ipynb
AetherPrior/malaya
45d37b171dff9e92c5d30bd7260b282cd0912a7d
[ "MIT" ]
38
2021-01-06T07:15:03.000Z
2022-03-19T05:07:50.000Z
35.80798
158
0.561878
[ [ [ "from fake_useragent import UserAgent\nimport requests\n\nua = UserAgent()", "Error occurred during loading data. Trying to use cache server https://fake-useragent.herokuapp.com/browsers/0.1.11\nTraceback (most recent call last):\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py\", line 1317, in do_open\n encode_chunked=req.has_header('Transfer-encoding'))\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py\", line 1252, in request\n self._send_request(method, url, body, headers, encode_chunked)\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py\", line 1298, in _send_request\n self.endheaders(body, encode_chunked=encode_chunked)\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py\", line 1247, in endheaders\n self._send_output(message_body, encode_chunked=encode_chunked)\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py\", line 1026, in _send_output\n self.send(msg)\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py\", line 966, in send\n self.connect()\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py\", line 938, in connect\n (self.host,self.port), self.timeout, self.source_address)\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py\", line 727, in create_connection\n raise err\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py\", line 716, in create_connection\n sock.connect(sa)\nsocket.timeout: timed out\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.7/site-packages/fake_useragent/utils.py\", line 67, in get\n context=context,\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py\", line 222, in urlopen\n return opener.open(url, data, timeout)\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py\", line 525, in open\n response = self._open(req, data)\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py\", line 543, in _open\n '_open', req)\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py\", line 503, in _call_chain\n result = func(*args)\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py\", line 1345, in http_open\n return self.do_open(http.client.HTTPConnection, req)\n File \"/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py\", line 1319, in do_open\n raise URLError(err)\nurllib.error.URLError: <urlopen error timed out>\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.7/site-packages/fake_useragent/utils.py\", line 166, in load\n verify_ssl=verify_ssl,\n File \"/usr/local/lib/python3.7/site-packages/fake_useragent/utils.py\", line 122, in get_browser_versions\n verify_ssl=verify_ssl,\n File \"/usr/local/lib/python3.7/site-packages/fake_useragent/utils.py\", line 84, in get\n raise FakeUserAgentError('Maximum amount of retries reached')\nfake_useragent.errors.FakeUserAgentError: Maximum amount of retries reached\n" ], [ "from newspaper import Article\nfrom queue import Queue\nfrom urllib.parse import quote\nfrom unidecode import unidecode\n\ndef get_date(load):\n try:\n date = re.findall(\n '[-+]?[.]?[\\d]+(?:,\\d\\d\\d)*[\\.]?\\d*(?:[eE][-+]?\\d+)?', load\n )\n return '%s-%s-%s' % (date[2], date[0], date[1])\n except Exce:\n return False\n\n\ndef run_parallel_in_threads(target, args_list):\n globalparas = []\n result = Queue()\n\n def task_wrapper(*args):\n result.put(target(*args))\n\n threads = [\n threading.Thread(target = task_wrapper, args = args)\n for args in args_list\n ]\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n while not result.empty():\n globalparas.append(result.get())\n globalparas = list(filter(None, globalparas))\n return globalparas\n\n\ndef get_article(link, news, date):\n article = Article(link)\n article.download()\n article.parse()\n article.nlp()\n lang = 'ENGLISH'\n if len(article.title) < 5 or len(article.text) < 5:\n lang = 'INDONESIA'\n print('found BM/ID article')\n article = Article(link, language = 'id')\n article.download()\n article.parse()\n article.nlp()\n return {\n 'title': article.title,\n 'url': link,\n 'authors': article.authors,\n 'top-image': article.top_image,\n 'text': article.text,\n 'keyword': article.keywords,\n 'summary': article.summary,\n 'news': news,\n 'date': date,\n 'language': lang,\n }", "_____no_output_____" ], [ "NUMBER_OF_CALLS_TO_GOOGLE_NEWS_ENDPOINT = 0\n\nGOOGLE_NEWS_URL = 'https://www.google.com.my/search?q={}&source=lnt&tbs=cdr%3A1%2Ccd_min%3A{}%2Ccd_max%3A{}&tbm=nws&start={}'\n\ndef forge_url(q, start, year_start, year_end):\n global NUMBER_OF_CALLS_TO_GOOGLE_NEWS_ENDPOINT\n NUMBER_OF_CALLS_TO_GOOGLE_NEWS_ENDPOINT += 1\n return GOOGLE_NEWS_URL.format(\n q.replace(' ', '+'), str(year_start), str(year_end), start\n )", "_____no_output_____" ], [ "num_articles_index = 0\nurl = forge_url('america', num_articles_index, '2005', '2021')\nurl", "_____no_output_____" ], [ "headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}\nheaders", "_____no_output_____" ], [ "response = requests.get(url, headers = headers, timeout = 60)", "_____no_output_____" ], [ "soup = BeautifulSoup(response.content, 'html.parser')\nstyle=\"text-decoration:none;display:block\"", "_____no_output_____" ], [ "soup.find_all('div', {'class': 'XTjFC WF4CUc'})[0]", "_____no_output_____" ], [ "[dateparser.parse(v.text) for v in soup.find_all('span', {'class': 'WG9SHc'})]", "_____no_output_____" ], [ "import dateparser\n\nstr(dateparser.parse('2 weeks ago'))", "_____no_output_____" ], [ "from bs4 import BeautifulSoup\nfrom datetime import datetime, timedelta\nfrom dateutil import parser\nimport dateparser\n\ndef extract_links(content):\n soup = BeautifulSoup(content, 'html.parser')\n # return soup\n today = datetime.now().strftime('%m/%d/%Y')\n links_list = [v.attrs['href'] for v in soup.find_all('a', {'style': 'text-decoration:none;display:block'})]\n dates_list = [v.text for v in soup.find_all('span', {'class': 'WG9SHc'})]\n sources_list = [v.text for v in soup.find_all('div', {'class': 'XTjFC WF4CUc'})]\n output = []\n for (link, date, source) in zip(links_list, dates_list, sources_list):\n try:\n date = str(dateparser.parse(date))\n except:\n pass\n output.append((link, date, source))\n return output", "_____no_output_____" ], [ "r = extract_links(response.content)\nr", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb65f569c7f0a666f36e51c201569b29c8bfc951
66,697
ipynb
Jupyter Notebook
Deep Learning/1. Neural Networks and Deep Learning/Exercise/Week4/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
arti1117/coursera
bd9140bc811fbc200a78f2172a57141e0f46849a
[ "MIT" ]
null
null
null
Deep Learning/1. Neural Networks and Deep Learning/Exercise/Week4/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
arti1117/coursera
bd9140bc811fbc200a78f2172a57141e0f46849a
[ "MIT" ]
null
null
null
Deep Learning/1. Neural Networks and Deep Learning/Exercise/Week4/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
arti1117/coursera
bd9140bc811fbc200a78f2172a57141e0f46849a
[ "MIT" ]
1
2021-12-08T00:22:19.000Z
2021-12-08T00:22:19.000Z
36.586396
490
0.529769
[ [ [ "# Building your Deep Neural Network: Step by Step\n\nWelcome to your week 4 assignment (part 1 of 2)! Previously you trained a 2-layer Neural Network with a single hidden layer. This week, you will build a deep neural network with as many layers as you want!\n\n- In this notebook, you'll implement all the functions required to build a deep neural network.\n- For the next assignment, you'll use these functions to build a deep neural network for image classification.\n\n**By the end of this assignment, you'll be able to:**\n\n- Use non-linear units like ReLU to improve your model\n- Build a deeper neural network (with more than 1 hidden layer)\n- Implement an easy-to-use neural network class\n\n**Notation**:\n- Superscript $[l]$ denotes a quantity associated with the $l^{th}$ layer. \n - Example: $a^{[L]}$ is the $L^{th}$ layer activation. $W^{[L]}$ and $b^{[L]}$ are the $L^{th}$ layer parameters.\n- Superscript $(i)$ denotes a quantity associated with the $i^{th}$ example. \n - Example: $x^{(i)}$ is the $i^{th}$ training example.\n- Lowerscript $i$ denotes the $i^{th}$ entry of a vector.\n - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the $l^{th}$ layer's activations).\n\nLet's get started!", "_____no_output_____" ], [ "## Table of Contents\n- [1 - Packages](#1)\n- [2 - Outline](#2)\n- [3 - Initialization](#3)\n - [3.1 - 2-layer Neural Network](#3-1)\n - [Exercise 1 - initialize_parameters](#ex-1)\n - [3.2 - L-layer Neural Network](#3-2)\n - [Exercise 2 - initialize_parameters_deep](#ex-2)\n- [4 - Forward Propagation Module](#4)\n - [4.1 - Linear Forward](#4-1)\n - [Exercise 3 - linear_forward](#ex-3)\n - [4.2 - Linear-Activation Forward](#4-2)\n - [Exercise 4 - linear_activation_forward](#ex-4)\n - [4.3 - L-Layer Model](#4-3)\n - [Exercise 5 - L_model_forward](#ex-5)\n- [5 - Cost Function](#5)\n - [Exercise 6 - compute_cost](#ex-6)\n- [6 - Backward Propagation Module](#6)\n - [6.1 - Linear Backward](#6-1)\n - [Exercise 7 - linear_backward](#ex-7)\n - [6.2 - Linear-Activation Backward](#6-2)\n - [Exercise 8 - linear_activation_backward](#ex-8)\n - [6.3 - L-Model Backward](#6-3)\n - [Exercise 9 - L_model_backward](#ex-9)\n - [6.4 - Update Parameters](#6-4)\n - [Exercise 10 - update_parameters](#ex-10)", "_____no_output_____" ], [ "<a name='1'></a>\n## 1 - Packages\n\nFirst, import all the packages you'll need during this assignment. \n\n- [numpy](www.numpy.org) is the main package for scientific computing with Python.\n- [matplotlib](http://matplotlib.org) is a library to plot graphs in Python.\n- dnn_utils provides some necessary functions for this notebook.\n- testCases provides some test cases to assess the correctness of your functions\n- np.random.seed(1) is used to keep all the random function calls consistent. It helps grade your work. Please don't change the seed! ", "_____no_output_____" ] ], [ [ "import numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nfrom testCases import *\nfrom dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward\nfrom public_tests import *\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n%load_ext autoreload\n%autoreload 2\n\nnp.random.seed(1)", "_____no_output_____" ] ], [ [ "<a name='2'></a>\n## 2 - Outline\n\nTo build your neural network, you'll be implementing several \"helper functions.\" These helper functions will be used in the next assignment to build a two-layer neural network and an L-layer neural network. \n\nEach small helper function will have detailed instructions to walk you through the necessary steps. Here's an outline of the steps in this assignment:\n\n- Initialize the parameters for a two-layer network and for an $L$-layer neural network\n- Implement the forward propagation module (shown in purple in the figure below)\n - Complete the LINEAR part of a layer's forward propagation step (resulting in $Z^{[l]}$).\n - The ACTIVATION function is provided for you (relu/sigmoid)\n - Combine the previous two steps into a new [LINEAR->ACTIVATION] forward function.\n - Stack the [LINEAR->RELU] forward function L-1 time (for layers 1 through L-1) and add a [LINEAR->SIGMOID] at the end (for the final layer $L$). This gives you a new L_model_forward function.\n- Compute the loss\n- Implement the backward propagation module (denoted in red in the figure below)\n - Complete the LINEAR part of a layer's backward propagation step\n - The gradient of the ACTIVATE function is provided for you(relu_backward/sigmoid_backward) \n - Combine the previous two steps into a new [LINEAR->ACTIVATION] backward function\n - Stack [LINEAR->RELU] backward L-1 times and add [LINEAR->SIGMOID] backward in a new L_model_backward function\n- Finally, update the parameters\n\n<img src=\"images/final outline.png\" style=\"width:800px;height:500px;\">\n<caption><center><b>Figure 1</b></center></caption><br>\n\n\n**Note**:\n\nFor every forward function, there is a corresponding backward function. This is why at every step of your forward module you will be storing some values in a cache. These cached values are useful for computing gradients. \n\nIn the backpropagation module, you can then use the cache to calculate the gradients. Don't worry, this assignment will show you exactly how to carry out each of these steps! ", "_____no_output_____" ], [ "<a name='3'></a>\n## 3 - Initialization\n\nYou will write two helper functions to initialize the parameters for your model. The first function will be used to initialize parameters for a two layer model. The second one generalizes this initialization process to $L$ layers.\n\n<a name='3-1'></a>\n### 3.1 - 2-layer Neural Network\n\n<a name='ex-1'></a>\n### Exercise 1 - initialize_parameters\n\nCreate and initialize the parameters of the 2-layer neural network.\n\n**Instructions**:\n\n- The model's structure is: *LINEAR -> RELU -> LINEAR -> SIGMOID*. \n- Use this random initialization for the weight matrices: `np.random.randn(shape)*0.01` with the correct shape\n- Use zero initialization for the biases: `np.zeros(shape)`", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: initialize_parameters\n\ndef initialize_parameters(n_x, n_h, n_y):\n \"\"\"\n Argument:\n n_x -- size of the input layer\n n_h -- size of the hidden layer\n n_y -- size of the output layer\n \n Returns:\n parameters -- python dictionary containing your parameters:\n W1 -- weight matrix of shape (n_h, n_x)\n b1 -- bias vector of shape (n_h, 1)\n W2 -- weight matrix of shape (n_y, n_h)\n b2 -- bias vector of shape (n_y, 1)\n \"\"\"\n \n np.random.seed(1)\n \n #(≈ 4 lines of code)\n # W1 = ...\n # b1 = ...\n # W2 = ...\n # b2 = ...\n # YOUR CODE STARTS HERE\n W1 = np.random.randn(n_h, n_x) * 0.01\n b1 = np.zeros((n_h, 1))\n W2 = np.random.randn(n_y, n_h) * 0.01\n b2 = np.zeros((n_y, 1))\n # YOUR CODE ENDS HERE\n \n parameters = {\"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2}\n \n return parameters ", "_____no_output_____" ], [ "parameters = initialize_parameters(3,2,1)\n\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))\n\ninitialize_parameters_test(initialize_parameters)", "W1 = [[ 0.01624345 -0.00611756 -0.00528172]\n [-0.01072969 0.00865408 -0.02301539]]\nb1 = [[0.]\n [0.]]\nW2 = [[ 0.01744812 -0.00761207]]\nb2 = [[0.]]\n\u001b[92m All tests passed.\n" ] ], [ [ "***Expected output***\n```\nW1 = [[ 0.01624345 -0.00611756 -0.00528172]\n [-0.01072969 0.00865408 -0.02301539]]\nb1 = [[0.]\n [0.]]\nW2 = [[ 0.01744812 -0.00761207]]\nb2 = [[0.]]\n```", "_____no_output_____" ], [ "<a name='3-2'></a>\n### 3.2 - L-layer Neural Network\n\nThe initialization for a deeper L-layer neural network is more complicated because there are many more weight matrices and bias vectors. When completing the `initialize_parameters_deep` function, you should make sure that your dimensions match between each layer. Recall that $n^{[l]}$ is the number of units in layer $l$. For example, if the size of your input $X$ is $(12288, 209)$ (with $m=209$ examples) then:\n\n<table style=\"width:100%\">\n <tr>\n <td> </td> \n <td> <b>Shape of W</b> </td> \n <td> <b>Shape of b</b> </td> \n <td> <b>Activation</b> </td>\n <td> <b>Shape of Activation</b> </td> \n <tr>\n <tr>\n <td> <b>Layer 1</b> </td> \n <td> $(n^{[1]},12288)$ </td> \n <td> $(n^{[1]},1)$ </td> \n <td> $Z^{[1]} = W^{[1]} X + b^{[1]} $ </td> \n <td> $(n^{[1]},209)$ </td> \n <tr>\n <tr>\n <td> <b>Layer 2</b> </td> \n <td> $(n^{[2]}, n^{[1]})$ </td> \n <td> $(n^{[2]},1)$ </td> \n <td>$Z^{[2]} = W^{[2]} A^{[1]} + b^{[2]}$ </td> \n <td> $(n^{[2]}, 209)$ </td> \n <tr>\n <tr>\n <td> $\\vdots$ </td> \n <td> $\\vdots$ </td> \n <td> $\\vdots$ </td> \n <td> $\\vdots$</td> \n <td> $\\vdots$ </td> \n <tr> \n <tr>\n <td> <b>Layer L-1</b> </td> \n <td> $(n^{[L-1]}, n^{[L-2]})$ </td> \n <td> $(n^{[L-1]}, 1)$ </td> \n <td>$Z^{[L-1]} = W^{[L-1]} A^{[L-2]} + b^{[L-1]}$ </td> \n <td> $(n^{[L-1]}, 209)$ </td> \n <tr>\n <tr>\n <td> <b>Layer L</b> </td> \n <td> $(n^{[L]}, n^{[L-1]})$ </td> \n <td> $(n^{[L]}, 1)$ </td>\n <td> $Z^{[L]} = W^{[L]} A^{[L-1]} + b^{[L]}$</td>\n <td> $(n^{[L]}, 209)$ </td> \n <tr>\n</table>\n\nRemember that when you compute $W X + b$ in python, it carries out broadcasting. For example, if: \n\n$$ W = \\begin{bmatrix}\n w_{00} & w_{01} & w_{02} \\\\\n w_{10} & w_{11} & w_{12} \\\\\n w_{20} & w_{21} & w_{22} \n\\end{bmatrix}\\;\\;\\; X = \\begin{bmatrix}\n x_{00} & x_{01} & x_{02} \\\\\n x_{10} & x_{11} & x_{12} \\\\\n x_{20} & x_{21} & x_{22} \n\\end{bmatrix} \\;\\;\\; b =\\begin{bmatrix}\n b_0 \\\\\n b_1 \\\\\n b_2\n\\end{bmatrix}\\tag{2}$$\n\nThen $WX + b$ will be:\n\n$$ WX + b = \\begin{bmatrix}\n (w_{00}x_{00} + w_{01}x_{10} + w_{02}x_{20}) + b_0 & (w_{00}x_{01} + w_{01}x_{11} + w_{02}x_{21}) + b_0 & \\cdots \\\\\n (w_{10}x_{00} + w_{11}x_{10} + w_{12}x_{20}) + b_1 & (w_{10}x_{01} + w_{11}x_{11} + w_{12}x_{21}) + b_1 & \\cdots \\\\\n (w_{20}x_{00} + w_{21}x_{10} + w_{22}x_{20}) + b_2 & (w_{20}x_{01} + w_{21}x_{11} + w_{22}x_{21}) + b_2 & \\cdots\n\\end{bmatrix}\\tag{3} $$\n", "_____no_output_____" ], [ "<a name='ex-2'></a>\n### Exercise 2 - initialize_parameters_deep\n\nImplement initialization for an L-layer Neural Network. \n\n**Instructions**:\n- The model's structure is *[LINEAR -> RELU] $ \\times$ (L-1) -> LINEAR -> SIGMOID*. I.e., it has $L-1$ layers using a ReLU activation function followed by an output layer with a sigmoid activation function.\n- Use random initialization for the weight matrices. Use `np.random.randn(shape) * 0.01`.\n- Use zeros initialization for the biases. Use `np.zeros(shape)`.\n- You'll store $n^{[l]}$, the number of units in different layers, in a variable `layer_dims`. For example, the `layer_dims` for last week's Planar Data classification model would have been [2,4,1]: There were two inputs, one hidden layer with 4 hidden units, and an output layer with 1 output unit. This means `W1`'s shape was (4,2), `b1` was (4,1), `W2` was (1,4) and `b2` was (1,1). Now you will generalize this to $L$ layers! \n- Here is the implementation for $L=1$ (one layer neural network). It should inspire you to implement the general case (L-layer neural network).\n```python\n if L == 1:\n parameters[\"W\" + str(L)] = np.random.randn(layer_dims[1], layer_dims[0]) * 0.01\n parameters[\"b\" + str(L)] = np.zeros((layer_dims[1], 1))\n```", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: initialize_parameters_deep\n\ndef initialize_parameters_deep(layer_dims):\n \"\"\"\n Arguments:\n layer_dims -- python array (list) containing the dimensions of each layer in our network\n \n Returns:\n parameters -- python dictionary containing your parameters \"W1\", \"b1\", ..., \"WL\", \"bL\":\n Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1])\n bl -- bias vector of shape (layer_dims[l], 1)\n \"\"\"\n \n np.random.seed(3)\n parameters = {}\n L = len(layer_dims) # number of layers in the network\n\n for l in range(1, L):\n #(≈ 2 lines of code)\n # parameters['W' + str(l)] = ...\n # parameters['b' + str(l)] = ...\n # YOUR CODE STARTS HERE\n parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) * 0.01\n parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))\n # YOUR CODE ENDS HERE\n \n assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l - 1]))\n assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))\n\n \n return parameters", "_____no_output_____" ], [ "parameters = initialize_parameters_deep([5,4,3])\n\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))\n\ninitialize_parameters_deep_test(initialize_parameters_deep)", "W1 = [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388]\n [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218]\n [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034]\n [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]]\nb1 = [[0.]\n [0.]\n [0.]\n [0.]]\nW2 = [[-0.01185047 -0.0020565 0.01486148 0.00236716]\n [-0.01023785 -0.00712993 0.00625245 -0.00160513]\n [-0.00768836 -0.00230031 0.00745056 0.01976111]]\nb2 = [[0.]\n [0.]\n [0.]]\n\u001b[92m All tests passed.\n" ] ], [ [ "***Expected output***\n```\nW1 = [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388]\n [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218]\n [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034]\n [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]]\nb1 = [[0.]\n [0.]\n [0.]\n [0.]]\nW2 = [[-0.01185047 -0.0020565 0.01486148 0.00236716]\n [-0.01023785 -0.00712993 0.00625245 -0.00160513]\n [-0.00768836 -0.00230031 0.00745056 0.01976111]]\nb2 = [[0.]\n [0.]\n [0.]]\n```", "_____no_output_____" ], [ "<a name='4'></a>\n## 4 - Forward Propagation Module\n\n<a name='4-1'></a>\n### 4.1 - Linear Forward \n\nNow that you have initialized your parameters, you can do the forward propagation module. Start by implementing some basic functions that you can use again later when implementing the model. Now, you'll complete three functions in this order:\n\n- LINEAR\n- LINEAR -> ACTIVATION where ACTIVATION will be either ReLU or Sigmoid. \n- [LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID (whole model)\n\nThe linear forward module (vectorized over all the examples) computes the following equations:\n\n$$Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}\\tag{4}$$\n\nwhere $A^{[0]} = X$. \n\n<a name='ex-3'></a>\n### Exercise 3 - linear_forward \n\nBuild the linear part of forward propagation.\n\n**Reminder**:\nThe mathematical representation of this unit is $Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}$. You may also find `np.dot()` useful. If your dimensions don't match, printing `W.shape` may help.", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: linear_forward\n\ndef linear_forward(A, W, b):\n \"\"\"\n Implement the linear part of a layer's forward propagation.\n\n Arguments:\n A -- activations from previous layer (or input data): (size of previous layer, number of examples)\n W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)\n b -- bias vector, numpy array of shape (size of the current layer, 1)\n\n Returns:\n Z -- the input of the activation function, also called pre-activation parameter \n cache -- a python tuple containing \"A\", \"W\" and \"b\" ; stored for computing the backward pass efficiently\n \"\"\"\n \n #(≈ 1 line of code)\n # Z = ...\n # YOUR CODE STARTS HERE\n Z = np.dot(W, A) + b \n # YOUR CODE ENDS HERE\n cache = (A, W, b)\n \n return Z, cache", "_____no_output_____" ], [ "t_A, t_W, t_b = linear_forward_test_case()\nt_Z, t_linear_cache = linear_forward(t_A, t_W, t_b)\nprint(\"Z = \" + str(t_Z))\n\nlinear_forward_test(linear_forward)", "Z = [[ 3.26295337 -1.23429987]]\n\u001b[92m All tests passed.\n" ] ], [ [ "***Expected output***\n```\nZ = [[ 3.26295337 -1.23429987]]\n```", "_____no_output_____" ], [ "<a name='4-2'></a>\n### 4.2 - Linear-Activation Forward\n\nIn this notebook, you will use two activation functions:\n\n- **Sigmoid**: $\\sigma(Z) = \\sigma(W A + b) = \\frac{1}{ 1 + e^{-(W A + b)}}$. You've been provided with the `sigmoid` function which returns **two** items: the activation value \"`a`\" and a \"`cache`\" that contains \"`Z`\" (it's what we will feed in to the corresponding backward function). To use it you could just call: \n``` python\nA, activation_cache = sigmoid(Z)\n```\n\n- **ReLU**: The mathematical formula for ReLu is $A = RELU(Z) = max(0, Z)$. You've been provided with the `relu` function. This function returns **two** items: the activation value \"`A`\" and a \"`cache`\" that contains \"`Z`\" (it's what you'll feed in to the corresponding backward function). To use it you could just call:\n``` python\nA, activation_cache = relu(Z)\n```", "_____no_output_____" ], [ "For added convenience, you're going to group two functions (Linear and Activation) into one function (LINEAR->ACTIVATION). Hence, you'll implement a function that does the LINEAR forward step, followed by an ACTIVATION forward step.\n\n<a name='ex-4'></a>\n### Exercise 4 - linear_activation_forward\n\nImplement the forward propagation of the *LINEAR->ACTIVATION* layer. Mathematical relation is: $A^{[l]} = g(Z^{[l]}) = g(W^{[l]}A^{[l-1]} +b^{[l]})$ where the activation \"g\" can be sigmoid() or relu(). Use `linear_forward()` and the correct activation function.", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: linear_activation_forward\n\ndef linear_activation_forward(A_prev, W, b, activation):\n \"\"\"\n Implement the forward propagation for the LINEAR->ACTIVATION layer\n\n Arguments:\n A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)\n W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)\n b -- bias vector, numpy array of shape (size of the current layer, 1)\n activation -- the activation to be used in this layer, stored as a text string: \"sigmoid\" or \"relu\"\n\n Returns:\n A -- the output of the activation function, also called the post-activation value \n cache -- a python tuple containing \"linear_cache\" and \"activation_cache\";\n stored for computing the backward pass efficiently\n \"\"\"\n \n if activation == \"sigmoid\":\n #(≈ 2 lines of code)\n # Z, linear_cache = ...\n # A, activation_cache = ...\n # YOUR CODE STARTS HERE\n Z, linear_cache = linear_forward(A_prev, W, b)\n A, activation_cache = sigmoid(Z)\n # YOUR CODE ENDS HERE\n \n elif activation == \"relu\":\n #(≈ 2 lines of code)\n # Z, linear_cache = ...\n # A, activation_cache = ...\n # YOUR CODE STARTS HERE\n Z, linear_cache = linear_forward(A_prev, W, b)\n A, activation_cache = relu(Z)\n # YOUR CODE ENDS HERE\n cache = (linear_cache, activation_cache)\n\n return A, cache", "_____no_output_____" ], [ "t_A_prev, t_W, t_b = linear_activation_forward_test_case()\n\nt_A, t_linear_activation_cache = linear_activation_forward(t_A_prev, t_W, t_b, activation = \"sigmoid\")\nprint(\"With sigmoid: A = \" + str(t_A))\n\nt_A, t_linear_activation_cache = linear_activation_forward(t_A_prev, t_W, t_b, activation = \"relu\")\nprint(\"With ReLU: A = \" + str(t_A))\n\nlinear_activation_forward_test(linear_activation_forward)", "With sigmoid: A = [[0.96890023 0.11013289]]\nWith ReLU: A = [[3.43896131 0. ]]\n\u001b[92m All tests passed.\n" ] ], [ [ "***Expected output***\n```\nWith sigmoid: A = [[0.96890023 0.11013289]]\nWith ReLU: A = [[3.43896131 0. ]]\n```", "_____no_output_____" ], [ "**Note**: In deep learning, the \"[LINEAR->ACTIVATION]\" computation is counted as a single layer in the neural network, not two layers. ", "_____no_output_____" ], [ "<a name='4-3'></a>\n### 4.3 - L-Layer Model \n\nFor even *more* convenience when implementing the $L$-layer Neural Net, you will need a function that replicates the previous one (`linear_activation_forward` with RELU) $L-1$ times, then follows that with one `linear_activation_forward` with SIGMOID.\n\n<img src=\"images/model_architecture_kiank.png\" style=\"width:600px;height:300px;\">\n<caption><center> <b>Figure 2</b> : *[LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID* model</center></caption><br>\n\n<a name='ex-5'></a>\n### Exercise 5 - L_model_forward\n\nImplement the forward propagation of the above model.\n\n**Instructions**: In the code below, the variable `AL` will denote $A^{[L]} = \\sigma(Z^{[L]}) = \\sigma(W^{[L]} A^{[L-1]} + b^{[L]})$. (This is sometimes also called `Yhat`, i.e., this is $\\hat{Y}$.) \n\n**Hints**:\n- Use the functions you've previously written \n- Use a for loop to replicate [LINEAR->RELU] (L-1) times\n- Don't forget to keep track of the caches in the \"caches\" list. To add a new value `c` to a `list`, you can use `list.append(c)`.", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: L_model_forward\n\ndef L_model_forward(X, parameters):\n \"\"\"\n Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation\n \n Arguments:\n X -- data, numpy array of shape (input size, number of examples)\n parameters -- output of initialize_parameters_deep()\n \n Returns:\n AL -- activation value from the output (last) layer\n caches -- list of caches containing:\n every cache of linear_activation_forward() (there are L of them, indexed from 0 to L-1)\n \"\"\"\n\n caches = []\n A = X\n L = len(parameters) // 2 # number of layers in the neural network\n \n # Implement [LINEAR -> RELU]*(L-1). Add \"cache\" to the \"caches\" list.\n # The for loop starts at 1 because layer 0 is the input\n for l in range(1, L):\n A_prev = A \n #(≈ 2 lines of code)\n # A, cache = ...\n # caches ...\n # YOUR CODE STARTS HERE\n A, cache = linear_activation_forward(A_prev, parameters[\"W\" + str(l)], parameters[\"b\" + str(l)], activation = \"relu\")\n caches.append(cache)\n # YOUR CODE ENDS HERE\n \n # Implement LINEAR -> SIGMOID. Add \"cache\" to the \"caches\" list.\n #(≈ 2 lines of code)\n # AL, cache = ...\n # caches ...\n # YOUR CODE STARTS HERE\n AL, cache = linear_activation_forward(A, parameters[\"W\" + str(L)], parameters[\"b\" + str(L)], activation = \"sigmoid\")\n caches.append(cache)\n # YOUR CODE ENDS HERE\n \n return AL, caches", "_____no_output_____" ], [ "t_X, t_parameters = L_model_forward_test_case_2hidden()\nt_AL, t_caches = L_model_forward(t_X, t_parameters)\n\nprint(\"AL = \" + str(t_AL))\n\nL_model_forward_test(L_model_forward)", "AL = [[0.03921668 0.70498921 0.19734387 0.04728177]]\n\u001b[92m All tests passed.\n" ] ], [ [ "***Expected output***\n```\nAL = [[0.03921668 0.70498921 0.19734387 0.04728177]]\n```", "_____no_output_____" ], [ "**Awesome!** You've implemented a full forward propagation that takes the input X and outputs a row vector $A^{[L]}$ containing your predictions. It also records all intermediate values in \"caches\". Using $A^{[L]}$, you can compute the cost of your predictions.", "_____no_output_____" ], [ "<a name='5'></a>\n## 5 - Cost Function\n\nNow you can implement forward and backward propagation! You need to compute the cost, in order to check whether your model is actually learning.\n\n<a name='ex-6'></a>\n### Exercise 6 - compute_cost\nCompute the cross-entropy cost $J$, using the following formula: $$-\\frac{1}{m} \\sum\\limits_{i = 1}^{m} (y^{(i)}\\log\\left(a^{[L] (i)}\\right) + (1-y^{(i)})\\log\\left(1- a^{[L](i)}\\right)) \\tag{7}$$\n", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: compute_cost\n\ndef compute_cost(AL, Y):\n \"\"\"\n Implement the cost function defined by equation (7).\n\n Arguments:\n AL -- probability vector corresponding to your label predictions, shape (1, number of examples)\n Y -- true \"label\" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)\n\n Returns:\n cost -- cross-entropy cost\n \"\"\"\n \n m = Y.shape[1]\n\n # Compute loss from aL and y.\n # (≈ 1 lines of code)\n # cost = ...\n # YOUR CODE STARTS HERE\n cost = -(np.dot(np.log(AL), Y.T) + np.dot(np.log(1-AL), (1-Y).T)) / m\n # YOUR CODE ENDS HERE\n \n cost = np.squeeze(cost) # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).\n\n \n return cost", "_____no_output_____" ], [ "t_Y, t_AL = compute_cost_test_case()\nt_cost = compute_cost(t_AL, t_Y)\n\nprint(\"Cost: \" + str(t_cost))\n\ncompute_cost_test(compute_cost)", "Cost: 0.2797765635793423\n\u001b[92m All tests passed.\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td><b>cost</b> </td>\n <td> 0.2797765635793422</td> \n </tr>\n</table>", "_____no_output_____" ], [ "<a name='6'></a>\n## 6 - Backward Propagation Module\n\nJust as you did for the forward propagation, you'll implement helper functions for backpropagation. Remember that backpropagation is used to calculate the gradient of the loss function with respect to the parameters. \n\n**Reminder**: \n<img src=\"images/backprop_kiank.png\" style=\"width:650px;height:250px;\">\n<caption><center><font color='purple'><b>Figure 3</b>: Forward and Backward propagation for LINEAR->RELU->LINEAR->SIGMOID <br> <i>The purple blocks represent the forward propagation, and the red blocks represent the backward propagation.</font></center></caption>\n\n\n<!-- \nFor those of you who are experts in calculus (which you don't need to be to do this assignment!), the chain rule of calculus can be used to derive the derivative of the loss $\\mathcal{L}$ with respect to $z^{[1]}$ in a 2-layer network as follows:\n\n$$\\frac{d \\mathcal{L}(a^{[2]},y)}{{dz^{[1]}}} = \\frac{d\\mathcal{L}(a^{[2]},y)}{{da^{[2]}}}\\frac{{da^{[2]}}}{{dz^{[2]}}}\\frac{{dz^{[2]}}}{{da^{[1]}}}\\frac{{da^{[1]}}}{{dz^{[1]}}} \\tag{8} $$\n\nIn order to calculate the gradient $dW^{[1]} = \\frac{\\partial L}{\\partial W^{[1]}}$, use the previous chain rule and you do $dW^{[1]} = dz^{[1]} \\times \\frac{\\partial z^{[1]} }{\\partial W^{[1]}}$. During backpropagation, at each step you multiply your current gradient by the gradient corresponding to the specific layer to get the gradient you wanted.\n\nEquivalently, in order to calculate the gradient $db^{[1]} = \\frac{\\partial L}{\\partial b^{[1]}}$, you use the previous chain rule and you do $db^{[1]} = dz^{[1]} \\times \\frac{\\partial z^{[1]} }{\\partial b^{[1]}}$.\n\nThis is why we talk about **backpropagation**.\n!-->\n\nNow, similarly to forward propagation, you're going to build the backward propagation in three steps:\n1. LINEAR backward\n2. LINEAR -> ACTIVATION backward where ACTIVATION computes the derivative of either the ReLU or sigmoid activation\n3. [LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID backward (whole model)", "_____no_output_____" ], [ "For the next exercise, you will need to remember that:\n\n- `b` is a matrix(np.ndarray) with 1 column and n rows, i.e: b = [[1.0], [2.0]] (remember that `b` is a constant)\n- np.sum performs a sum over the elements of a ndarray\n- axis=1 or axis=0 specify if the sum is carried out by rows or by columns respectively\n- keepdims specifies if the original dimensions of the matrix must be kept.\n- Look at the following example to clarify:", "_____no_output_____" ] ], [ [ "A = np.array([[1, 2], [3, 4]])\n\nprint('axis=1 and keepdims=True')\nprint(np.sum(A, axis=1, keepdims=True))\nprint('axis=1 and keepdims=False')\nprint(np.sum(A, axis=1, keepdims=False))\nprint('axis=0 and keepdims=True')\nprint(np.sum(A, axis=0, keepdims=True))\nprint('axis=0 and keepdims=False')\nprint(np.sum(A, axis=0, keepdims=False))", "axis=1 and keepdims=True\n[[3]\n [7]]\naxis=1 and keepdims=False\n[3 7]\naxis=0 and keepdims=True\n[[4 6]]\naxis=0 and keepdims=False\n[4 6]\n" ] ], [ [ "<a name='6-1'></a>\n### 6.1 - Linear Backward\n\nFor layer $l$, the linear part is: $Z^{[l]} = W^{[l]} A^{[l-1]} + b^{[l]}$ (followed by an activation).\n\nSuppose you have already calculated the derivative $dZ^{[l]} = \\frac{\\partial \\mathcal{L} }{\\partial Z^{[l]}}$. You want to get $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$.\n\n<img src=\"images/linearback_kiank.png\" style=\"width:250px;height:300px;\">\n<caption><center><font color='purple'><b>Figure 4</b></font></center></caption>\n\nThe three outputs $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$ are computed using the input $dZ^{[l]}$.\n\nHere are the formulas you need:\n$$ dW^{[l]} = \\frac{\\partial \\mathcal{J} }{\\partial W^{[l]}} = \\frac{1}{m} dZ^{[l]} A^{[l-1] T} \\tag{8}$$\n$$ db^{[l]} = \\frac{\\partial \\mathcal{J} }{\\partial b^{[l]}} = \\frac{1}{m} \\sum_{i = 1}^{m} dZ^{[l](i)}\\tag{9}$$\n$$ dA^{[l-1]} = \\frac{\\partial \\mathcal{L} }{\\partial A^{[l-1]}} = W^{[l] T} dZ^{[l]} \\tag{10}$$\n\n\n$A^{[l-1] T}$ is the transpose of $A^{[l-1]}$. ", "_____no_output_____" ], [ "<a name='ex-7'></a>\n### Exercise 7 - linear_backward \n\nUse the 3 formulas above to implement `linear_backward()`.\n\n**Hint**:\n\n- In numpy you can get the transpose of an ndarray `A` using `A.T` or `A.transpose()`", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: linear_backward\n\ndef linear_backward(dZ, cache):\n \"\"\"\n Implement the linear portion of backward propagation for a single layer (layer l)\n\n Arguments:\n dZ -- Gradient of the cost with respect to the linear output (of current layer l)\n cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer\n\n Returns:\n dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n dW -- Gradient of the cost with respect to W (current layer l), same shape as W\n db -- Gradient of the cost with respect to b (current layer l), same shape as b\n \"\"\"\n A_prev, W, b = cache\n m = A_prev.shape[1]\n\n ### START CODE HERE ### (≈ 3 lines of code)\n # dW = ...\n # db = ... sum by the rows of dZ with keepdims=True\n # dA_prev = ...\n # YOUR CODE STARTS HERE\n dW = np.dot(dZ, A_prev.T) / m\n db = np.sum(dZ, axis=1, keepdims=True) / m\n dA_prev = np.dot(W.T, dZ)\n # YOUR CODE ENDS HERE\n \n return dA_prev, dW, db", "_____no_output_____" ], [ "t_dZ, t_linear_cache = linear_backward_test_case()\nt_dA_prev, t_dW, t_db = linear_backward(t_dZ, t_linear_cache)\n\nprint(\"dA_prev: \" + str(t_dA_prev))\nprint(\"dW: \" + str(t_dW))\nprint(\"db: \" + str(t_db))\n\nlinear_backward_test(linear_backward)", "dA_prev: [[-1.15171336 0.06718465 -0.3204696 2.09812712]\n [ 0.60345879 -3.72508701 5.81700741 -3.84326836]\n [-0.4319552 -1.30987417 1.72354705 0.05070578]\n [-0.38981415 0.60811244 -1.25938424 1.47191593]\n [-2.52214926 2.67882552 -0.67947465 1.48119548]]\ndW: [[ 0.07313866 -0.0976715 -0.87585828 0.73763362 0.00785716]\n [ 0.85508818 0.37530413 -0.59912655 0.71278189 -0.58931808]\n [ 0.97913304 -0.24376494 -0.08839671 0.55151192 -0.10290907]]\ndb: [[-0.14713786]\n [-0.11313155]\n [-0.13209101]]\n\u001b[92m All tests passed.\n" ] ], [ [ "**Expected Output**:\n```\ndA_prev: [[-1.15171336 0.06718465 -0.3204696 2.09812712]\n [ 0.60345879 -3.72508701 5.81700741 -3.84326836]\n [-0.4319552 -1.30987417 1.72354705 0.05070578]\n [-0.38981415 0.60811244 -1.25938424 1.47191593]\n [-2.52214926 2.67882552 -0.67947465 1.48119548]]\ndW: [[ 0.07313866 -0.0976715 -0.87585828 0.73763362 0.00785716]\n [ 0.85508818 0.37530413 -0.59912655 0.71278189 -0.58931808]\n [ 0.97913304 -0.24376494 -0.08839671 0.55151192 -0.10290907]]\ndb: [[-0.14713786]\n [-0.11313155]\n [-0.13209101]]\n ```", "_____no_output_____" ], [ "<a name='6-2'></a>\n### 6.2 - Linear-Activation Backward\n\nNext, you will create a function that merges the two helper functions: **`linear_backward`** and the backward step for the activation **`linear_activation_backward`**. \n\nTo help you implement `linear_activation_backward`, two backward functions have been provided:\n- **`sigmoid_backward`**: Implements the backward propagation for SIGMOID unit. You can call it as follows:\n\n```python\ndZ = sigmoid_backward(dA, activation_cache)\n```\n\n- **`relu_backward`**: Implements the backward propagation for RELU unit. You can call it as follows:\n\n```python\ndZ = relu_backward(dA, activation_cache)\n```\n\nIf $g(.)$ is the activation function, \n`sigmoid_backward` and `relu_backward` compute $$dZ^{[l]} = dA^{[l]} * g'(Z^{[l]}). \\tag{11}$$ \n\n<a name='ex-8'></a>\n### Exercise 8 - linear_activation_backward\n\nImplement the backpropagation for the *LINEAR->ACTIVATION* layer.", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: linear_activation_backward\n\ndef linear_activation_backward(dA, cache, activation):\n \"\"\"\n Implement the backward propagation for the LINEAR->ACTIVATION layer.\n \n Arguments:\n dA -- post-activation gradient for current layer l \n cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently\n activation -- the activation to be used in this layer, stored as a text string: \"sigmoid\" or \"relu\"\n \n Returns:\n dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n dW -- Gradient of the cost with respect to W (current layer l), same shape as W\n db -- Gradient of the cost with respect to b (current layer l), same shape as b\n \"\"\"\n linear_cache, activation_cache = cache\n \n if activation == \"relu\":\n #(≈ 2 lines of code)\n # dZ = ...\n # dA_prev, dW, db = ...\n # YOUR CODE STARTS HERE\n dZ = relu_backward(dA, activation_cache)\n dA_prev, dW, db = linear_backward(dZ, linear_cache)\n # YOUR CODE ENDS HERE\n \n elif activation == \"sigmoid\":\n #(≈ 2 lines of code)\n # dZ = ...\n # dA_prev, dW, db = ...\n # YOUR CODE STARTS HERE\n dZ = sigmoid_backward(dA, activation_cache)\n dA_prev, dW, db = linear_backward(dZ, linear_cache)\n # YOUR CODE ENDS HERE\n \n return dA_prev, dW, db", "_____no_output_____" ], [ "t_dAL, t_linear_activation_cache = linear_activation_backward_test_case()\n\nt_dA_prev, t_dW, t_db = linear_activation_backward(t_dAL, t_linear_activation_cache, activation = \"sigmoid\")\nprint(\"With sigmoid: dA_prev = \" + str(t_dA_prev))\nprint(\"With sigmoid: dW = \" + str(t_dW))\nprint(\"With sigmoid: db = \" + str(t_db))\n\nt_dA_prev, t_dW, t_db = linear_activation_backward(t_dAL, t_linear_activation_cache, activation = \"relu\")\nprint(\"With relu: dA_prev = \" + str(t_dA_prev))\nprint(\"With relu: dW = \" + str(t_dW))\nprint(\"With relu: db = \" + str(t_db))\n\nlinear_activation_backward_test(linear_activation_backward)", "With sigmoid: dA_prev = [[ 0.11017994 0.01105339]\n [ 0.09466817 0.00949723]\n [-0.05743092 -0.00576154]]\nWith sigmoid: dW = [[ 0.10266786 0.09778551 -0.01968084]]\nWith sigmoid: db = [[-0.05729622]]\nWith relu: dA_prev = [[ 0.44090989 0. ]\n [ 0.37883606 0. ]\n [-0.2298228 0. ]]\nWith relu: dW = [[ 0.44513824 0.37371418 -0.10478989]]\nWith relu: db = [[-0.20837892]]\n\u001b[92m All tests passed.\n" ] ], [ [ "**Expected output:**\n\n```\nWith sigmoid: dA_prev = [[ 0.11017994 0.01105339]\n [ 0.09466817 0.00949723]\n [-0.05743092 -0.00576154]]\nWith sigmoid: dW = [[ 0.10266786 0.09778551 -0.01968084]]\nWith sigmoid: db = [[-0.05729622]]\nWith relu: dA_prev = [[ 0.44090989 0. ]\n [ 0.37883606 0. ]\n [-0.2298228 0. ]]\nWith relu: dW = [[ 0.44513824 0.37371418 -0.10478989]]\nWith relu: db = [[-0.20837892]]\n```", "_____no_output_____" ], [ "<a name='6-3'></a>\n### 6.3 - L-Model Backward \n\nNow you will implement the backward function for the whole network! \n\nRecall that when you implemented the `L_model_forward` function, at each iteration, you stored a cache which contains (X,W,b, and z). In the back propagation module, you'll use those variables to compute the gradients. Therefore, in the `L_model_backward` function, you'll iterate through all the hidden layers backward, starting from layer $L$. On each step, you will use the cached values for layer $l$ to backpropagate through layer $l$. Figure 5 below shows the backward pass. \n\n\n<img src=\"images/mn_backward.png\" style=\"width:450px;height:300px;\">\n<caption><center><font color='purple'><b>Figure 5</b>: Backward pass</font></center></caption>\n\n**Initializing backpropagation**:\n\nTo backpropagate through this network, you know that the output is: \n$A^{[L]} = \\sigma(Z^{[L]})$. Your code thus needs to compute `dAL` $= \\frac{\\partial \\mathcal{L}}{\\partial A^{[L]}}$.\nTo do so, use this formula (derived using calculus which, again, you don't need in-depth knowledge of!):\n```python\ndAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) # derivative of cost with respect to AL\n```\n\nYou can then use this post-activation gradient `dAL` to keep going backward. As seen in Figure 5, you can now feed in `dAL` into the LINEAR->SIGMOID backward function you implemented (which will use the cached values stored by the L_model_forward function). \n\nAfter that, you will have to use a `for` loop to iterate through all the other layers using the LINEAR->RELU backward function. You should store each dA, dW, and db in the grads dictionary. To do so, use this formula : \n\n$$grads[\"dW\" + str(l)] = dW^{[l]}\\tag{15} $$\n\nFor example, for $l=3$ this would store $dW^{[l]}$ in `grads[\"dW3\"]`.\n\n<a name='ex-9'></a>\n### Exercise 9 - L_model_backward\n\nImplement backpropagation for the *[LINEAR->RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID* model.", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: L_model_backward\n\ndef L_model_backward(AL, Y, caches):\n \"\"\"\n Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group\n \n Arguments:\n AL -- probability vector, output of the forward propagation (L_model_forward())\n Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat)\n caches -- list of caches containing:\n every cache of linear_activation_forward() with \"relu\" (it's caches[l], for l in range(L-1) i.e l = 0...L-2)\n the cache of linear_activation_forward() with \"sigmoid\" (it's caches[L-1])\n \n Returns:\n grads -- A dictionary with the gradients\n grads[\"dA\" + str(l)] = ... \n grads[\"dW\" + str(l)] = ...\n grads[\"db\" + str(l)] = ... \n \"\"\"\n grads = {}\n L = len(caches) # the number of layers\n m = AL.shape[1]\n Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL\n \n # Initializing the backpropagation\n #(1 line of code)\n # dAL = ...\n # YOUR CODE STARTS HERE\n dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))\n # YOUR CODE ENDS HERE\n \n # Lth layer (SIGMOID -> LINEAR) gradients. Inputs: \"dAL, current_cache\". Outputs: \"grads[\"dAL-1\"], grads[\"dWL\"], grads[\"dbL\"]\n #(approx. 5 lines)\n # current_cache = ...\n # dA_prev_temp, dW_temp, db_temp = ...\n # grads[\"dA\" + str(L-1)] = ...\n # grads[\"dW\" + str(L)] = ...\n # grads[\"db\" + str(L)] = ...\n # YOUR CODE STARTS HERE\n current_cache = caches[L-1]\n dA_prev_temp, dW_temp, db_temp = linear_activation_backward(dAL, current_cache, \"sigmoid\")\n grads[\"dA\" + str(L-1)] = dA_prev_temp\n grads[\"dW\" + str(L)] = dW_temp\n grads[\"db\" + str(L)] = db_temp\n # YOUR CODE ENDS HERE\n \n # Loop from l=L-2 to l=0\n for l in reversed(range(L-1)):\n # lth layer: (RELU -> LINEAR) gradients.\n # Inputs: \"grads[\"dA\" + str(l + 1)], current_cache\". Outputs: \"grads[\"dA\" + str(l)] , grads[\"dW\" + str(l + 1)] , grads[\"db\" + str(l + 1)] \n #(approx. 5 lines)\n # current_cache = ...\n # dA_prev_temp, dW_temp, db_temp = ...\n # grads[\"dA\" + str(l)] = ...\n # grads[\"dW\" + str(l + 1)] = ...\n # grads[\"db\" + str(l + 1)] = ...\n # YOUR CODE STARTS HERE\n current_cache = caches[l]\n dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads[\"dA\" + str(l+1)], current_cache, \"relu\")\n grads[\"dA\" + str(l)] = dA_prev_temp\n grads[\"dW\" + str(l+1)] = dW_temp\n grads[\"db\" + str(l+1)] = db_temp\n # YOUR CODE ENDS HERE\n\n return grads", "_____no_output_____" ], [ "t_AL, t_Y_assess, t_caches = L_model_backward_test_case()\ngrads = L_model_backward(t_AL, t_Y_assess, t_caches)\n\nprint(\"dA0 = \" + str(grads['dA0']))\nprint(\"dA1 = \" + str(grads['dA1']))\nprint(\"dW1 = \" + str(grads['dW1']))\nprint(\"dW2 = \" + str(grads['dW2']))\nprint(\"db1 = \" + str(grads['db1']))\nprint(\"db2 = \" + str(grads['db2']))\n\nL_model_backward_test(L_model_backward)", "dA0 = [[ 0. 0.52257901]\n [ 0. -0.3269206 ]\n [ 0. -0.32070404]\n [ 0. -0.74079187]]\ndA1 = [[ 0.12913162 -0.44014127]\n [-0.14175655 0.48317296]\n [ 0.01663708 -0.05670698]]\ndW1 = [[0.41010002 0.07807203 0.13798444 0.10502167]\n [0. 0. 0. 0. ]\n [0.05283652 0.01005865 0.01777766 0.0135308 ]]\ndW2 = [[-0.39202432 -0.13325855 -0.04601089]]\ndb1 = [[-0.22007063]\n [ 0. ]\n [-0.02835349]]\ndb2 = [[0.15187861]]\n\u001b[92m All tests passed.\n" ] ], [ [ "**Expected output:**\n\n```\ndA0 = [[ 0. 0.52257901]\n [ 0. -0.3269206 ]\n [ 0. -0.32070404]\n [ 0. -0.74079187]]\ndA1 = [[ 0.12913162 -0.44014127]\n [-0.14175655 0.48317296]\n [ 0.01663708 -0.05670698]]\ndW1 = [[0.41010002 0.07807203 0.13798444 0.10502167]\n [0. 0. 0. 0. ]\n [0.05283652 0.01005865 0.01777766 0.0135308 ]]\ndW2 = [[-0.39202432 -0.13325855 -0.04601089]]\ndb1 = [[-0.22007063]\n [ 0. ]\n [-0.02835349]]\ndb2 = [[0.15187861]]\n```", "_____no_output_____" ], [ "<a name='6-4'></a>\n### 6.4 - Update Parameters\n\nIn this section, you'll update the parameters of the model, using gradient descent: \n\n$$ W^{[l]} = W^{[l]} - \\alpha \\text{ } dW^{[l]} \\tag{16}$$\n$$ b^{[l]} = b^{[l]} - \\alpha \\text{ } db^{[l]} \\tag{17}$$\n\nwhere $\\alpha$ is the learning rate. \n\nAfter computing the updated parameters, store them in the parameters dictionary. ", "_____no_output_____" ], [ "<a name='ex-10'></a>\n### Exercise 10 - update_parameters\n\nImplement `update_parameters()` to update your parameters using gradient descent.\n\n**Instructions**:\nUpdate parameters using gradient descent on every $W^{[l]}$ and $b^{[l]}$ for $l = 1, 2, ..., L$. ", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: update_parameters\n\ndef update_parameters(params, grads, learning_rate):\n \"\"\"\n Update parameters using gradient descent\n \n Arguments:\n params -- python dictionary containing your parameters \n grads -- python dictionary containing your gradients, output of L_model_backward\n \n Returns:\n parameters -- python dictionary containing your updated parameters \n parameters[\"W\" + str(l)] = ... \n parameters[\"b\" + str(l)] = ...\n \"\"\"\n parameters = params.copy()\n L = len(parameters) // 2 # number of layers in the neural network\n\n # Update rule for each parameter. Use a for loop.\n #(≈ 2 lines of code)\n for l in range(L):\n # parameters[\"W\" + str(l+1)] = ...\n # parameters[\"b\" + str(l+1)] = ...\n # YOUR CODE STARTS HERE\n parameters[\"W\" + str(l+1)] = params[\"W\" + str(l+1)] - learning_rate * grads[\"dW\" + str(l+1)]\n parameters[\"b\" + str(l+1)] = params[\"b\" + str(l+1)] - learning_rate * grads[\"db\" + str(l+1)]\n # YOUR CODE ENDS HERE\n return parameters", "_____no_output_____" ], [ "t_parameters, grads = update_parameters_test_case()\nt_parameters = update_parameters(t_parameters, grads, 0.1)\n\nprint (\"W1 = \"+ str(t_parameters[\"W1\"]))\nprint (\"b1 = \"+ str(t_parameters[\"b1\"]))\nprint (\"W2 = \"+ str(t_parameters[\"W2\"]))\nprint (\"b2 = \"+ str(t_parameters[\"b2\"]))\n\nupdate_parameters_test(update_parameters)", "W1 = [[-0.59562069 -0.09991781 -2.14584584 1.82662008]\n [-1.76569676 -0.80627147 0.51115557 -1.18258802]\n [-1.0535704 -0.86128581 0.68284052 2.20374577]]\nb1 = [[-0.04659241]\n [-1.28888275]\n [ 0.53405496]]\nW2 = [[-0.55569196 0.0354055 1.32964895]]\nb2 = [[-0.84610769]]\n\u001b[92m All tests passed.\n" ] ], [ [ "**Expected output:**\n\n```\nW1 = [[-0.59562069 -0.09991781 -2.14584584 1.82662008]\n [-1.76569676 -0.80627147 0.51115557 -1.18258802]\n [-1.0535704 -0.86128581 0.68284052 2.20374577]]\nb1 = [[-0.04659241]\n [-1.28888275]\n [ 0.53405496]]\nW2 = [[-0.55569196 0.0354055 1.32964895]]\nb2 = [[-0.84610769]]\n```", "_____no_output_____" ], [ "### Congratulations! \n\nYou've just implemented all the functions required for building a deep neural network, including: \n\n- Using non-linear units improve your model\n- Building a deeper neural network (with more than 1 hidden layer)\n- Implementing an easy-to-use neural network class\n\nThis was indeed a long assignment, but the next part of the assignment is easier. ;) \n\nIn the next assignment, you'll be putting all these together to build two models:\n\n- A two-layer neural network\n- An L-layer neural network\n\nYou will in fact use these models to classify cat vs non-cat images! (Meow!) Great work and see you next time. ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ] ]
cb65f668117f17813cfd9cca78e40e21335cd3a0
14,043
ipynb
Jupyter Notebook
chestxray_evalutation.ipynb
hmsch/natural-synthetic-anomalies
64d1626c1cbfdfc4c92af5ddd8ad8187052a5717
[ "MIT" ]
12
2021-11-22T01:42:44.000Z
2022-02-09T04:22:31.000Z
chestxray_evalutation.ipynb
hmsch/natural-synthetic-anomalies
64d1626c1cbfdfc4c92af5ddd8ad8187052a5717
[ "MIT" ]
2
2022-02-27T07:56:29.000Z
2022-03-05T20:23:04.000Z
chestxray_evalutation.ipynb
hmsch/natural-synthetic-anomalies
64d1626c1cbfdfc4c92af5ddd8ad8187052a5717
[ "MIT" ]
2
2021-11-22T00:31:21.000Z
2022-02-01T02:04:06.000Z
34.932836
148
0.510503
[ [ [ "import os\nimport numpy as np\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms as T\nimport cv2\nimport pandas as pd\n\nfrom self_sup_data.chest_xray import SelfSupChestXRay\nfrom model.resnet import resnet18_enc_dec\nfrom train_chest_xray import SETTINGS\nfrom experiments.chest_xray_tasks import test_real_anomalies\n\n\ndef test(test_dat, setting, device, preact=False, pool=True, final=True, show=True, plots=False):\n if final:\n fname = os.path.join(model_dir, setting.get('out_dir'), 'final_' + setting.get('fname'))\n else: \n fname = os.path.join(model_dir, setting.get('out_dir'), setting.get('fname'))\n print(fname)\n if not os.path.exists(fname):\n return np.nan, np.nan\n\n model = resnet18_enc_dec(num_classes=1, preact=preact, pool=pool, in_channels=1,\n final_activation=setting.get('final_activation')).to(device)\n if final:\n model.load_state_dict(torch.load(fname))\n else:\n model.load_state_dict(torch.load(fname).get('model_state_dict'))\n \n if plots:\n sample_ap, sample_auroc, fig = test_real_anomalies(model, test_dat, \n device=device, batch_size=16, show=show, full_size=True)\n fig.savefig(os.path.join(out_dir, setting.get('fname')[:-3] + '.png'))\n plt.close(fig)\n else:\n sample_ap, sample_auroc, _ = test_real_anomalies(model, test_dat, \n device=device, batch_size=16, show=show, plots=plots, full_size=True)\n \n return sample_ap, sample_auroc\n\n\nmodel_dir = 'put/your/path/here'\nif not os.path.exists(model_dir):\n os.makedirs(model_dir)\n \nout_dir = 'put/your/path/here'\nif not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\ndata_dir = 'put/your/path/here'\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(f'Using {device}')", "Using cuda\n" ] ], [ [ "# Evaluation for male PA", "_____no_output_____" ] ], [ [ "with open('self_sup_data/chest_xray_lists/norm_MaleAdultPA_test_curated_list.txt', \"r\") as f:\n normal_test_files = f.read().splitlines()\nwith open('self_sup_data/chest_xray_lists/anomaly_MaleAdultPA_test_curated_list.txt', \"r\") as f:\n anom_test_files = f.read().splitlines()\n\nmodes = list(SETTINGS.keys())\n\nsample_ap_df = pd.DataFrame(columns=modes)\nsample_auroc_df = pd.DataFrame(columns=modes)\n\ntest_dat = SelfSupChestXRay(data_dir=data_dir, normal_files=normal_test_files, anom_files=anom_test_files,\n is_train=False, res=256, transform=T.CenterCrop(224))\nsample_aps, sample_aurocs = {}, {}\nfor mode in modes:\n sample_aps[mode], sample_aurocs[mode] = test(\n test_dat, SETTINGS.get(mode), device, preact=False, pool=True, final=True)\n\nsample_ap_df = sample_ap_df.append(sample_aps, ignore_index=True).transpose()\nsample_auroc_df = sample_auroc_df.append(sample_aurocs, ignore_index=True).transpose()\n", "_____no_output_____" ], [ "pd.options.display.float_format = '{:3.1f}'.format\n\nsample_table = 100 * sample_auroc_df.transpose()\n\ncols_shift = sample_table.loc[: , 'Shift-M':'Shift-M-123425']\ncols_shift_int = sample_table.loc[: , 'Shift-Intensity-M':'Shift-Intensity-M-123425']\ncols_shift_raw_int = sample_table.loc[: , 'Shift-Raw-Intensity-M':'Shift-Raw-Intensity-M-123425']\ncols_pii = sample_table.loc[: , 'FPI-Poisson':'FPI-Poisson-123425']\n\nmerge_func = lambda x: r'{:3.1f} {{\\tiny $\\pm$ {:3.1f}}}'.format(*x)\nsample_table['Shift'] = list(map(merge_func, zip(cols_shift.mean(axis=1), cols_shift.std(axis=1))))\nsample_table['Shift-Intensity'] = list(map(merge_func, zip(cols_shift_int.mean(axis=1), cols_shift_int.std(axis=1))))\nsample_table['Shift-Raw-Intensity'] = list(map(merge_func, zip(cols_shift_raw_int.mean(axis=1), cols_shift_raw_int.std(axis=1))))\nsample_table['FPI-Poisson'] = list(map(merge_func, zip(cols_pii.mean(axis=1), cols_pii.std(axis=1))))\n\n\nsample_table = sample_table[['CutPaste', 'FPI', 'FPI-Poisson', \n 'Shift', 'Shift-Raw-Intensity', 'Shift-Intensity']].rename(\n columns={'Shift':'Ours (binary)', 'Shift-Intensity':'Ours (logistic)', 'Shift-Raw-Intensity':'Ours (continous)'})\n\nprint(sample_table.to_latex(escape=False))", "\\begin{tabular}{lrrllll}\n\\toprule\n{} & CutPaste & FPI & FPI-Poisson & Ours (binary) & Ours (continous) & Ours (logistic) \\\\\n\\midrule\n0 & 59.8 & 73.7 & 91.7 {\\tiny $\\pm$ 0.6} & 94.0 {\\tiny $\\pm$ 0.5} & 93.4 {\\tiny $\\pm$ 0.3} & 94.0 {\\tiny $\\pm$ 0.6} \\\\\n\\bottomrule\n\\end{tabular}\n\n" ], [ "sample_table # male", "_____no_output_____" ] ], [ [ "# Evaluation for female PA", "_____no_output_____" ] ], [ [ "with open('self_sup_data/chest_xray_lists/norm_FemaleAdultPA_test_curated_list.txt', \"r\") as f:\n normal_test_files = f.read().splitlines()\nwith open('self_sup_data/chest_xray_lists/anomaly_FemaleAdultPA_test_curated_list.txt', \"r\") as f:\n anom_test_files = f.read().splitlines()\n\nmodes = list(SETTINGS.keys())\n\nsample_ap_df = pd.DataFrame(columns=modes)\nsample_auroc_df = pd.DataFrame(columns=modes)\n\ntest_dat = SelfSupChestXRay(data_dir=data_dir, normal_files=normal_test_files, anom_files=anom_test_files,\n is_train=False, res=256, transform=T.CenterCrop(224))\nsample_aps, sample_aurocs = {}, {}\nfor mode in modes:\n sample_aps[mode], sample_aurocs[mode] = test(\n test_dat, SETTINGS.get(mode), device, preact=False, pool=True, final=True)\n\nsample_ap_df = sample_ap_df.append(sample_aps, ignore_index=True).transpose()\nsample_auroc_df = sample_auroc_df.append(sample_aurocs, ignore_index=True).transpose()", "_____no_output_____" ], [ "pd.options.display.float_format = '{:3.1f}'.format\n\nsample_table = 100 * sample_auroc_df.transpose()\n\ncols_shift = sample_table.loc[: , 'Shift-M':'Shift-M-123425']\ncols_shift_int = sample_table.loc[: , 'Shift-Intensity-M':'Shift-Intensity-M-123425']\ncols_shift_raw_int = sample_table.loc[: , 'Shift-Raw-Intensity-M':'Shift-Raw-Intensity-M-123425']\ncols_pii = sample_table.loc[: , 'FPI-Poisson':'FPI-Poisson-123425']\n\nmerge_func = lambda x: r'{:3.1f} {{\\tiny $\\pm$ {:3.1f}}}'.format(*x)\nsample_table['Shift'] = list(map(merge_func, zip(cols_shift.mean(axis=1), cols_shift.std(axis=1))))\nsample_table['Shift-Intensity'] = list(map(merge_func, zip(cols_shift_int.mean(axis=1), cols_shift_int.std(axis=1))))\nsample_table['Shift-Raw-Intensity'] = list(map(merge_func, zip(cols_shift_raw_int.mean(axis=1), cols_shift_raw_int.std(axis=1))))\nsample_table['FPI-Poisson'] = list(map(merge_func, zip(cols_pii.mean(axis=1), cols_pii.std(axis=1))))\n\n\nsample_table = sample_table[['CutPaste', 'FPI', 'FPI-Poisson', \n 'Shift', 'Shift-Raw-Intensity', 'Shift-Intensity']].rename(\n columns={'Shift':'Ours (binary)', 'Shift-Intensity':'Ours (logistic)', 'Shift-Raw-Intensity':'Ours (continous)'})\n\nprint(sample_table.to_latex(escape=False))", "\\begin{tabular}{lrrllll}\n\\toprule\n{} & CutPaste & FPI & FPI-Poisson & Ours (binary) & Ours (continous) & Ours (logistic) \\\\\n\\midrule\n0 & 56.2 & 67.4 & 92.8 {\\tiny $\\pm$ 0.4} & 94.3 {\\tiny $\\pm$ 0.6} & 93.0 {\\tiny $\\pm$ 0.4} & 94.0 {\\tiny $\\pm$ 0.5} \\\\\n\\bottomrule\n\\end{tabular}\n\n" ], [ "sample_table # female", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cb6616127dd88412fa67cd9303b8c7f042b911c0
11,818
ipynb
Jupyter Notebook
gratings.ipynb
ecs-vlc/opponency
f2eae25818be6c9c6e6541802b04b6c5e56112a2
[ "MIT" ]
12
2019-10-11T12:32:13.000Z
2021-09-05T06:26:43.000Z
gratings.ipynb
ecs-vlc/opponency
f2eae25818be6c9c6e6541802b04b6c5e56112a2
[ "MIT" ]
null
null
null
gratings.ipynb
ecs-vlc/opponency
f2eae25818be6c9c6e6541802b04b6c5e56112a2
[ "MIT" ]
1
2021-11-05T01:36:19.000Z
2021-11-05T01:36:19.000Z
79.315436
2,884
0.843798
[ [ [ "# Examples of grating patterns\n\nThis notebook shows a few examples of grating patterns used as stimuli for the spatial opponency experiments. It corresponds to Figure 5 in the appendinx.\n\n**Note**: The easiest way to use this is as a colab notebook, which allows you to dive in with no setup.\n\n## Load Dependencies - Colab Only", "_____no_output_____" ] ], [ [ "from os.path import exists\nif not exists('opponency.zip'):\n !wget -O opponency.zip https://github.com/ecs-vlc/opponency/archive/master.zip\n !unzip -qq opponency.zip\n !mv opponency-master/* ./\n !rm -r opponency-master", "_____no_output_____" ] ], [ [ "## Generate Plots", "_____no_output_____" ] ], [ [ "import numpy as np\n%matplotlib inline\nimport matplotlib.pyplot as plt \nfrom statistics.gratings import *\n\nfreq = 4\nfor degrees in [0, 45, 90, 135]:\n theta = degrees\n grating = make_grating(freq, theta, 0).squeeze(0)\n plt.figure()\n plt.axis('off')\n plt.imshow(grating.permute(1, 2, 0))\n plt.savefig('figures/' + str(degrees) + \"_grey.pdf\", bbox_inches='tight')", "0.6275 \tWARNING \tMonitor specification not found. Creating a temporary one...\n1.2914 \tWARNING \tMonitor specification not found. Creating a temporary one...\n1.8848 \tWARNING \tMonitor specification not found. Creating a temporary one...\n2.4509 \tWARNING \tMonitor specification not found. Creating a temporary one...\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb661cc31daeb12034b6660a0d9cfd5ab9bb8e6d
7,195
ipynb
Jupyter Notebook
Chapter6/Fig6_2_Trumpler1930.ipynb
CambridgeUniversityPress/Interstellar-and-Intergalactic-Medium
6d19cd4a517126e0f4737ba0f338117098224d92
[ "CC0-1.0", "CC-BY-4.0" ]
10
2021-04-20T07:26:10.000Z
2022-02-24T11:02:47.000Z
Chapter6/Fig6_2_Trumpler1930.ipynb
CambridgeUniversityPress/Interstellar-and-Intergalactic-Medium
6d19cd4a517126e0f4737ba0f338117098224d92
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
Chapter6/Fig6_2_Trumpler1930.ipynb
CambridgeUniversityPress/Interstellar-and-Intergalactic-Medium
6d19cd4a517126e0f4737ba0f338117098224d92
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
32.704545
178
0.589854
[ [ [ "# Trumpler 1930 Dust Extinction\n\nFigure 6.2 from Chapter 6 of *Interstellar and Intergalactic Medium* by Ryden & Pogge, 2021, \nCambridge University Press.\n\nData are from [Trumpler, R. 1930, Lick Observatory Bulletin #420, 14, 154](https://ui.adsabs.harvard.edu/abs/1930LicOB..14..154T), Table 3. The extinction curve derived\nuses a different normalization in the bulletin paper than in the oft-reproduced figure from the Trumpler\n1930 PASP paper ([Trumpler, R. 1930, PASP, 42, 267](https://ui.adsabs.harvard.edu/abs/1930PASP...42..267T), \nFigure 1).\n\nTable 3 gives distances and linear diameters to open star clusters. We've created two data files:\n * Trumpler_GoodData.txt - Unflagged \n * Trumpler_BadData.txt - Trumpler's \"somewhat uncertain or less reliable\" data, designed by the entry being printed in italics in Table 3.\n \nThe distances we use are from Table 3 column 8 (\"Obs.\"distance from spectral types) and column 10\n(\"from diam.\"), both converted to kiloparsecs.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nimport os\nimport sys\nimport math\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, LogLocator, NullFormatter\n\nimport warnings\nwarnings.filterwarnings('ignore',category=UserWarning, append=True)", "_____no_output_____" ] ], [ [ "## Standard Plot Format\n\nSetup the standard plotting format and make the plot. Fonts and resolution adopted follow CUP style.", "_____no_output_____" ] ], [ [ "figName = 'Fig6_2' \n\n# graphic aspect ratio = width/height\n\naspect = 4.0/3.0 # 4:3\n\n# Text width in inches - don't change, this is defined by the print layout\n\ntextWidth = 6.0 # inches\n\n# output format and resolution\n\nfigFmt = 'png'\ndpi = 600\n\n# Graphic dimensions \n\nplotWidth = dpi*textWidth\nplotHeight = plotWidth/aspect\naxisFontSize = 10\nlabelFontSize = 6\nlwidth = 0.5\naxisPad = 5\nwInches = textWidth \nhInches = wInches/aspect\n\n# Plot filename\n\nplotFile = f'{figName}.{figFmt}'\n\n# LaTeX is used throughout for markup of symbols, Times-Roman serif font\n\nplt.rc('text', usetex=True)\nplt.rc('font', **{'family':'serif','serif':['Times-Roman'],'weight':'bold','size':'16'})\n\n# Font and line weight defaults for axes\n\nmatplotlib.rc('axes',linewidth=lwidth)\nmatplotlib.rcParams.update({'font.size':axisFontSize})\n\n# axis and label padding\n\nplt.rcParams['xtick.major.pad'] = f'{axisPad}'\nplt.rcParams['ytick.major.pad'] = f'{axisPad}'\nplt.rcParams['axes.labelpad'] = f'{axisPad}'", "_____no_output_____" ] ], [ [ "## Trumpler (1930) Data and Extinction Curve\n\nThe data are derived from the Table 3 in Trumpler 1930, converted to modern units of kiloparsecs. We've divided\nthe data into two files based on Trumpler's 2-fold division of the data into reliable and \"\"somewhat uncertain \nor less reliable\", which we abbreviate as \"good\" and \"bad\", respectively. This is the division used for\nTrumpler's original diagram.\n\nThe Trumpler extintion curve is of the form:\n$$ d_{L} = d_{A} e^{\\kappa d_{A}/2}$$\nwhere the extinction coefficient plotted is $\\kappa=0.6$kpc$^{-1}$, plotted as a dashed line.", "_____no_output_____" ] ], [ [ "# Good data\n\ndata = pd.read_csv('Trumpler_GoodData.txt',sep=r'\\s+',comment='#')\ndLgood = np.array(data['dL']) # luminosity distance\ndAgood = np.array(data['dA']) # angular diameter distance\n\n# Bad data\n\ndata = pd.read_csv('Trumpler_BadData.txt',sep=r'\\s+',comment='#')\ndLbad = np.array(data['dL']) # luminosity distance\ndAbad = np.array(data['dA']) # angular diameter distance\n\n# Trumpler extinction curve\n\nk = 0.6 # kpc^-1 [modern units]\ndAext = np.linspace(0.0,4.0,401)\ndLext = dAext*np.exp(k*dAext/2)", "_____no_output_____" ] ], [ [ "## Cluster angular diameter distance vs. luminosity distance\n\nPlot open cluster angular distance against luminosity distance (what Trumpler called \"photometric distance\").\nGood data are ploted as filled circles, the bad (less-reliable) data are plotted as open circles. \n\nThe unextincted 1:1 relation is plotted as a dotted line.", "_____no_output_____" ] ], [ [ "fig,ax = plt.subplots()\n\nfig.set_dpi(dpi)\nfig.set_size_inches(wInches,hInches,forward=True)\n\nax.tick_params('both',length=6,width=lwidth,which='major',direction='in',top='on',right='on')\nax.tick_params('both',length=3,width=lwidth,which='minor',direction='in',top='on',right='on')\n\n# Limits\n\nax.xaxis.set_major_locator(MultipleLocator(1))\nax.xaxis.set_minor_locator(MultipleLocator(0.2))\nax.set_xlabel(r'Luminosity distance [kpc]')\nax.set_xlim(0,5)\n\nax.yaxis.set_major_locator(MultipleLocator(1))\nax.yaxis.set_minor_locator(MultipleLocator(0.2))\nax.set_ylabel(r'Angular diameter distance [kpc]')\nax.set_ylim(0,4)\n\nplt.plot(dLgood,dAgood,'o',mfc='black',mec='black',ms=3,zorder=10,mew=0.5)\nplt.plot(dLbad,dAbad,'o',mfc='white',mec='black',ms=3,zorder=9,mew=0.5)\n \nplt.plot([0,4],[0,4],':',color='black',lw=1,zorder=5)\nplt.plot(dLext,dAext,'--',color='black',lw=1,zorder=7)\n\nplt.plot()\nplt.savefig(plotFile,bbox_inches='tight',facecolor='white')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb6647246c37f644d33cb9ebe6c30aa63db491ea
106,609
ipynb
Jupyter Notebook
Notebooks/EOG_dataViz_09_02_2021.ipynb
gbernal/IEEEVR_paper_code
a62e286ff8ac7c3da8ebc8f6f64898dd0ae6845b
[ "MIT" ]
null
null
null
Notebooks/EOG_dataViz_09_02_2021.ipynb
gbernal/IEEEVR_paper_code
a62e286ff8ac7c3da8ebc8f6f64898dd0ae6845b
[ "MIT" ]
null
null
null
Notebooks/EOG_dataViz_09_02_2021.ipynb
gbernal/IEEEVR_paper_code
a62e286ff8ac7c3da8ebc8f6f64898dd0ae6845b
[ "MIT" ]
null
null
null
226.82766
67,268
0.907935
[ [ [ "#Mounts your google drive into this virtual machine\n\nfrom google.colab import drive, files\nimport sys\ndrive.mount('/content/drive')\n#Now we need to access the files downloaded, copy the path where you saved the files downloaded from the github repo and paste below\n\nsys.path.append('/content/drive/MyDrive/YOURPATH/SignalValidation/')\n", "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n" ], [ "%cd /content/drive/MyDrive/YOURPATH/SignalValidation/\n", "/content/drive/MyDrive/CogFlex\n" ], [ "!pip install neurokit2\n!pip install mne\n!pip install --upgrade pandas\n", "Requirement already satisfied: neurokit2 in /usr/local/lib/python3.7/dist-packages (0.1.4.1)\nRequirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from neurokit2) (3.2.2)\nRequirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from neurokit2) (0.22.2.post1)\nRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from neurokit2) (1.4.1)\nRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from neurokit2) (1.19.5)\nRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from neurokit2) (1.3.4)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->neurokit2) (1.3.2)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->neurokit2) (0.10.0)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->neurokit2) (2.4.7)\nRequirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->neurokit2) (2.8.2)\nRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from cycler>=0.10->matplotlib->neurokit2) (1.15.0)\nRequirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas->neurokit2) (2018.9)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->neurokit2) (1.0.1)\nRequirement already satisfied: mne in /usr/local/lib/python3.7/dist-packages (0.23.4)\nRequirement already satisfied: numpy>=1.15.4 in /usr/local/lib/python3.7/dist-packages (from mne) (1.19.5)\nRequirement already satisfied: scipy>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from mne) (1.4.1)\nRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (1.3.4)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas) (2.8.2)\nRequirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.7/dist-packages (from pandas) (1.19.5)\nRequirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas) (2018.9)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)\n" ], [ "%matplotlib inline\nimport signal_formatpeaks\nimport time\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport neurokit2 as nk\nimport mne\nimport matplotlib.pyplot as plt\nimport os\n\nimport random\n\nfrom sklearn.cross_decomposition import CCA\nfrom scipy import signal\n\nfrom scipy.signal import butter, lfilter\nfrom scipy.fft import fft, fftfreq, ifft\n\nimport pickle\nplt.rcParams['figure.figsize'] = [30, 20]", "_____no_output_____" ] ], [ [ "## **Offline EOG data visualization and processing**", "_____no_output_____" ] ], [ [ "data = pd.read_csv('/content/drive/MyDrive/YOURPATH/SharedPublicly/Data/Blink_EOG_RAW-2021-09-03_12-03-27.txt',header=4 ,sep=r'\\s*,\\s*',engine='python')\ndata.columns = [\"Sample Index\",\t\"EMG Channel 0\",\t\"EMG Channel 1\",\t\"EMG Channel 2\",\t\"EMG Channel 3\",\t\"EOG Channel 0\",\t\"EOG Channel 1\",\t\"EEG Channel 0\",\t\"EEG Channel 1\",\t\"EEG Channel 2\",\t\"EEG Channel 3\",\t\"EEG Channel 4\",\t\"EEG Channel 5\",\t\"EEG Channel 6\",\t\"EEG Channel 7\",\t\"EEG Channel 8\",\t\"EEG Channel 9\",\t\"PPG Channel 0\",\t\"PPG Channel 1\",\t\"EDA_Channel_0\",\t\"Other\",\t\"Raw PC Timestamp\",\t\"Raw Device Timestamp\",\t\"Other.1\",\t\"Timestamp\",\t\"Marker\",\t\"Timestamp (Formatted)\"]\ndata", "_____no_output_____" ], [ "def eog_process_detrend(veog_signal, sampling_rate=1000, **kwargs):\n \"\"\"Process an EOG signal.\n\n Convenience function that automatically processes an EOG signal.\n\n\n Parameters\n ----------\n veog_signal : Union[list, np.array, pd.Series]\n The raw vertical EOG channel. Note that it must be positively oriented, i.e., blinks must\n appear as upward peaks.\n sampling_rate : int\n The sampling frequency of `eog_signal` (in Hz, i.e., samples/second). Defaults to 1000.\n **kwargs\n Other arguments passed to other functions.\n\n Returns\n -------\n signals : DataFrame\n A DataFrame of the same length as the `eog_signal` containing the following columns:\n - *\"EOG_Raw\"*: the raw signal.\n - *\"EOG_Clean\"*: the cleaned signal.\n - *\"EOG_Blinks\"*: the blinks marked as \"1\" in a list of zeros.\n - *\"EOG_Rate\"*: eye blinks rate interpolated between blinks.\n\n info : dict\n A dictionary containing the samples at which the eye blinks occur, accessible with the key \"EOG_Blinks\"\n as well as the signals' sampling rate.\n\n See Also\n --------\n eog_clean, eog_findpeaks\n\n Examples\n --------\n >>> import neurokit2 as nk\n >>>\n >>> # Get data\n >>> eog_signal = nk.data('eog_100hz')\n >>>\n >>> signals, info = nk.eog_process(eog_signal, sampling_rate=100)\n\n References\n ----------\n - Agarwal, M., & Sivakumar, R. (2019, September). Blink: A Fully Automated Unsupervised Algorithm for\n Eye-Blink Detection in EEG Signals. In 2019 57th Annual Allerton Conference on Communication, Control,\n and Computing (Allerton) (pp. 1113-1121). IEEE.\n\n \"\"\"\n # Sanitize input\n eog_signal = nk.as_vector(veog_signal)\n\n # Clean signal\n # eog_cleaned = eog_clean(eog_signal, sampling_rate=sampling_rate, **kwargs)\n eog_cleaned = nk.signal_detrend(eog_signal)\n eog_cleaned = nk.signal_filter(eog_cleaned, lowcut=0.05, highcut=100)\n eog_cleaned = eog_cleaned - np.mean(eog_cleaned)\n\n eog_signal = eog_signal - np.mean(eog_signal)\n\n # Find peaks\n peaks = nk.eog_findpeaks(eog_cleaned, sampling_rate=sampling_rate, **kwargs)\n\n info = {\"EOG_Blinks\": peaks}\n info['sampling_rate'] = sampling_rate # Add sampling rate in dict info\n\n # Mark (potential) blink events\n signal_blinks = signal_formatpeaks._signal_from_indices(peaks, desired_length=len(eog_cleaned))\n\n # Rate computation\n rate = nk.signal_rate(peaks, sampling_rate=sampling_rate, desired_length=len(eog_cleaned))\n\n # Prepare output\n signals = pd.DataFrame(\n {\"EOG_Raw\": eog_signal, \"EOG_Clean\": eog_cleaned, \"EOG_Blinks\": signal_blinks, \"EOG_Rate\": rate}\n )\n\n return signals, info", "_____no_output_____" ], [ "#Collect and process EOG\neog_signal =data[\"EOG Channel 0\"]\neog_signal = nk.as_vector(eog_signal) # Extract the only column as a vector\nsignals2, info = eog_process_detrend(eog_signal[1250:], sampling_rate=250) #make sure to split eog_signal correctly", "_____no_output_____" ], [ "plt.rcParams['figure.figsize'] = [10, 5]\nplot = nk.eog_plot(signals2, info, sampling_rate=250)\npath = '/content/drive/MyDrive/YOURPATH/SharedPublicly/Figures'\nimage_format = 'eps' # e.g .png, .svg, etc.\nimage_name = 'galea_eog.eps'\nplot.savefig(path+image_name, format=image_format, dpi=1200)\nplt.tight_layout()", "The PostScript backend does not support transparency; partially transparent artists will be rendered opaque.\nThe PostScript backend does not support transparency; partially transparent artists will be rendered opaque.\nThe PostScript backend does not support transparency; partially transparent artists will be rendered opaque.\nThe PostScript backend does not support transparency; partially transparent artists will be rendered opaque.\nThe PostScript backend does not support transparency; partially transparent artists will be rendered opaque.\nThe PostScript backend does not support transparency; partially transparent artists will be rendered opaque.\n" ], [ "plt.rcParams['figure.figsize'] = [15, 2]\nnk.signal_plot(signals2.EOG_Clean)", "_____no_output_____" ] ], [ [ "### Signal Validation", "_____no_output_____" ] ], [ [ "#Difference in Power Spectrum\nprint(\"PSD Closed vs. Open difference\", np.mean(avg_psds_close) - np.mean(avg_psds_open))", "_____no_output_____" ], [ "#Computing EOG SNR:\nmean_Pow_signal = []\nmean_Pow_background = []\n\nd = signals2['EOG_Clean'].to_numpy()\n#Compute fourier transform\nN = d.shape[-1]\nFs = 250\ndt = 1/Fs\nT = N*dt\ndf = Fs/N\nX = fft(d)/N #fourier spectrum\n\n#Compute power from fourier spectrum\nPow = np.abs(X)**2\nfreq = df*np.arange(N)\n\nmean_Pow_signal = np.mean(Pow[(freq<10)])\nmean_Pow_background = np.mean(Pow[(freq>10)])\n\nprint(\"EOG SNR: \", 10*np.log10((mean_Pow_signal-mean_Pow_background)/mean_Pow_background))", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cb6650f2a3d776bb049331bdf12714bdbda2a6a1
18,481
ipynb
Jupyter Notebook
nlu/colab/component_examples/named_entity_recognition_(NER)/aspect_based_ner_sentiment_restaurants.ipynb
fcivardi/spark-nlp-workshop
aedb1f5d93577c81bc3dd0da5e46e02586941541
[ "Apache-2.0" ]
687
2018-09-07T03:45:39.000Z
2022-03-20T17:11:20.000Z
nlu/colab/component_examples/named_entity_recognition_(NER)/aspect_based_ner_sentiment_restaurants.ipynb
fcivardi/spark-nlp-workshop
aedb1f5d93577c81bc3dd0da5e46e02586941541
[ "Apache-2.0" ]
89
2018-09-18T02:04:42.000Z
2022-02-24T18:22:27.000Z
nlu/colab/component_examples/named_entity_recognition_(NER)/aspect_based_ner_sentiment_restaurants.ipynb
fcivardi/spark-nlp-workshop
aedb1f5d93577c81bc3dd0da5e46e02586941541
[ "Apache-2.0" ]
407
2018-09-07T03:45:44.000Z
2022-03-20T05:12:25.000Z
18,481
18,481
0.661274
[ [ [ "![JohnSnowLabs](https://nlp.johnsnowlabs.com/assets/images/logo.png)\n\n[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/JohnSnowLabs/nlu/blob/master/examples/colab/component_examples/named_entity_recognition_(NER)/aspect_based_ner_sentiment_restaurants.ipynb)\n\n\n\n\nAutomatically detect positive, negative and neutral aspects about restaurants from user reviews. Instead of labelling the entire review as negative or positive, this model helps identify which exact phrases relate to sentiment identified in the review.", "_____no_output_____" ] ], [ [ "!wget https://setup.johnsnowlabs.com/nlu/colab.sh -O - | bash\n \n\nimport nlu", "--2021-05-01 21:59:58-- https://raw.githubusercontent.com/JohnSnowLabs/nlu/master/scripts/colab_setup.sh\nResolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.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: 1671 (1.6K) [text/plain]\nSaving to: ‘STDOUT’\n\n\r- 0%[ ] 0 --.-KB/s Installing NLU 3.0.0 with PySpark 3.0.2 and Spark NLP 3.0.1 for Google Colab ...\n\r- 100%[===================>] 1.63K --.-KB/s in 0.001s \n\n2021-05-01 21:59:58 (1.36 MB/s) - written to stdout [1671/1671]\n\n\u001b[K |████████████████████████████████| 204.8MB 77kB/s \n\u001b[K |████████████████████████████████| 153kB 40.4MB/s \n\u001b[K |████████████████████████████████| 204kB 23.3MB/s \n\u001b[K |████████████████████████████████| 204kB 49.3MB/s \n\u001b[?25h Building wheel for pyspark (setup.py) ... \u001b[?25l\u001b[?25hdone\n" ], [ "import nlu\npipe = nlu.load('en.ner.aspect_sentiment')\ndata = 'We loved our Thai-style main which amazing with lots of flavours very impressive for vegetarian. But the service was below average and the chips were too terrible to finish.'\ndf = pipe.predict([data], output_level='chunk')\ndf", "ner_aspect_based_sentiment download started this may take some time.\nApproximate size to download 21.3 MB\n[OK!]\nglove_6B_300 download started this may take some time.\nApproximate size to download 426.2 MB\n[OK!]\nsentence_detector_dl download started this may take some time.\nApproximate size to download 354.6 KB\n[OK!]\n" ], [ "df = pipe.predict([data], output_level='document')\ndf", "_____no_output_____" ], [ "data = 'We loved our Thai-style main which amazing with lots of flavours very impressive for vegetarian. But the service was below average and the chips were too terrible to finish.'\ndf = pipe.predict([data], output_level='sentence')\ndf", "_____no_output_____" ], [ "nlu.print_all_model_kinds_for_action('pos')", "For language <nl> NLU provides the following Models : \nnlu.load('nl.pos') returns Spark NLP model pos_ud_alpino\nnlu.load('nl.pos.ud_alpino') returns Spark NLP model pos_ud_alpino\nFor language <en> NLU provides the following Models : \nnlu.load('en.pos') returns Spark NLP model pos_anc\nnlu.load('en.pos.anc') returns Spark NLP model pos_anc\nnlu.load('en.pos.ud_ewt') returns Spark NLP model pos_ud_ewt\nFor language <fr> NLU provides the following Models : \nnlu.load('fr.pos') returns Spark NLP model pos_ud_gsd\nnlu.load('fr.pos.ud_gsd') returns Spark NLP model pos_ud_gsd\nFor language <de> NLU provides the following Models : \nnlu.load('de.pos.ud_hdt') returns Spark NLP model pos_ud_hdt\nnlu.load('de.pos') returns Spark NLP model pos_ud_hdt\nFor language <it> NLU provides the following Models : \nnlu.load('it.pos') returns Spark NLP model pos_ud_isdt\nnlu.load('it.pos.ud_isdt') returns Spark NLP model pos_ud_isdt\nFor language <nb> NLU provides the following Models : \nnlu.load('nb.pos.ud_bokmaal') returns Spark NLP model pos_ud_bokmaal\nFor language <nn> NLU provides the following Models : \nnlu.load('nn.pos') returns Spark NLP model pos_ud_nynorsk\nnlu.load('nn.pos.ud_nynorsk') returns Spark NLP model pos_ud_nynorsk\nFor language <pl> NLU provides the following Models : \nnlu.load('pl.pos') returns Spark NLP model pos_ud_lfg\nnlu.load('pl.pos.ud_lfg') returns Spark NLP model pos_ud_lfg\nFor language <pt> NLU provides the following Models : \nnlu.load('pt.pos.ud_bosque') returns Spark NLP model pos_ud_bosque\nnlu.load('pt.pos') returns Spark NLP model pos_ud_bosque\nFor language <ru> NLU provides the following Models : \nnlu.load('ru.pos.ud_gsd') returns Spark NLP model pos_ud_gsd\nnlu.load('ru.pos') returns Spark NLP model pos_ud_gsd\nFor language <es> NLU provides the following Models : \nnlu.load('es.pos') returns Spark NLP model pos_ud_gsd\nnlu.load('es.pos.ud_gsd') returns Spark NLP model pos_ud_gsd\nFor language <ar> NLU provides the following Models : \nnlu.load('ar.pos') returns Spark NLP model pos_ud_padt\nFor language <hy> NLU provides the following Models : \nnlu.load('hy.pos') returns Spark NLP model pos_ud_armtdp\nFor language <eu> NLU provides the following Models : \nnlu.load('eu.pos') returns Spark NLP model pos_ud_bdt\nFor language <bn> NLU provides the following Models : \nnlu.load('bn.pos') returns Spark NLP model pos_msri\nFor language <br> NLU provides the following Models : \nnlu.load('br.pos') returns Spark NLP model pos_ud_keb\nFor language <bg> NLU provides the following Models : \nnlu.load('bg.pos') returns Spark NLP model pos_ud_btb\nnlu.load('bg.pos.ud_btb') returns Spark NLP model pos_ud_btb\nFor language <ca> NLU provides the following Models : \nnlu.load('ca.pos') returns Spark NLP model pos_ud_ancora\nFor language <cs> NLU provides the following Models : \nnlu.load('cs.pos') returns Spark NLP model pos_ud_pdt\nnlu.load('cs.pos.ud_pdt') returns Spark NLP model pos_ud_pdt\nFor language <fi> NLU provides the following Models : \nnlu.load('fi.pos.ud_tdt') returns Spark NLP model pos_ud_tdt\nnlu.load('fi.pos') returns Spark NLP model pos_ud_tdt\nFor language <gl> NLU provides the following Models : \nnlu.load('gl.pos') returns Spark NLP model pos_ud_treegal\nFor language <el> NLU provides the following Models : \nnlu.load('el.pos') returns Spark NLP model pos_ud_gdt\nnlu.load('el.pos.ud_gdt') returns Spark NLP model pos_ud_gdt\nFor language <he> NLU provides the following Models : \nnlu.load('he.pos') returns Spark NLP model pos_ud_htb\nnlu.load('he.pos.ud_htb') returns Spark NLP model pos_ud_htb\nFor language <hi> NLU provides the following Models : \nnlu.load('hi.pos') returns Spark NLP model pos_ud_hdtb\nFor language <hu> NLU provides the following Models : \nnlu.load('hu.pos') returns Spark NLP model pos_ud_szeged\nnlu.load('hu.pos.ud_szeged') returns Spark NLP model pos_ud_szeged\nFor language <id> NLU provides the following Models : \nnlu.load('id.pos') returns Spark NLP model pos_ud_gsd\nFor language <ga> NLU provides the following Models : \nnlu.load('ga.pos') returns Spark NLP model pos_ud_idt\nFor language <da> NLU provides the following Models : \nnlu.load('da.pos') returns Spark NLP model pos_ud_ddt\nFor language <ja> NLU provides the following Models : \nnlu.load('ja.pos') returns Spark NLP model pos_ud_gsd\nnlu.load('ja.pos.ud_gsd') returns Spark NLP model pos_ud_gsd\nFor language <la> NLU provides the following Models : \nnlu.load('la.pos') returns Spark NLP model pos_ud_llct\nFor language <lv> NLU provides the following Models : \nnlu.load('lv.pos') returns Spark NLP model pos_ud_lvtb\nFor language <mr> NLU provides the following Models : \nnlu.load('mr.pos') returns Spark NLP model pos_ud_ufal\nFor language <fa> NLU provides the following Models : \nnlu.load('fa.pos') returns Spark NLP model pos_ud_perdt\nFor language <ro> NLU provides the following Models : \nnlu.load('ro.pos') returns Spark NLP model pos_ud_rrt\nnlu.load('ro.pos.ud_rrt') returns Spark NLP model pos_ud_rrt\nFor language <sk> NLU provides the following Models : \nnlu.load('sk.pos') returns Spark NLP model pos_ud_snk\nnlu.load('sk.pos.ud_snk') returns Spark NLP model pos_ud_snk\nFor language <sl> NLU provides the following Models : \nnlu.load('sl.pos') returns Spark NLP model pos_ud_ssj\nFor language <sv> NLU provides the following Models : \nnlu.load('sv.pos') returns Spark NLP model pos_ud_tal\nnlu.load('sv.pos.ud_tal') returns Spark NLP model pos_ud_tal\nFor language <th> NLU provides the following Models : \nnlu.load('th.pos') returns Spark NLP model pos_lst20\nFor language <tr> NLU provides the following Models : \nnlu.load('tr.pos') returns Spark NLP model pos_ud_imst\nnlu.load('tr.pos.ud_imst') returns Spark NLP model pos_ud_imst\nFor language <uk> NLU provides the following Models : \nnlu.load('uk.pos') returns Spark NLP model pos_ud_iu\nnlu.load('uk.pos.ud_iu') returns Spark NLP model pos_ud_iu\nFor language <yo> NLU provides the following Models : \nnlu.load('yo.pos') returns Spark NLP model pos_ud_ytb\nFor language <zh> NLU provides the following Models : \nnlu.load('zh.pos') returns Spark NLP model pos_ud_gsd\nnlu.load('zh.pos.ud_gsd') returns Spark NLP model pos_ud_gsd\nnlu.load('zh.pos.ctb9') returns Spark NLP model pos_ctb9\nnlu.load('zh.pos.ud_gsd_trad') returns Spark NLP model pos_ud_gsd_trad\nFor language <et> NLU provides the following Models : \nnlu.load('et.pos') returns Spark NLP model pos_ud_edt\nFor language <ur> NLU provides the following Models : \nnlu.load('ur.pos') returns Spark NLP model pos_ud_udtb\nnlu.load('ur.pos.ud_udtb') returns Spark NLP model pos_ud_udtb\nFor language <ko> NLU provides the following Models : \nnlu.load('ko.pos') returns Spark NLP model pos_ud_kaist\nnlu.load('ko.pos.ud_kaist') returns Spark NLP model pos_ud_kaist\nFor language <bh> NLU provides the following Models : \nnlu.load('bh.pos') returns Spark NLP model pos_ud_bhtb\nFor language <am> NLU provides the following Models : \nnlu.load('am.pos') returns Spark NLP model pos_ud_att\n" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
cb665fa99993c25dfaad659a2e234a58ef2b67d3
6,772
ipynb
Jupyter Notebook
02-image_detection/04-clickable/ipynb/h5tocheckpoint.ipynb
AppTestBot/AppTestBot
035e93e662753e50d7dcc38d6fd362933186983b
[ "Apache-2.0" ]
null
null
null
02-image_detection/04-clickable/ipynb/h5tocheckpoint.ipynb
AppTestBot/AppTestBot
035e93e662753e50d7dcc38d6fd362933186983b
[ "Apache-2.0" ]
null
null
null
02-image_detection/04-clickable/ipynb/h5tocheckpoint.ipynb
AppTestBot/AppTestBot
035e93e662753e50d7dcc38d6fd362933186983b
[ "Apache-2.0" ]
null
null
null
37.208791
1,347
0.620939
[ [ [ "import numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nimport pandas as pd\nimport seaborn as sns\nfrom pylab import rcParams\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nfrom pandas.plotting import register_matplotlib_converters\nfrom sklearn.model_selection import train_test_split\nimport urllib\nimport os\nimport csv\nimport cv2\nimport time\nfrom PIL import Image\nfrom keras_retinanet import models\nfrom keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image\nfrom keras_retinanet.utils.visualization import draw_box, draw_caption\nfrom keras_retinanet.utils.colors import label_color\nPATH = '/home/kimsoohyun/00-Research/02-Graph/02-image_detection/04-clickable/dataset/03-models/retinanet/resnet50_csv_49.h5'\nmodel = models.load_model(PATH)", "Using TensorFlow backend.\n" ], [ "import numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras", "_____no_output_____" ], [ "model.save('my_model')", "_____no_output_____" ], [ "reconstructed_model = models.load_model(\"my_model\")\n", "_____no_output_____" ], [ "import tensorflow as tf\nimport shutil \nimport os", "_____no_output_____" ], [ "# Helper For getting the model Size\nimport os\nfrom tensorflow.python import ops\ndef get_size(model_dir, model_file='saved_model.pb'):\n model_file_path = os.path.join(model_dir, model_file)\n print(model_file_path, '')\n pb_size = os.path.getsize(model_file_path)\n variables_size = 0\n if os.path.exists(\n os.path.join(model_dir,'variables/variables.data-00000-of-00001')):\n variables_size = os.path.getsize(os.path.join(\n model_dir,'variables/variables.data-00000-of-00001'))\n variables_size += os.path.getsize(os.path.join(\n model_dir,'variables/variables.index'))\n print('Model size: {} KB'.format(round(pb_size/(1024.0),3)))\n print('Variables size: {} KB'.format(round( variables_size/(1024.0),3)))\n print('Total Size: {} KB'.format(round((pb_size + variables_size)/(1024.0),3)))", "_____no_output_____" ], [ "# To Freeze the Saved Model\n# We need to freeze the model to do further optimisation on it\n\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python.tools import freeze_graph\nfrom tensorflow.python import ops\nfrom tensorflow.tools.graph_transforms import TransformGraph\n\ndef freeze_model(saved_model_dir, output_node_names, output_filename):\n output_graph_filename = os.path.join(saved_model_dir, output_filename)\n initializer_nodes = ''\n freeze_graph.freeze_graph(\n input_saved_model_dir=saved_model_dir,\n output_graph=output_graph_filename,\n saved_model_tags = tag_constants.SERVING,\n output_node_names=output_node_names,\n initializer_nodes=initializer_nodes,\n input_graph=None,\n input_saver=False,\n input_binary=False,\n input_checkpoint=None,\n restore_op_name=None,\n filename_tensor_name=None,\n clear_devices=True,\n input_meta_graph=False,\n )\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
cb6660de1b611abb41e970a4db0e1f3ff3939cca
24,463
ipynb
Jupyter Notebook
demo_iris.ipynb
leitte/NoLiES
597aaef8a49f873aa44c4dd03e4c2f6b393f665b
[ "MIT" ]
1
2021-08-23T21:21:04.000Z
2021-08-23T21:21:04.000Z
demo_iris.ipynb
leitte/NoLiES
597aaef8a49f873aa44c4dd03e4c2f6b393f665b
[ "MIT" ]
null
null
null
demo_iris.ipynb
leitte/NoLiES
597aaef8a49f873aa44c4dd03e4c2f6b393f665b
[ "MIT" ]
1
2021-10-21T12:43:38.000Z
2021-10-21T12:43:38.000Z
34.309958
250
0.533745
[ [ [ "from os.path import join, dirname\nfrom os import listdir\n\nimport numpy as np\nimport pandas as pd\n\n# GUI library\nimport panel as pn\nimport panel.widgets as pnw\n\n# Chart libraries\nfrom bokeh.plotting import figure\nfrom bokeh.models import ColumnDataSource, Legend\nfrom bokeh.palettes import Spectral5, Set2\nfrom bokeh.events import SelectionGeometry\n\n# Dimensionality reduction\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import MDS\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\n\n#\nfrom shapely.geometry import MultiPoint, MultiLineString, Polygon, MultiPolygon, LineString\nfrom shapely.ops import unary_union\nfrom shapely.ops import triangulate\n\n# local scripts\nfrom Embedding.Rangeset import Rangeset\n\npn.extension()", "_____no_output_____" ] ], [ [ "# Parameters", "_____no_output_____" ] ], [ [ "l = str(len(pd.read_csv('data/BLI_30102020171001105.csv')))\ndataset_name = l\n\nbins = 5\n\nshow_labels = True\nlabels_column = 'index'\n\noverview_height = 700\n\nsmall_multiples_ncols = 3\nhistogram_width = 250\nshow_numpy_histogram = True\n\nrangeset_threshold = 1", "_____no_output_____" ] ], [ [ "# Load data", "_____no_output_____" ] ], [ [ "from bokeh.sampledata.iris import flowers\n\ndf = flowers", "_____no_output_____" ], [ "label_encoder = LabelEncoder().fit(df.species)\ndf['class'] = label_encoder.transform(df.species)", "_____no_output_____" ] ], [ [ "# Preprocessing", "_____no_output_____" ] ], [ [ "# attributes to be included in the overlays\nselected_var = list(df.columns[:-2]) + ['class']\n#selected_var = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'projection quality'] # custom selection\n\n# maximal slider range and step size\n# {'variable_name': (min,max,stepsize)}\ncustom_range = {'projection quality': (0,1,0.01)}\n\n# custom min/max settings for sliders\n# {'variable_name': (min,max)}\ndefault_range = {'projection quality': (0.4,0.9)}", "_____no_output_____" ], [ "# which variables to use for the embedding\nselected_var_embd = selected_var[:-1]\n\n# set up embedding\n#embedding = PCA(n_components=2)\nembedding = MDS(n_components=2, random_state=42)\nscaler = StandardScaler()\nX_scaled = scaler.fit_transform(df[selected_var_embd])\n\n# some projections change the original data, so we make a copy\n# this can cost a lot of memory for large data\nX = X_scaled.copy()\npp = embedding.fit_transform(X)", "_____no_output_____" ], [ "x_range = pp[:,0].max() - pp[:,0].min()\ny_range = pp[:,1].max() - pp[:,1].min()\n\n# keep the aspect ration of the projected data\noverview_width = int(overview_height * x_range / y_range)\nhistogram_height = int(histogram_width * y_range / x_range)", "_____no_output_____" ], [ "from Embedding.ProjectionQuality import projection_quality\n\ndf['projection quality'] = projection_quality(X_scaled, pp)\nselected_var += ['projection quality']", "_____no_output_____" ], [ "rangeset = Rangeset(pp, df)\nrangeset.threshold = rangeset_threshold\nrangeset.size_inside = 8\nrangeset.size_outside = 12", "_____no_output_____" ] ], [ [ "# GUI\n\n## Vis elements\n\n**overview chart** shows a large version of the embedding", "_____no_output_____" ] ], [ [ "TOOLS = \"pan,wheel_zoom,box_zoom,box_select,lasso_select,help,reset,save\"\noverview = figure(tools=TOOLS, width=overview_width, height=overview_height, active_drag=\"lasso_select\")\n\noverview.scatter(x=pp[:,0], y=pp[:,1], color=\"#333333\", muted_alpha=0,\n size=7, level='underlay', name='points',\n line_color=None, legend_label='data')\n\nif show_labels:\n labels = df.index.astype(str) if labels_column == 'index' else df[labels_column].astype(str)\n overview.text(x=pp[:,0], y=pp[:,1], text=labels, legend_label='labels',\n font_size=\"10pt\", x_offset=5, y_offset=5, muted_alpha=0,\n text_baseline=\"middle\", text_align=\"left\", color='#666666', level='glyph')\n\nsource_selection = ColumnDataSource({'x': [], 'y': []})\noverview.patch(source=source_selection, x='x', y='y', fill_color=None, line_width=4, line_color='#aaaaaa',\n level='annotation')\n\noverview.legend.location = 'bottom_right'\noverview.legend.label_height=1\noverview.legend.click_policy='mute'\noverview.legend.visible = True\n\noverview.outline_line_color = None\n\noverview.xgrid.visible = False\noverview.ygrid.visible = False\noverview.xaxis.visible = False\noverview.yaxis.visible = False\noverview.toolbar.logo = None", "_____no_output_____" ], [ "# Check the embedding with the code below\n\n# pn.Row(overview)", "_____no_output_____" ] ], [ [ "**small multiples** charts are created upon request", "_____no_output_____" ] ], [ [ "def _make_chart( var, df_polys, df_scatter, bounds, cnt_in, cnt_out ):\n global df\n\n xvals = df[var].unique()\n is_categorical = False\n if len(xvals) < 10:\n is_categorical = True\n xvals = sorted(xvals.astype(str))\n \n global histogram_width\n p = figure(width=histogram_width, height=histogram_height, title=var)\n df_scatter['size'] = df_scatter['size'] * histogram_height / overview_height\n \n p.multi_polygons(source=df_polys, xs='xs', ys='ys', color='color', fill_alpha=0.5, level='image', line_color=None)\n p.scatter(source=df_scatter, x='x', y='y', color='color', size='size', level='overlay')\n \n global source_selection\n p.patch(source=source_selection, x='x', y='y', fill_color=None, level='annotation', line_width=2, line_color='#333333')\n \n p.xgrid.visible = False\n p.ygrid.visible = False\n p.xaxis.visible = False\n p.yaxis.visible = False\n p.toolbar.logo = None\n p.toolbar_location = None\n p.border_fill_color = '#f0f0f0'\n \n p_histo = figure(height=100, width=histogram_width, name='histo')\n if is_categorical:\n p_histo = figure(height=100, width=histogram_width, name='histo', x_range=xvals)\n p_histo.vbar(x=xvals, top=cnt_in, bottom=0, width=0.9, line_color='white', color=rangeset.colormap)\n p_histo.vbar(x=xvals, top=0, bottom=np.array(cnt_out)*-1, width=0.9, line_color='white', color=rangeset.colormap)\n else:\n p_histo.quad(bottom=[0]*len(cnt_in), top=cnt_in, left=bounds[:-1], right=bounds[1:], line_color='white', color=rangeset.colormap)\n p_histo.quad(bottom=np.array(cnt_out)*(-1), top=[0]*len(cnt_out), left=bounds[:-1], right=bounds[1:], line_color='white', color=rangeset.colormap)\n\n df_select = df[df[var] < bounds[0]]\n p_histo.square(df_select[var], -.5, color=rangeset.colormap[0])\n df_select = df[df[var] > bounds[-1]]\n p_histo.square(df_select[var], -.5, color=rangeset.colormap[-1])\n \n p_histo.toolbar.logo = None\n p_histo.toolbar_location = None\n p_histo.xgrid.visible = False\n p_histo.xaxis.minor_tick_line_color = None\n p_histo.yaxis.minor_tick_line_color = None\n p_histo.outline_line_color = None\n p_histo.border_fill_color = '#f0f0f0'\n \n global show_numpy_histogram\n if show_numpy_histogram:\n if is_categorical:\n frequencies, edges = np.histogram(df[var], bins=len(xvals))\n p_histo.vbar(x=xvals, bottom=0, width=.5, top=frequencies*-1,\n line_color='white', color='gray', line_alpha=.5, fill_alpha=0.5)\n else:\n frequencies, edges = np.histogram(df[var])\n p_histo.quad(bottom=[0]*len(frequencies), top=frequencies*-1, left=edges[:-1], right=edges[1:], \n line_color='white', color='gray', line_alpha=.5, fill_alpha=0.5)\n \n return (p, p_histo)", "_____no_output_____" ] ], [ [ "## Create input widget (buttons, sliders, etc) and layout", "_____no_output_____" ] ], [ [ "class MyCheckbox(pnw.Checkbox):\n variable = \"\"\n \n def __init__(self, variable=\"\", slider=None, **kwds):\n super().__init__(**kwds)\n \n self.variable = variable\n self.slider = slider\n \ndef init_slider_values(var):\n vmin = df[var].min()\n vmax = df[var].max()\n step = 0\n \n if var in custom_range:\n vmin,vmax,step = custom_range[var]\n value = (vmin,vmax)\n \n if var in default_range:\n value = default_range[var]\n \n return (vmin, vmax, step, value)", "_____no_output_____" ], [ "ranges_embd = pn.Column()\nranges_aux = pn.Column()\n\nsliders = {}\n\ndef create_slider(var):\n vmin, vmax, step, value = init_slider_values(var) \n slider = pnw.RangeSlider(name=var, start=vmin, end=vmax, step=step, value=value) \n\n checkbox = MyCheckbox(name='', variable=var, value=False, width=20, slider=slider)\n return pn.Row(checkbox,slider)\n \nfor var in selected_var:\n s = create_slider(var)\n sliders[var] = s\n\n if var in selected_var_embd:\n ranges_embd.append(s)\n else:\n ranges_aux.append(s)\n \nselected_var = []\n\nfor r in ranges_embd:\n selected_var.append(r[1].name)\nfor r in ranges_aux:\n selected_var.append(r[1].name)", "_____no_output_____" ], [ "gui_colormap = pn.Row(pn.pane.Str(background=rangeset.colormap[0], height=30, width=20), \"very low\",\n pn.pane.Str(background=rangeset.colormap[1], height=30, width=20), \"low\",\n pn.pane.Str(background=rangeset.colormap[2], height=30, width=20), \"medium\",\n pn.pane.Str(background=rangeset.colormap[3], height=30, width=20), \"high\",\n pn.pane.Str(background=rangeset.colormap[4], height=30, width=20), \"very high\", sizing_mode='stretch_width')\n\nselectColoring = pn.widgets.Select(name='', options=['None']+selected_var)\n\n\n# set up the GUI\nlayout = pn.Row(pn.Column(\n pn.Row(pn.pane.Markdown('''# NoLiES: The non-linear embedding surveyor\\n\nNoLiES augments the projected data with additional information. The following interactions are supported:\\n\n* **Attribute-based coloring** Chose an attribute from the drop-down menu below the embedding to display contours for multiple value ranges.\n* **Selective muting**: Click on the legend to mute/hide parts of the chart. Press _labels_ to hide the labels.\n* **Contour control** Change the slider range to change the contours.\n* **Histograms** Select the check-box next to the slider to view the attribute's histogram.\n* **Selection** Use the selection tool to outline a set of points and share this outline across plots.''', sizing_mode='stretch_width'), \n margin=(0, 25,0,25)),\n pn.Row(\n pn.Column(pn.pane.Markdown('''# Attributes\\nEnable histograms with the checkboxes.'''), \n '## Embedding',\n ranges_embd,\n #pn.layout.Divider(),\n '## Auxiliary',\n ranges_aux, margin=(0, 25, 0, 0)),\n pn.Column(pn.pane.Markdown('''# Embedding - '''+type(embedding).__name__+'''&nbsp;&nbsp; Dataset - '''+dataset_name, sizing_mode='stretch_width'), \n overview, \n pn.Row(selectColoring, gui_colormap)\n ), \n margin=(0,25,25,25)\n ), \n #pn.Row(sizing_mode='stretch_height'), \n pn.Row(pn.pane.Markdown('''Data source: Fisher,R.A. \"The use of multiple measurements in taxonomic problems\" Annual Eugenics, 7, Part II, 179-188 (1936); also in \"Contributions to Mathematical Statistics\" (John Wiley, NY, 1950). ''',\n width=800), sizing_mode='stretch_width', margin=(0,25,0,25))),\n pn.GridBox(ncols=small_multiples_ncols, sizing_mode='stretch_both', margin=(220,25,0,0)),\n background='#efefef'\n )", "_____no_output_____" ], [ "# Check the GUI with the following code - this version is not interactive yet\n\nlayout", "_____no_output_____" ] ], [ [ "## Callbacks\n\nCallbacks for **slider interactions**", "_____no_output_____" ] ], [ [ "visible = [False]*len(selected_var)\nmapping = {v: k for k, v in dict(enumerate(selected_var)).items()}\n\n \ndef onSliderChanged(event):\n '''Actions upon attribute slider change.\n \n Attributes\n ----------\n event: bokeh.Events.Event\n information about the event that triggered the callback\n '''\n\n var = event.obj.name\n v_range = event.obj.value\n \n # if changed variable is currently displayed\n if var == layout[0][1][1][2][0].value:\n setColoring(var, v_range)\n \n # find the matching chart and update it\n for col in layout[1]:\n if col.name == var:\n df_polys, df_scatter, bounds, cnt_in, cnt_out = rangeset.compute_contours(var, v_range, bins=20 if col.name == 'groups' else 5)\n p,histo = _make_chart(var, df_polys, df_scatter, bounds, cnt_in, cnt_out)\n col[0].object = p\n col[1].object = histo\n\ndef onSliderChanged_released(event):\n '''Actions upon attribute slider change.\n \n Attributes\n ----------\n event: bokeh.Events.Event\n information about the event that triggered the callback\n '''\n\n var = event.obj.name\n v_range = event.obj.value\n \n print('\\''+var+'\\': ('+str(v_range[0])+','+str(v_range[1])+')')\n\n\ndef onAttributeSelected(event):\n '''Actions upon attribute checkbox change.\n \n Attributes\n ----------\n event: bokeh.Events.Event\n information about the event that triggered the callback\n '''\n var = event.obj.variable\n i = mapping[var]\n \n if event.obj.value == True:\n v_range = event.obj.slider.value\n \n df_polys, df_scatter, bounds, cnt_in, cnt_out = rangeset.compute_contours(var, v_range)\n p,p_histo = _make_chart(var, df_polys, df_scatter, bounds, cnt_in, cnt_out)\n pos_insert = sum(visible[:i])\n layout[1].insert(pos_insert, pn.Column(p,pn.panel(p_histo), name=var, margin=5))\n else:\n pos_remove = sum(visible[:i])\n layout[1].pop(pos_remove)\n \n visible[i] = event.obj.value \n\n# link widgets to their callbacks\nfor var in sliders.keys():\n sliders[var][0].param.watch(onAttributeSelected, 'value')\n sliders[var][1].param.watch(onSliderChanged, 'value')\n sliders[var][1].param.watch(onSliderChanged_released, 'value_throttled')", "_____no_output_____" ] ], [ [ "Callbacks **rangeset selection** in overview plot", "_____no_output_____" ] ], [ [ "def clearColoring():\n '''Remove rangeset augmentation from the embedding.'''\n \n global overview\n overview.legend.visible = False\n \n for r in overview.renderers:\n if r.name is not None and ('poly' in r.name or 'scatter' in r.name):\n r.visible = False\n r.muted = True\n \ndef setColoring(var, v_range=None):\n '''Compute and render the rangeset for a selected variable.\n \n Attributes\n ----------\n var: str\n the selected variable\n v_range: tuple (min,max)\n the user define value range for the rangeset\n '''\n \n global overview \n overview.legend.visible = True\n \n df_polys, df_scatter, bounds, cnt,cnt = rangeset.compute_contours(var, val_range=v_range, bins=bins)\n for r in overview.renderers:\n if r.name is not None and ('poly' in r.name or 'scatter' in r.name):\n r.visible = False\n r.muted = True\n \n if len(df_polys) > 0:\n for k in list(rangeset.labels.keys())[::-1]:\n g = df_polys[df_polys.color == k]\n r = overview.select('poly '+k)\n if len(r) > 0:\n r[0].visible = True\n r[0].muted = False\n r[0].data_source.data = dict(ColumnDataSource(g).data)\n else:\n overview.multi_polygons(source = g, xs='xs', ys='ys', name='poly '+k,\n color='color', alpha=.5, legend_label=rangeset.color2label(k),\n line_color=None, muted_color='gray', muted_alpha=.1) \n \n g = df_scatter[df_scatter.color == k]\n r = overview.select('scatter '+k)\n if len(r) > 0:\n r[0].visible = True\n r[0].muted = False\n r[0].data_source.data = dict(ColumnDataSource(g).data)\n else:\n overview.circle(source = g, x='x', y='y', size='size', name='scatter '+k,\n color='color', alpha=1, legend_label=rangeset.color2label(k),\n muted_color='gray', muted_alpha=0) \n\ndef onChangeColoring(event):\n '''Actions upon change of the rangeset attribute.\n \n Attributes\n ----------\n event: bokeh.Events.Event\n information about the event that triggered the callback\n '''\n var = event.obj.value\n \n if var == 'None':\n clearColoring()\n else:\n v_range = sliders[var][1].value\n setColoring(var, v_range)\n \nselectColoring.param.watch( onChangeColoring, 'value' )", "_____no_output_____" ] ], [ [ "User **selection of data points** in the overview chart.", "_____no_output_____" ] ], [ [ "def onSelectionChanged(event):\n if event.final:\n sel_pp = pp[list(overview.select('points').data_source.selected.indices)]\n if len(sel_pp) == 0:\n source_selection.data = dict({'x': [], 'y': []})\n else:\n points = MultiPoint(sel_pp)\n poly = unary_union([polygon for polygon in triangulate(points) if rangeset._max_edge(polygon) < 5]).boundary.parallel_offset(-0.05).coords.xy\n source_selection.data = dict({'x': poly[0].tolist(), 'y': poly[1].tolist()})\n\noverview.on_event(SelectionGeometry, onSelectionChanged)", "_____no_output_____" ], [ "layout.servable('NoLies')", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cb66684898934bfa15dbf070345f43615841bac4
44,306
ipynb
Jupyter Notebook
notebooks/Example-03-Authors_with_Similar_Papers.ipynb
smartdatalake/simjoin
340b312f3042d7cb3a740c7b092964c976df84d6
[ "Apache-2.0" ]
3
2020-01-28T13:42:50.000Z
2021-04-24T00:50:26.000Z
notebooks/Example-03-Authors_with_Similar_Papers.ipynb
smartdatalake/simjoin
340b312f3042d7cb3a740c7b092964c976df84d6
[ "Apache-2.0" ]
5
2021-07-02T18:39:27.000Z
2022-02-16T01:14:52.000Z
notebooks/Example-03-Authors_with_Similar_Papers.ipynb
smartdatalake/simjoin
340b312f3042d7cb3a740c7b092964c976df84d6
[ "Apache-2.0" ]
2
2020-09-14T13:29:59.000Z
2021-04-24T00:50:29.000Z
36.109209
173
0.391798
[ [ [ "## Imports", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport json", "_____no_output_____" ] ], [ [ "## Settings to enable real-time output from a shell command", "_____no_output_____" ] ], [ [ "from subprocess import Popen, PIPE, STDOUT\nfrom IPython.core.magic import register_line_magic\n\n@register_line_magic\ndef runrealcmd(command):\n process = Popen(command, stdout=PIPE, shell=True, stderr=STDOUT, bufsize=1, close_fds=True)\n for line in iter(process.stdout.readline, b''):\n print(line.rstrip().decode('utf-8'))\n process.stdout.close()\n process.wait()", "_____no_output_____" ] ], [ [ "# 1. Self Join", "_____no_output_____" ], [ "## 1.a Preview the input file", "_____no_output_____" ] ], [ [ "df = pd.read_csv('../data/dblp_authors_papers_test.csv', sep=';', header=None, names=['Authors','Paper_ID','Title'])\ndf.sort_values('Authors').head(100)", "_____no_output_____" ] ], [ [ "## 1.b Load and optionally edit the config file", "_____no_output_____" ] ], [ [ "config_file_example = '../config.json.example'\nconfig_file = '../config.json'\ninput_file = '../data/dblp_authors_papers_test.csv'\noutput_file = '../data/output/dblp_authors_papers_selfjoin_out.csv'\nlog_file = '../data/output/log.txt'", "_____no_output_____" ], [ "params = json.load(open(config_file_example))\nparams", "_____no_output_____" ], [ "params['mode'] = 'fuzzy'\nparams['join_type'] = 'threshold'\nparams['threshold'] = '0.33'\ndel(params['query_file'])\nparams['input_file'] = input_file\nparams['output_file'] = output_file\nparams['log_file'] = log_file\nparams['set_column'] = '1'\nparams['elements_column'] = '2'\nparams['tokens_column'] = '3'", "_____no_output_____" ], [ "json.dump(params, open(config_file, 'w'), indent=4)", "_____no_output_____" ] ], [ [ "## 1.c Execute the join operation", "_____no_output_____" ] ], [ [ "%runrealcmd java -jar ../target/simjoin-0.0.1-SNAPSHOT-jar-with-dependencies.jar $config_file", "Finished reading file. Lines read: 71. Lines skipped due to errors: 0. Num of sets: 45. Elements per set: 1.5777777777777777. Tokens per Element: 6.23943661971831\nRead time: 0.008667764 sec.\nTransform time: 0.010144087 sec.\nCollection size: 45\nIndexing time: 0.007271427 sec.\nJoin time: 0.212302917 sec. 0m 0s\nNumber of matches: 87\n" ] ], [ [ "## 1.c Load the results", "_____no_output_____" ] ], [ [ "out1 = pd.read_csv(output_file, header=None, names=['Author_ID_1', 'Author_ID_2', 'Similarity'])\nout1.sort_values(['Similarity'], ascending=False).head(150)", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb6676e576d09ecab6120545dabe1f3254f67201
10,596
ipynb
Jupyter Notebook
Complete Code/attempt10/attempt5_final.ipynb
architsangal/AskReddit-Troll-Question-Detection-Challenge
191f05c5819a14d44491036350f68b9f5e66831e
[ "MIT" ]
null
null
null
Complete Code/attempt10/attempt5_final.ipynb
architsangal/AskReddit-Troll-Question-Detection-Challenge
191f05c5819a14d44491036350f68b9f5e66831e
[ "MIT" ]
null
null
null
Complete Code/attempt10/attempt5_final.ipynb
architsangal/AskReddit-Troll-Question-Detection-Challenge
191f05c5819a14d44491036350f68b9f5e66831e
[ "MIT" ]
null
null
null
22.984816
105
0.444319
[ [ [ "# AskReddit Troll Question Detection Challenge", "_____no_output_____" ], [ "## Imports", "_____no_output_____" ] ], [ [ "import numpy as np \nimport pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport re", "_____no_output_____" ], [ "train_df = pd.read_csv(\"train.csv\")\ntest_df = pd.read_csv(\"test.csv\")", "_____no_output_____" ], [ "sentences1 = train_df['question_text'] # .values.astype('U')\nsentences2 = test_df['question_text'] # .values.astype('U')\nsentences1 = sentences1.tolist()\nsentences2 = sentences2.tolist()\n# print(len(sentences1))\n# print(len(sentences2))\n# print(sentences1[0:10])\n# print(sentences2[0:10])\nsentences = []\nsentences = sentences1 + sentences2\nprint(len(sentences))", "1306122\n" ], [ "N = 1306122\nsentences = sentences[:N]", "_____no_output_____" ] ], [ [ "## Trying Methods", "_____no_output_____" ], [ "### Bag Of Words", "_____no_output_____" ] ], [ [ "cv = CountVectorizer(ngram_range=(1,3))\ncv.fit(sentences)", "_____no_output_____" ], [ "train_X1 = cv.transform(sentences1)\ntest_X1 = cv.transform(sentences2)\ntrain_X1 = train_X1.astype(float)\ntest_X1 = test_X1.astype(float)", "_____no_output_____" ], [ "Y1 = train_df['target'].to_numpy().astype(np.float64)\nY1 = Y1[:N]", "_____no_output_____" ] ], [ [ "### TF IDF", "_____no_output_____" ] ], [ [ "cv = TfidfVectorizer(ngram_range=(1,3))\ncv.fit(sentences)", "_____no_output_____" ], [ "train_X2 = cv.transform(sentences1)\ntest_X2 = cv.transform(sentences2)\ntrain_X2 = train_X1.astype(float)\ntest_X2 = test_X1.astype(float)", "_____no_output_____" ], [ "Y2 = Y1", "_____no_output_____" ] ], [ [ "## Model generation", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LogisticRegression \nfrom sklearn.metrics import accuracy_score, f1_score, roc_auc_score", "_____no_output_____" ] ], [ [ "### For data genrated by \"Bag of words\" method ", "_____no_output_____" ] ], [ [ "lreg1 = LogisticRegression(solver='liblinear')\nlreg1.fit(train_X1,Y1)", "_____no_output_____" ] ], [ [ "### For data generated by \"TD IDF\" method", "_____no_output_____" ] ], [ [ "lreg2 = LogisticRegression(solver='liblinear')\nlreg2.fit(train_X2,Y2)\n", "_____no_output_____" ] ], [ [ "### Predict for X1, Y1", "_____no_output_____" ] ], [ [ "test_yhat1 = lreg1.predict_proba(test_X1)\nthreshold = 0.20139999999999986\ntest_output1 = (test_yhat1[:,1] > threshold).astype(int)", "_____no_output_____" ] ], [ [ "### Predict for X2, Y2", "_____no_output_____" ] ], [ [ "test_yhat2 = lreg2.predict_proba(test_X2)\nthreshold = 0.20049999999999996\ntest_output2 = (test_yhat2[:,1] > threshold).astype(int)", "_____no_output_____" ] ], [ [ "## Reshaping To Store Data", "_____no_output_____" ] ], [ [ "test_output1 = test_output1.reshape(-1,1)\ntest_output1 = test_output1.astype(int)", "_____no_output_____" ], [ "test_output2 = test_output2.reshape(-1,1)\ntest_output2 = test_output2.astype(int)", "_____no_output_____" ] ], [ [ "### Making a submission file", "_____no_output_____" ] ], [ [ "y_pred_df1 = pd.DataFrame(data=test_output1[:,0], columns = [\"target\"])\nsubmission_df1 = pd.concat([test_df[\"qid\"], y_pred_df1[\"target\"]], axis=1, join='inner')\nsubmission_df1.to_csv(\"submission1.csv\", index = False)\nprint(submission_df1.shape)", "(653061, 2)\n" ], [ "y_pred_df2 = pd.DataFrame(data=test_output2[:,0], columns = [\"target\"])\nsubmission_df2 = pd.concat([test_df[\"qid\"], y_pred_df2[\"target\"]], axis=1, join='inner')\nsubmission_df2.to_csv(\"submission2.csv\", index = False)\nprint(submission_df2.shape)", "(653061, 2)\n" ], [ "print(train_X1.shape)", "_____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", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cb668941de5789c52a996180bdd3a4adfc1bcd0f
2,856
ipynb
Jupyter Notebook
Gamma-Correction/GammaCorrection/NightVideos_improving.ipynb
akshit7165/Width-Detection-Lane
cce95f168300ea516416bb8b96b1aa136d36d86d
[ "MIT" ]
null
null
null
Gamma-Correction/GammaCorrection/NightVideos_improving.ipynb
akshit7165/Width-Detection-Lane
cce95f168300ea516416bb8b96b1aa136d36d86d
[ "MIT" ]
null
null
null
Gamma-Correction/GammaCorrection/NightVideos_improving.ipynb
akshit7165/Width-Detection-Lane
cce95f168300ea516416bb8b96b1aa136d36d86d
[ "MIT" ]
null
null
null
23.409836
83
0.477941
[ [ [ "import cv2\nimport numpy as np", "_____no_output_____" ], [ "cap = cv2.VideoCapture(\"small_nightRoad.mp4\")\nvidsize = (640,480,3)", "_____no_output_____" ], [ "#Gamma Correction Function\ndef gamma_correction(RGBimage, correct_param = 0.35,equalizeHist = False):\n red = RGBimage[:,:,2]\n green = RGBimage[:,:,1]\n blue = RGBimage[:,:,0]\n \n red = red/255.0\n red = cv2.pow(red, correct_param)\n red = np.uint8(red*255)\n if equalizeHist:\n red = cv2.equalizeHist(red)\n \n green = green/255.0\n green = cv2.pow(green, correct_param)\n green = np.uint8(green*255)\n if equalizeHist:\n green = cv2.equalizeHist(green)\n \n \n blue = blue/255.0\n blue = cv2.pow(blue, correct_param)\n blue = np.uint8(blue*255)\n if equalizeHist:\n blue = cv2.equalizeHist(blue)\n \n\n output = cv2.merge((blue,green,red))\n return output", "_____no_output_____" ], [ "#GAMMA CORRECTION\ncv2.namedWindow('input')\ncv2.namedWindow('output')\ncolors = np.zeros((3))\n\nout = np.zeros_like((vidsize))\n\nwhile cap.isOpened():\n ret,image_np = cap.read()\n if ret == True:\n goruntu = gamma_correction(image_np)\n cv2.imshow('input', image_np)\n cv2.imshow('output', goruntu)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\n else:\n break\n \n\n\ncap.release() \ncv2.destroyAllWindows() ", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
cb668c721ebb137926bfea075ca87255aed68b5b
58,210
ipynb
Jupyter Notebook
lectures-labs/labs/03_neural_recsys/Implicit_Feedback_Recsys_with_the_triplet_loss_rendered.ipynb
gopala-kr/ds-notebooks
bc35430ecdd851f2ceab8f2437eec4d77cb59423
[ "MIT" ]
3
2019-09-30T08:04:21.000Z
2021-11-09T11:27:28.000Z
lectures-labs/labs/03_neural_recsys/Implicit_Feedback_Recsys_with_the_triplet_loss_rendered.ipynb
gopala-kr/ds-notebooks
bc35430ecdd851f2ceab8f2437eec4d77cb59423
[ "MIT" ]
null
null
null
lectures-labs/labs/03_neural_recsys/Implicit_Feedback_Recsys_with_the_triplet_loss_rendered.ipynb
gopala-kr/ds-notebooks
bc35430ecdd851f2ceab8f2437eec4d77cb59423
[ "MIT" ]
4
2019-04-20T03:02:05.000Z
2019-07-15T05:42:57.000Z
40.992958
475
0.549734
[ [ [ "# Triplet Loss for Implicit Feedback Neural Recommender Systems\n\nThe goal of this notebook is first to demonstrate how it is possible to build a bi-linear recommender system only using positive feedback data.\n\nIn a latter section we show that it is possible to train deeper architectures following the same design principles.\n\nThis notebook is inspired by Maciej Kula's [Recommendations in Keras using triplet loss](\nhttps://github.com/maciejkula/triplet_recommendations_keras). Contrary to Maciej we won't use the BPR loss but instead will introduce the more common margin-based comparator.\n\n## Loading the movielens-100k dataset\n\nFor the sake of computation time, we will only use the smallest variant of the movielens reviews dataset. Beware that the architectural choices and hyperparameters that work well on such a toy dataset will not necessarily be representative of the behavior when run on a more realistic dataset such as [Movielens 10M](https://grouplens.org/datasets/movielens/10m/) or the [Yahoo Songs dataset with 700M rating](https://webscope.sandbox.yahoo.com/catalog.php?datatype=r).", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os.path as op\n\nfrom zipfile import ZipFile\ntry:\n from urllib.request import urlretrieve\nexcept ImportError: # Python 2 compat\n from urllib import urlretrieve\n\n\nML_100K_URL = \"http://files.grouplens.org/datasets/movielens/ml-100k.zip\"\nML_100K_FILENAME = ML_100K_URL.rsplit('/', 1)[1]\nML_100K_FOLDER = 'ml-100k'\n\nif not op.exists(ML_100K_FILENAME):\n print('Downloading %s to %s...' % (ML_100K_URL, ML_100K_FILENAME))\n urlretrieve(ML_100K_URL, ML_100K_FILENAME)\n\nif not op.exists(ML_100K_FOLDER):\n print('Extracting %s to %s...' % (ML_100K_FILENAME, ML_100K_FOLDER))\n ZipFile(ML_100K_FILENAME).extractall('.')", "_____no_output_____" ], [ "data_train = pd.read_csv(op.join(ML_100K_FOLDER, 'ua.base'), sep='\\t',\n names=[\"user_id\", \"item_id\", \"rating\", \"timestamp\"])\ndata_test = pd.read_csv(op.join(ML_100K_FOLDER, 'ua.test'), sep='\\t',\n names=[\"user_id\", \"item_id\", \"rating\", \"timestamp\"])\n\ndata_train.describe()", "_____no_output_____" ], [ "data_train.head()", "_____no_output_____" ], [ "# data_test.describe()", "_____no_output_____" ], [ "max_user_id = max(data_train['user_id'].max(), data_test['user_id'].max())\nmax_item_id = max(data_train['item_id'].max(), data_test['item_id'].max())\n\nn_users = max_user_id + 1\nn_items = max_item_id + 1\n\nprint('n_users=%d, n_items=%d' % (n_users, n_items))", "n_users=944, n_items=1683\n" ] ], [ [ "## Implicit feedback data\n\nConsider ratings >= 4 as positive feed back and ignore the rest:", "_____no_output_____" ] ], [ [ "pos_data_train = data_train.query(\"rating >= 4\")\npos_data_test = data_test.query(\"rating >= 4\")", "_____no_output_____" ] ], [ [ "Because the median rating is around 3.5, this cut will remove approximately half of the ratings from the datasets:", "_____no_output_____" ] ], [ [ "pos_data_train['rating'].count()", "_____no_output_____" ], [ "pos_data_test['rating'].count()", "_____no_output_____" ] ], [ [ "## The Triplet Loss\n\nThe following section demonstrates how to build a low-rank quadratic interaction model between users and items. The similarity score between a user and an item is defined by the unormalized dot products of their respective embeddings.\n\nThe matching scores can be use to rank items to recommend to a specific user.\n\nTraining of the model parameters is achieved by randomly sampling negative items not seen by a pre-selected anchor user. We want the model embedding matrices to be such that the similarity between the user vector and the negative vector is smaller than the similarity between the user vector and the positive item vector. Furthermore we use a margin to further move appart the negative from the anchor user.\n\nHere is the architecture of such a triplet architecture. The triplet name comes from the fact that the loss to optimize is defined for triple `(anchor_user, positive_item, negative_item)`:\n\n<img src=\"images/rec_archi_implicit_2.svg\" style=\"width: 600px;\" />\n\nWe call this model a triplet model with bi-linear interactions because the similarity between a user and an item is captured by a dot product of the first level embedding vectors. This is therefore not a deep architecture.", "_____no_output_____" ] ], [ [ "import tensorflow as tf\n\n\ndef identity_loss(y_true, y_pred):\n \"\"\"Ignore y_true and return the mean of y_pred\n \n This is a hack to work-around the design of the Keras API that is\n not really suited to train networks with a triplet loss by default.\n \"\"\"\n return tf.reduce_mean(y_pred + 0 * y_true)\n\n\ndef margin_comparator_loss(inputs, margin=1.):\n \"\"\"Comparator loss for a pair of precomputed similarities\n \n If the inputs are cosine similarities, they each have range in\n (-1, 1), therefore their difference have range in (-2, 2). Using\n a margin of 1. can therefore make sense.\n\n If the input similarities are not normalized, it can be beneficial\n to use larger values for the margin of the comparator loss.\n \"\"\"\n positive_pair_sim, negative_pair_sim = inputs\n return tf.maximum(negative_pair_sim - positive_pair_sim + margin, 0)", "_____no_output_____" ] ], [ [ "Here is the actual code that builds the model(s) with shared weights. Note that here we use the cosine similarity instead of unormalized dot products (both seems to yield comparable results).", "_____no_output_____" ] ], [ [ "from keras.models import Model\nfrom keras.layers import Embedding, Flatten, Input, Dense, merge\nfrom keras.regularizers import l2\nfrom keras_fixes import dot_mode, cos_mode\n\n\ndef build_models(n_users, n_items, latent_dim=64, l2_reg=0):\n \"\"\"Build a triplet model and its companion similarity model\n \n The triplet model is used to train the weights of the companion\n similarity model. The triplet model takes 1 user, 1 positive item\n (relative to the selected user) and one negative item and is\n trained with comparator loss.\n \n The similarity model takes one user and one item as input and return\n compatibility score (aka the match score).\n \"\"\"\n # Common architectural components for the two models:\n # - symbolic input placeholders\n user_input = Input((1,), name='user_input')\n positive_item_input = Input((1,), name='positive_item_input')\n negative_item_input = Input((1,), name='negative_item_input')\n\n # - embeddings\n l2_reg = None if l2_reg == 0 else l2(l2_reg)\n user_layer = Embedding(n_users, latent_dim, input_length=1,\n name='user_embedding', W_regularizer=l2_reg)\n \n # The following embedding parameters will be shared to encode both\n # the positive and negative items.\n item_layer = Embedding(n_items, latent_dim, input_length=1,\n name=\"item_embedding\", W_regularizer=l2_reg)\n\n user_embedding = Flatten()(user_layer(user_input))\n positive_item_embedding = Flatten()(item_layer(positive_item_input))\n negative_item_embedding = Flatten()(item_layer(negative_item_input))\n\n # - similarity computation between embeddings\n positive_similarity = merge([user_embedding, positive_item_embedding],\n mode=cos_mode, output_shape=(1,),\n name=\"positive_similarity\")\n negative_similarity = merge([user_embedding, negative_item_embedding],\n mode=cos_mode, output_shape=(1,),\n name=\"negative_similarity\")\n\n # The triplet network model, only used for training\n triplet_loss = merge([positive_similarity, negative_similarity],\n mode=margin_comparator_loss, output_shape=(1,),\n name='comparator_loss')\n\n triplet_model = Model(input=[user_input,\n positive_item_input,\n negative_item_input],\n output=triplet_loss)\n \n # The match-score model, only use at inference to rank items for a given\n # model: the model weights are shared with the triplet_model therefore\n # we do not need to train it and therefore we do not need to plug a loss\n # and an optimizer.\n match_model = Model(input=[user_input, positive_item_input],\n output=positive_similarity)\n \n return triplet_model, match_model\n\n\ntriplet_model, match_model = build_models(n_users, n_items, latent_dim=64,\n l2_reg=1e-6)", "Using TensorFlow backend.\n" ] ], [ [ "### Exercise:\n\nHow many trainable parameters does each model. Count the shared parameters only once per model.", "_____no_output_____" ] ], [ [ "print(match_model.summary())", "____________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n====================================================================================================\nuser_input (InputLayer) (None, 1) 0 \n____________________________________________________________________________________________________\npositive_item_input (InputLayer) (None, 1) 0 \n____________________________________________________________________________________________________\nuser_embedding (Embedding) (None, 1, 64) 60416 user_input[0][0] \n____________________________________________________________________________________________________\nitem_embedding (Embedding) (None, 1, 64) 107712 positive_item_input[0][0] \n____________________________________________________________________________________________________\nflatten_1 (Flatten) (None, 64) 0 user_embedding[0][0] \n____________________________________________________________________________________________________\nflatten_2 (Flatten) (None, 64) 0 item_embedding[0][0] \n____________________________________________________________________________________________________\npositive_similarity (Merge) (None, 1) 0 flatten_1[0][0] \n flatten_2[0][0] \n====================================================================================================\nTotal params: 168,128\nTrainable params: 168,128\nNon-trainable params: 0\n____________________________________________________________________________________________________\nNone\n" ], [ "print(triplet_model.summary())", "____________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n====================================================================================================\nuser_input (InputLayer) (None, 1) 0 \n____________________________________________________________________________________________________\npositive_item_input (InputLayer) (None, 1) 0 \n____________________________________________________________________________________________________\nnegative_item_input (InputLayer) (None, 1) 0 \n____________________________________________________________________________________________________\nuser_embedding (Embedding) (None, 1, 64) 60416 user_input[0][0] \n____________________________________________________________________________________________________\nitem_embedding (Embedding) (None, 1, 64) 107712 positive_item_input[0][0] \n negative_item_input[0][0] \n____________________________________________________________________________________________________\nflatten_1 (Flatten) (None, 64) 0 user_embedding[0][0] \n____________________________________________________________________________________________________\nflatten_2 (Flatten) (None, 64) 0 item_embedding[0][0] \n____________________________________________________________________________________________________\nflatten_3 (Flatten) (None, 64) 0 item_embedding[1][0] \n____________________________________________________________________________________________________\npositive_similarity (Merge) (None, 1) 0 flatten_1[0][0] \n flatten_2[0][0] \n____________________________________________________________________________________________________\nnegative_similarity (Merge) (None, 1) 0 flatten_1[0][0] \n flatten_3[0][0] \n____________________________________________________________________________________________________\ncomparator_loss (Merge) (None, 1) 0 positive_similarity[0][0] \n negative_similarity[0][0] \n====================================================================================================\nTotal params: 168,128\nTrainable params: 168,128\nNon-trainable params: 0\n____________________________________________________________________________________________________\nNone\n" ], [ "# %load solutions/triplet_parameter_count.py\n# Analysis:\n#\n# Both models have exactly the same number of parameters,\n# namely the parameters of the 2 embeddings:\n#\n# - user embedding: n_users x embedding_dim\n# - item embedding: n_items x embedding_dim\n#\n# The triplet model uses the same item embedding twice,\n# once to compute the positive similarity and the other\n# time to compute the negative similarity. However because\n# those two nodes in the computation graph share the same\n# instance of the item embedding layer, the item embedding\n# weight matrix is shared by the two branches of the\n# graph and therefore the total number of parameters for\n# each model is in both cases:\n#\n# (n_users x embedding_dim) + (n_items x embedding_dim)", "_____no_output_____" ] ], [ [ "## Quality of Ranked Recommendations\n\nNow that we have a randomly initialized model we can start computing random recommendations. To assess their quality we do the following for each user:\n\n- compute matching scores for items (except the movies that the user has already seen in the training set),\n- compare to the positive feedback actually collected on the test set using the ROC AUC ranking metric,\n- average ROC AUC scores across users to get the average performance of the recommender model on the test set.", "_____no_output_____" ] ], [ [ "from sklearn.metrics import roc_auc_score\n\n\ndef average_roc_auc(match_model, data_train, data_test):\n \"\"\"Compute the ROC AUC for each user and average over users\"\"\"\n max_user_id = max(data_train['user_id'].max(), data_test['user_id'].max())\n max_item_id = max(data_train['item_id'].max(), data_test['item_id'].max())\n user_auc_scores = []\n for user_id in range(1, max_user_id + 1):\n pos_item_train = data_train[data_train['user_id'] == user_id]\n pos_item_test = data_test[data_test['user_id'] == user_id]\n \n # Consider all the items already seen in the training set\n all_item_ids = np.arange(1, max_item_id + 1)\n items_to_rank = np.setdiff1d(all_item_ids, pos_item_train['item_id'].values)\n \n # Ground truth: return 1 for each item positively present in the test set\n # and 0 otherwise.\n expected = np.in1d(items_to_rank, pos_item_test['item_id'].values)\n \n if np.sum(expected) >= 1:\n # At least one positive test value to rank\n repeated_user_id = np.empty_like(items_to_rank)\n repeated_user_id.fill(user_id)\n\n predicted = match_model.predict([repeated_user_id, items_to_rank],\n batch_size=4096)\n user_auc_scores.append(roc_auc_score(expected, predicted))\n\n return sum(user_auc_scores) / len(user_auc_scores)", "_____no_output_____" ] ], [ [ "By default the model should make predictions that rank the items in random order. The **ROC AUC score** is a ranking score that represents the **expected value of correctly ordering uniformly sampled pairs of recommendations**.\n\nA random (untrained) model should yield 0.50 ROC AUC on average. ", "_____no_output_____" ] ], [ [ "average_roc_auc(match_model, pos_data_train, pos_data_test)", "_____no_output_____" ] ], [ [ "## Training the Triplet Model\n\nLet's now fit the parameters of the model by sampling triplets: for each user, select a movie in the positive feedback set of that user and randomly sample another movie to serve as negative item.\n\nNote that this sampling scheme could be improved by removing items that are marked as positive in the data to remove some label noise. In practice this does not seem to be a problem though.", "_____no_output_____" ] ], [ [ "def sample_triplets(pos_data, max_item_id, random_seed=0):\n \"\"\"Sample negatives at random\"\"\"\n rng = np.random.RandomState(random_seed)\n user_ids = pos_data['user_id'].values\n pos_item_ids = pos_data['item_id'].values\n\n neg_item_ids = rng.randint(low=1, high=max_item_id + 1,\n size=len(user_ids))\n\n return [user_ids, pos_item_ids, neg_item_ids]", "_____no_output_____" ] ], [ [ "Let's train the triplet model:", "_____no_output_____" ] ], [ [ "# we plug the identity loss and the a fake target variable ignored by\n# the model to be able to use the Keras API to train the triplet model\ntriplet_model.compile(loss=identity_loss, optimizer=\"adam\")\nfake_y = np.ones_like(pos_data_train['user_id'])\n\nn_epochs = 15\n\nfor i in range(n_epochs):\n # Sample new negatives to build different triplets at each epoch\n triplet_inputs = sample_triplets(pos_data_train, max_item_id,\n random_seed=i)\n\n # Fit the model incrementally by doing a single pass over the\n # sampled triplets.\n triplet_model.fit(triplet_inputs, fake_y, shuffle=True,\n batch_size=64, nb_epoch=1, verbose=2)\n \n # Monitor the convergence of the model\n test_auc = average_roc_auc(match_model, pos_data_train, pos_data_test)\n print(\"Epoch %d/%d: test ROC AUC: %0.4f\"\n % (i + 1, n_epochs, test_auc))", "Epoch 1/1\n1s - loss: 0.7678\nEpoch 1/15: test ROC AUC: 0.8481\nEpoch 1/1\n1s - loss: 0.3854\nEpoch 2/15: test ROC AUC: 0.8858\nEpoch 1/1\n1s - loss: 0.3564\nEpoch 3/15: test ROC AUC: 0.9002\nEpoch 1/1\n1s - loss: 0.3430\nEpoch 4/15: test ROC AUC: 0.9052\nEpoch 1/1\n1s - loss: 0.3358\nEpoch 5/15: test ROC AUC: 0.9109\nEpoch 1/1\n1s - loss: 0.3287\nEpoch 6/15: test ROC AUC: 0.9142\nEpoch 1/1\n1s - loss: 0.3307\nEpoch 7/15: test ROC AUC: 0.9175\nEpoch 1/1\n1s - loss: 0.3246\nEpoch 8/15: test ROC AUC: 0.9180\nEpoch 1/1\n1s - loss: 0.3232\nEpoch 9/15: test ROC AUC: 0.9184\nEpoch 1/1\n1s - loss: 0.3211\nEpoch 10/15: test ROC AUC: 0.9186\nEpoch 1/1\n1s - loss: 0.3192\nEpoch 11/15: test ROC AUC: 0.9193\nEpoch 1/1\n1s - loss: 0.3196\nEpoch 12/15: test ROC AUC: 0.9205\nEpoch 1/1\n1s - loss: 0.3186\nEpoch 13/15: test ROC AUC: 0.9210\nEpoch 1/1\n1s - loss: 0.3221\nEpoch 14/15: test ROC AUC: 0.9221\nEpoch 1/1\n1s - loss: 0.3171\nEpoch 15/15: test ROC AUC: 0.9233\n" ] ], [ [ "## Training a Deep Matching Model on Implicit Feedback\n\n\nInstead of using hard-coded cosine similarities to predict the match of a `(user_id, item_id)` pair, we can instead specify a deep neural network based parametrisation of the similarity. The parameters of that matching model are also trained with the margin comparator loss:\n\n<img src=\"images/rec_archi_implicit_1.svg\" style=\"width: 600px;\" />\n\n\n### Exercise to complete as a home assignment:\n\n- Implement a `deep_match_model`, `deep_triplet_model` pair of models\n for the architecture described in the schema. The last layer of\n the embedded Multi Layer Perceptron outputs a single scalar that\n encodes the similarity between a user and a candidate item.\n\n- Evaluate the resulting model by computing the per-user average\n ROC AUC score on the test feedback data.\n \n - Check that the AUC ROC score is close to 0.50 for a randomly\n initialized model.\n \n - Check that you can reach at least 0.91 ROC AUC with this deep\n model (you might need to adjust the hyperparameters).\n \n \nHints:\n\n- it is possible to reuse the code to create embeddings from the previous model\n definition;\n\n- the concatenation between user and the positive item embedding can be\n obtained with:\n\n```py\n positive_embeddings_pair = merge([user_embedding, positive_item_embedding],\n mode='concat',\n name=\"positive_embeddings_pair\")\n negative_embeddings_pair = merge([user_embedding, negative_item_embedding],\n mode='concat',\n name=\"negative_embeddings_pair\")\n```\n\n- those embedding pairs should be fed to a shared MLP instance to compute the similarity scores.", "_____no_output_____" ] ], [ [ "from keras.models import Sequential\n\n\ndef make_interaction_mlp(input_dim, n_hidden=1, hidden_size=64,\n dropout=0, l2_reg=None):\n mlp = Sequential()\n # TODO:\n return mlp\n\n\ndef build_models(n_users, n_items, user_dim=32, item_dim=64,\n n_hidden=1, hidden_size=64, dropout=0, l2_reg=0):\n # TODO:\n # Inputs and the shared embeddings can be defined as previously.\n\n # Use a single instance of the MLP created by make_interaction_mlp()\n # and use it twice: once on the positive pair, once on the negative\n # pair\n interaction_layers = make_interaction_mlp(\n user_dim + item_dim, n_hidden=n_hidden, hidden_size=hidden_size,\n dropout=dropout, l2_reg=l2_reg)\n\n # Build the models: one for inference, one for triplet training\n deep_match_model = None\n deep_triplet_model = None\n return deep_match_model, deep_triplet_model", "_____no_output_____" ], [ "# %load solutions/deep_implicit_feedback_recsys.py\nfrom keras.models import Model, Sequential\nfrom keras.layers import Embedding, Flatten, Input, Dense, Dropout, merge\nfrom keras.regularizers import l2\n\n\ndef make_interaction_mlp(input_dim, n_hidden=1, hidden_size=64,\n dropout=0, l2_reg=None):\n \"\"\"Build the shared multi layer perceptron\"\"\"\n mlp = Sequential()\n if n_hidden == 0:\n # Plug the output unit directly: this is a simple\n # linear regression model. Not dropout required.\n mlp.add(Dense(1, input_dim=input_dim,\n activation='relu', W_regularizer=l2_reg))\n else:\n mlp.add(Dense(hidden_size, input_dim=input_dim,\n activation='relu', W_regularizer=l2_reg))\n mlp.add(Dropout(dropout))\n for i in range(n_hidden - 1):\n mlp.add(Dense(hidden_size, activation='relu',\n W_regularizer=l2_reg))\n mlp.add(Dropout(dropout))\n mlp.add(Dense(1, activation='relu', W_regularizer=l2_reg))\n return mlp\n\n\ndef build_models(n_users, n_items, user_dim=32, item_dim=64,\n n_hidden=1, hidden_size=64, dropout=0, l2_reg=0):\n \"\"\"Build models to train a deep triplet network\"\"\"\n user_input = Input((1,), name='user_input')\n positive_item_input = Input((1,), name='positive_item_input')\n negative_item_input = Input((1,), name='negative_item_input')\n\n l2_reg = None if l2_reg == 0 else l2(l2_reg)\n user_layer = Embedding(n_users, user_dim, input_length=1,\n name='user_embedding', W_regularizer=l2_reg)\n\n # The following embedding parameters will be shared to encode both\n # the positive and negative items.\n item_layer = Embedding(n_items, item_dim, input_length=1,\n name=\"item_embedding\", W_regularizer=l2_reg)\n\n user_embedding = Flatten()(user_layer(user_input))\n positive_item_embedding = Flatten()(item_layer(positive_item_input))\n negative_item_embedding = Flatten()(item_layer(negative_item_input))\n\n\n # Similarity computation between embeddings using a MLP similarity\n positive_embeddings_pair = merge([user_embedding, positive_item_embedding],\n mode='concat',\n name=\"positive_embeddings_pair\")\n positive_embeddings_pair = Dropout(dropout)(positive_embeddings_pair)\n negative_embeddings_pair = merge([user_embedding, negative_item_embedding],\n mode='concat',\n name=\"negative_embeddings_pair\")\n negative_embeddings_pair = Dropout(dropout)(negative_embeddings_pair)\n\n # Instanciate the shared similarity architecture\n interaction_layers = make_interaction_mlp(\n user_dim + item_dim, n_hidden=n_hidden, hidden_size=hidden_size,\n dropout=dropout, l2_reg=l2_reg)\n\n positive_similarity = interaction_layers(positive_embeddings_pair)\n negative_similarity = interaction_layers(negative_embeddings_pair)\n\n # The triplet network model, only used for training\n triplet_loss = merge([positive_similarity, negative_similarity],\n mode=margin_comparator_loss, output_shape=(1,),\n name='comparator_loss')\n\n deep_triplet_model = Model(input=[user_input,\n positive_item_input,\n negative_item_input],\n output=triplet_loss)\n\n # The match-score model, only used at inference\n deep_match_model = Model(input=[user_input, positive_item_input],\n output=positive_similarity)\n\n return deep_match_model, deep_triplet_model\n\n\nhyper_parameters = dict(\n user_dim=32,\n item_dim=64,\n n_hidden=1,\n hidden_size=128,\n dropout=0.1,\n l2_reg=0\n)\ndeep_match_model, deep_triplet_model = build_models(n_users, n_items,\n **hyper_parameters)\n\n\ndeep_triplet_model.compile(loss=identity_loss, optimizer='adam')\nfake_y = np.ones_like(pos_data_train['user_id'])\n\nn_epochs = 15\n\nfor i in range(n_epochs):\n # Sample new negatives to build different triplets at each epoch\n triplet_inputs = sample_triplets(pos_data_train, max_item_id,\n random_seed=i)\n\n # Fit the model incrementally by doing a single pass over the\n # sampled triplets.\n deep_triplet_model.fit(triplet_inputs, fake_y, shuffle=True,\n batch_size=64, nb_epoch=1, verbose=2)\n\n # Monitor the convergence of the model\n test_auc = average_roc_auc(deep_match_model, pos_data_train, pos_data_test)\n print(\"Epoch %d/%d: test ROC AUC: %0.4f\"\n % (i + 1, n_epochs, test_auc))\n", "Epoch 1/1\n2s - loss: 0.4704\nEpoch 1/15: test ROC AUC: 0.8545\nEpoch 1/1\n1s - loss: 0.3798\nEpoch 2/15: test ROC AUC: 0.8620\nEpoch 1/1\n1s - loss: 0.3722\nEpoch 3/15: test ROC AUC: 0.8638\nEpoch 1/1\n1s - loss: 0.3670\nEpoch 4/15: test ROC AUC: 0.8639\nEpoch 1/1\n1s - loss: 0.3620\nEpoch 5/15: test ROC AUC: 0.8682\nEpoch 1/1\n1s - loss: 0.3502\nEpoch 6/15: test ROC AUC: 0.8785\nEpoch 1/1\n1s - loss: 0.3343\nEpoch 7/15: test ROC AUC: 0.8863\nEpoch 1/1\n1s - loss: 0.3183\nEpoch 8/15: test ROC AUC: 0.8893\nEpoch 1/1\n1s - loss: 0.3131\nEpoch 9/15: test ROC AUC: 0.8912\nEpoch 1/1\n1s - loss: 0.3058\nEpoch 10/15: test ROC AUC: 0.8941\nEpoch 1/1\n1s - loss: 0.2971\nEpoch 11/15: test ROC AUC: 0.8986\nEpoch 1/1\n1s - loss: 0.2899\nEpoch 12/15: test ROC AUC: 0.9014\nEpoch 1/1\n1s - loss: 0.2824\nEpoch 13/15: test ROC AUC: 0.9076\nEpoch 1/1\n1s - loss: 0.2800\nEpoch 14/15: test ROC AUC: 0.9102\nEpoch 1/1\n1s - loss: 0.2708\nEpoch 15/15: test ROC AUC: 0.9121\n" ] ], [ [ "### Exercise:\n\nCount the number of parameters in `deep_match_model` and `deep_triplet_model`. Which model has the largest number of parameters?", "_____no_output_____" ] ], [ [ "print(deep_match_model.summary())", "____________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n====================================================================================================\nuser_input (InputLayer) (None, 1) 0 \n____________________________________________________________________________________________________\npositive_item_input (InputLayer) (None, 1) 0 \n____________________________________________________________________________________________________\nuser_embedding (Embedding) (None, 1, 32) 30208 user_input[0][0] \n____________________________________________________________________________________________________\nitem_embedding (Embedding) (None, 1, 64) 107712 positive_item_input[0][0] \n____________________________________________________________________________________________________\nflatten_4 (Flatten) (None, 32) 0 user_embedding[0][0] \n____________________________________________________________________________________________________\nflatten_5 (Flatten) (None, 64) 0 item_embedding[0][0] \n____________________________________________________________________________________________________\npositive_embeddings_pair (Merge) (None, 96) 0 flatten_4[0][0] \n flatten_5[0][0] \n____________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 96) 0 positive_embeddings_pair[0][0] \n____________________________________________________________________________________________________\nsequential_1 (Sequential) (None, 1) 12545 dropout_1[0][0] \n====================================================================================================\nTotal params: 150,465\nTrainable params: 150,465\nNon-trainable params: 0\n____________________________________________________________________________________________________\nNone\n" ], [ "print(deep_triplet_model.summary())", "____________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n====================================================================================================\nuser_input (InputLayer) (None, 1) 0 \n____________________________________________________________________________________________________\npositive_item_input (InputLayer) (None, 1) 0 \n____________________________________________________________________________________________________\nnegative_item_input (InputLayer) (None, 1) 0 \n____________________________________________________________________________________________________\nuser_embedding (Embedding) (None, 1, 32) 30208 user_input[0][0] \n____________________________________________________________________________________________________\nitem_embedding (Embedding) (None, 1, 64) 107712 positive_item_input[0][0] \n negative_item_input[0][0] \n____________________________________________________________________________________________________\nflatten_4 (Flatten) (None, 32) 0 user_embedding[0][0] \n____________________________________________________________________________________________________\nflatten_5 (Flatten) (None, 64) 0 item_embedding[0][0] \n____________________________________________________________________________________________________\nflatten_6 (Flatten) (None, 64) 0 item_embedding[1][0] \n____________________________________________________________________________________________________\npositive_embeddings_pair (Merge) (None, 96) 0 flatten_4[0][0] \n flatten_5[0][0] \n____________________________________________________________________________________________________\nnegative_embeddings_pair (Merge) (None, 96) 0 flatten_4[0][0] \n flatten_6[0][0] \n____________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 96) 0 positive_embeddings_pair[0][0] \n____________________________________________________________________________________________________\ndropout_2 (Dropout) (None, 96) 0 negative_embeddings_pair[0][0] \n____________________________________________________________________________________________________\nsequential_1 (Sequential) (None, 1) 12545 dropout_1[0][0] \n dropout_2[0][0] \n____________________________________________________________________________________________________\ncomparator_loss (Merge) (None, 1) 0 sequential_1[1][0] \n sequential_1[2][0] \n====================================================================================================\nTotal params: 150,465\nTrainable params: 150,465\nNon-trainable params: 0\n____________________________________________________________________________________________________\nNone\n" ], [ "# %load solutions/deep_triplet_parameter_count.py\n# Analysis:\n#\n# Both models have again exactly the same number of parameters,\n# namely the parameters of the 2 embeddings:\n#\n# - user embedding: n_users x user_dim\n# - item embedding: n_items x item_dim\n#\n# and the parameters of the MLP model used to compute the\n# similarity score of an (user, item) pair:\n#\n# - first hidden layer weights: (user_dim + item_dim) * hidden_size\n# - first hidden biases: hidden_size\n# - extra hidden layers weights: hidden_size * hidden_size\n# - extra hidden layers biases: hidden_size\n# - output layer weights: hidden_size * 1\n# - output layer biases: 1\n#\n# The triplet model uses the same item embedding layer\n# twice and the same MLP instance twice:\n# once to compute the positive similarity and the other\n# time to compute the negative similarity. However because\n# those two lanes in the computation graph share the same\n# instances for the item embedding layer and for the MLP,\n# their parameters are shared.\n#\n# Reminder: MLP stands for multi-layer perceptron, which is a\n# common short-hand for Feed Forward Fully Connected Neural\n# Network.", "_____no_output_____" ] ], [ [ "## Possible Extensions\n\nYou can implement any of the following ideas if you want to get a deeper understanding of recommender systems.\n\n\n### Leverage User and Item metadata\n\nAs we did for the Explicit Feedback model, it's also possible to extend our models to take additional user and item metadata as side information when computing the match score.\n\n\n### Better Ranking Metrics\n\nIn this notebook we evaluated the quality of the ranked recommendations using the ROC AUC metric. This score reflect the ability of the model to correctly rank any pair of items (sampled uniformly at random among all possible items).\n\nIn practice recommender systems will only display a few recommendations to the user (typically 1 to 10). It is typically more informative to use an evaluatio metric that characterize the quality of the top ranked items and attribute less or no importance to items that are not good recommendations for a specific users. Popular ranking metrics therefore include the **Precision at k** and the **Mean Average Precision**.\n\nYou can read up online about those metrics and try to implement them here.\n\n\n### Hard Negatives Sampling\n\nIn this experiment we sampled negative items uniformly at random. However, after training the model for a while, it is possible that the vast majority of sampled negatives have a similarity already much lower than the positive pair and that the margin comparator loss sets the majority of the gradients to zero effectively wasting a lot of computation.\n\nGiven the current state of the recsys model we could sample harder negatives with a larger likelihood to train the model better closer to its decision boundary. This strategy is implemented in the WARP loss [1].\n\nThe main drawback of hard negative sampling is increasing the risk of sever overfitting if a significant fraction of the labels are noisy.\n\n\n### Factorization Machines\n\nA very popular recommender systems model is called Factorization Machines [2][3]. They two use low rank vector representations of the inputs but they do not use a cosine similarity or a neural network to model user/item compatibility.\n\nIt is be possible to adapt our previous code written with Keras to replace the cosine sims / MLP with the low rank FM quadratic interactions by reading through [this gentle introduction](http://tech.adroll.com/blog/data-science/2015/08/25/factorization-machines.html).\n\nIf you choose to do so, you can compare the quality of the predictions with those obtained by the [pywFM project](https://github.com/jfloff/pywFM) which provides a Python wrapper for the [official libFM C++ implementation](http://www.libfm.org/). Maciej Kula also maintains a [lighfm](http://www.libfm.org/) that implements an efficient and well documented variant in Cython and Python.\n\n\n## References:\n\n [1] Wsabie: Scaling Up To Large Vocabulary Image Annotation\n Jason Weston, Samy Bengio, Nicolas Usunier, 2011\n https://research.google.com/pubs/pub37180.html\n\n [2] Factorization Machines, Steffen Rendle, 2010\n https://www.ismll.uni-hildesheim.de/pub/pdfs/Rendle2010FM.pdf\n\n [3] Factorization Machines with libFM, Steffen Rendle, 2012\n in ACM Trans. Intell. Syst. Technol., 3(3), May.\n http://doi.acm.org/10.1145/2168752.2168771", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
cb66a0d6b9a218c27b277ed20bb14fb9fb4c447b
23,358
ipynb
Jupyter Notebook
poeun/ml_12.ipynb
ingu627/handson-ml2
fa16881b044750a895ba6eddf98c1d9bac198917
[ "Apache-2.0" ]
1
2021-11-13T02:04:22.000Z
2021-11-13T02:04:22.000Z
poeun/ml_12.ipynb
ingu627/handson-ml2
fa16881b044750a895ba6eddf98c1d9bac198917
[ "Apache-2.0" ]
null
null
null
poeun/ml_12.ipynb
ingu627/handson-ml2
fa16881b044750a895ba6eddf98c1d9bac198917
[ "Apache-2.0" ]
null
null
null
28.007194
332
0.497988
[ [ [ "import tensorflow as tf\n\ntf.constant([[1.,2.,3.], [4.,5.,6.]])", "_____no_output_____" ], [ "tf.constant(42) # 스칼라", "_____no_output_____" ], [ "t = tf.constant([[1.,2.,3.], [4.,5.,6.]])\nt.shape # TensorShape([2, 3])\nt.dtype # tf.float32", "_____no_output_____" ], [ "t[:, 1:]", "_____no_output_____" ], [ "t[..., 1, tf.newaxis]", "_____no_output_____" ], [ "t + 10", "_____no_output_____" ], [ "tf.square(t) # 제곱", "_____no_output_____" ], [ "t @ tf.transpose(t) # transpose는 행렬 변환", "_____no_output_____" ], [ "import numpy as np\n\na = np.array([2., 4., 5.])\ntf.constant(a)\n# <tf.Tensor: shape=(3,), dtype=float64, numpy=array([2., 4., 5.])>\nnp.array(t)\n# array([[1., 2., 3.],\n# [4., 5., 6.]], dtype=float32)\ntf.square(a)\n# <tf.Tensor: shape=(3,), dtype=float64, numpy=array([ 4., 16., 25.])>\nnp.square(t)\n# array([[ 1., 4., 9.],\n# [16., 25., 36.]], dtype=float32)", "_____no_output_____" ], [ "t2 = tf.constant(40., dtype=tf.float64)\ntf.constant(2.0) + tf.cast(t2, tf.float32)\n# <tf.Tensor: shape=(), dtype=float32, numpy=42.0>", "_____no_output_____" ], [ "v = tf.Variable([[1.,2.,3.], [4.,5.,6.]])\nv", "_____no_output_____" ], [ "v.assign(2 * v)", "_____no_output_____" ], [ "v[0,1].assign(42)", "_____no_output_____" ], [ "v[:,2].assign([0., 1.])", "_____no_output_____" ], [ "v.scatter_nd_update(indices=[[0,0], [1,2]], updates=[100., 200.])", "_____no_output_____" ], [ "def huber_fn(y_true, y_pred):\n error = y_true - y_pred\n is_small_error = tf.abs(error) < 1\n squared_loss = tf.square(error) / 2\n linear_loss = tf.abs(error) - 0.5\n return tf.where(is_small_error, squared_loss, linear_loss)", "_____no_output_____" ], [ "model.compile(loss=huber_fn, optimizer='nadam')\nmodel.fit(X_train, y_train, [...])", "_____no_output_____" ], [ "from tensorflow.keras.models import load_model\n\nmodel = load_model(\"my_model_with_a_custom_loss.h5\",\n custom_objects={\"huber_fn\": huber_fn})", "_____no_output_____" ], [ "def create_huber(threshold=1.0):\n def huber_fn(y_true, y_pred):\n error = y_true - y_pred\n is_small_error = tf.abs(error) < threshold\n squared_loss = tf.square(error) / 2\n linear_loss = threshold * tf.abs(error) - threshold**2 / 2\n return tf.where(is_small_error, squared_loss, linear_loss)\n return huber_fn\n\nmodel.compile(loss=create_huber(2.0), optimizer=\"nadam\")", "_____no_output_____" ], [ "model = load_model(\"my_model_with_a_custom_loss_threshold_2.h5\",\n custom_objects={\"huber_fn\": create_huber(2.0)})", "_____no_output_____" ], [ "from tensorflow.keras.losses import Loss\n\nclass HuberLoss(Loss):\n def __init__(self, threshold=1.0, **kwargs):\n self.threshold = threshold\n super().__init__(**kwargs)\n def call(self, y_true, y_pred):\n error = y_true - y_pred\n is_small_error = tf.abs(error) < self.threshold\n squared_loss = tf.square(error) / 2\n linear_loss = self.threshold * tf.abs(error) - self.threshold**2 / 2\n return tf.where(is_small_error, squared_loss, linear_loss)\n def get_config(self):\n base_config = super().get_config()\n return {**base_config, \"threshold\": self.threshold}", "_____no_output_____" ], [ "model.compile(loss=HuberLoss(2.), optimizer=\"nadam\")\n\nmodel = load_model(\"my_model_with_a_custom_loss_class.h5\",\n custom_objects={\"HuberLoss\": HuberLoss})", "_____no_output_____" ], [ "import tensorflow as tf\n\n# 사용자 정의 활성화 함수 (keras.activations.softplus())\ndef my_softplus(z):\n return tf.math.log(tf.exp(z) + 1.0)\n\n# 사용자 정의 글로럿 초기화 (keras.initializers.glorot_normal())\ndef my_glorot_initializer(shape, dtype=tf.float32):\n stddev = tf.sqrt(2. / (shape[0] + shape[1]))\n return tf.random.normal(shape, stddev=stddev, dtype=dtype)\n\ndef my_l1_regularizer(weights):\n return tf.reduce_sum(tf.abs(0.01 * weights))\n\ndef my_positive_weights(weights):\n return tf.where(weights < 0., tf.zeros_like(weights), weights)", "_____no_output_____" ], [ "from tensorflow.keras.layers import Dense\n\nlayer = Dense(30 activation=my_softplus,\n kernel_initializer=my_glorot_initializer,\n kernel_regularizer=my_l1_regularizer,\n kernel_constarint=my_positive_weights)", "_____no_output_____" ], [ "model.compile(loss='mse', optimizer='nadam', metrics=[create_huber(2.0)])", "_____no_output_____" ], [ "from tensorflow.keras.metrics import Metric\nimport tensorflow as tf\n\nclass HuberMetric(Metric):\n def __init__(self, threshold=1.0, **kwargs):\n super().__init__(**kwargs)\n self.threshold = threshold\n self.huber_fn = create_huber(threshold)\n self.total = self.add_weight('total', initializer='zeros')\n self.count = self.add_Weight('count', initializer='zeros')\n def update_state(self, y_true, y_pred, sample_weight=None):\n metric = self.huber_fn(y_true, y_pred)\n self.total.assign_add(tf.reduce_sum(metric))\n self.count.assign_add(tf.cast(Tf.size(y_true), tf.float32))\n def result(self):\n return self.total / self.count\n def get_config(self):\n basㅠㅠe_config = super().get_config()\n return {**base_config, \"threshold\":self.threshold}", "_____no_output_____" ], [ "from tensorflow.keras.layers import Layer\n\nclass MyDense(Layer):\n def __init__(self, units, activation=None, **kwargs):\n super().__init__(**kwargs)\n self.units = units\n self.activation = tf.keras.activations.get(activation)\n \n def build(self, batch_input_shape):\n self.kernel = self.add_weight(\n name='kernel', shape=[batch_input_shape[-1], self.units],\n initializer = 'glorot_normal'\n )\n self.bias = self.add_weight(\n name='bias', shape=[self.units], initializer='zeros'\n )\n super().build(batch_input_shape)\n \n def call(self, X):\n return self.activation(X @ self.kernel + self.bias)\n \n def comput_output_shape(self, batch_input_shape):\n return tf.TensorShape(batch_input_shape.as_list()[:-1] + [self.units])\n \n def get_config(self):\n base_config = super().get_config()\n return {**base_config, 'units':self.units,\n 'activation': tf.keras.activations.serialize(self.activation)}", "_____no_output_____" ], [ "class MyMultiLayer(tf.keras.layers.Layer):\n def call(self, X):\n X1, X2 = X\n return [X1 + X2, X1 * X2, X1 / X2]\n \n def compute_output_shape(self, batch_input_shape):\n b1, b2 = batch_input_shape\n return [b1, b1, b1]", "_____no_output_____" ], [ "class MyGaussianNoise(tf.keras.layers.Layer):\n def __init__(self, stddev, **kwargs):\n super().__init__(**kwargs)\n self.stddev = stddev\n \n def call(self, X, training=None):\n if training:\n noise = tf.random.normal(tf.shape(X), stddev=self.stddev)\n return X + noise\n else:\n return X\n \n def compute_output_shape(self, batch_input_shape):\n return batch_input_shape", "_____no_output_____" ], [ "import tensorflow as tf\n\nclass ResidualBlock(tf.keras.layers.Layer):\n def __init__(self, n_layers, n_neurons, **kwargs):\n super().__init__(**kwargs)\n self.hidden = [tf.keras.layers.Dense(n_neurons, activation='elu',\n kernel_initializer='he_normal')\n for _ in range(n_layers)]\n \n def call(self, inputs):\n Z = inputs\n for layer in self.hidden:\n Z = layer(Z)\n return inputs + Z", "_____no_output_____" ], [ "class ResidualRegressor(tf.keras.Model):\n def __init__(self, output_dim, **kwargs):\n super().__init__(**kwargs)\n self.hidden1 = tf.keras.layers.Dense(30, activation='elu',\n kernel_initializer='he_normal')\n self.block1 = ResidualBlock(2, 30)\n self.block2 = ResidualBlock(2, 30)\n self.out = tf.keras.layers.Dense(output_dim)\n \n def call(self, inputs):\n Z = self.hidden1(inputs)\n for _ in range(1 + 3):\n Z = self.block1(Z)\n Z = self.block2(Z)\n return self.out(Z)", "_____no_output_____" ], [ "class ReconstructingRegressor(tf.keras.Model):\n def __init__(self, output_dim, **kwargs):\n super().__init__(**kwargs)\n self.hidden = [tf.keras.layers.Dense(30, activation='selu',\n kernel_initializer='lecun_normal')\n for _ in range(5)]\n self.out = tf.keras.layers.Dense(output_dim)\n \n def build(self, batch_input_shape):\n n_inputs = batch_input_shape[-1]\n self.reconstruct = tf.keras.layers.Dense(n_inputs)\n super().build(batch_input_shape)\n \n def call(self, inputs):\n Z = inputs\n for layer in self.hidden:\n Z = layer(Z)\n reconstruction = self.reconstruct(Z)\n recon_loss = tf.reduce_mean(tf.square(reconstruction - inputs))\n self.add_loss(0.05 * recon_loss)\n return self.out(Z)", "_____no_output_____" ], [ "def f(w1, w2):\n return 3 * w1 ** 2 + 2 * w1 * w2\n\nw1, w2 = 5, 3; eps = 1e-6\nprint((f(w1 + eps, w2) - f(w1, w2)) / eps) # 36.000003007075065\nprint((f(w1, w2 + eps) - f(w1, w2)) / eps) # 10.000000003174137", "36.000003007075065\n10.000000003174137\n" ], [ "w1, w2 = tf.Variable(5.), tf.Variable(3.)\nwith tf.GradientTape() as tape:\n z = f(w1, w2)\n \ngradients = tape.gradient(z, [w1, w2])\ngradients\n# [<tf.Tensor: shape=(), dtype=float32, numpy=36.0>,\n# <tf.Tensor: shape=(), dtype=float32, numpy=10.0>]", "_____no_output_____" ], [ "l2_reg = tf.keras.regularizers.l2(0.05)\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Dense(30, activation='elu', kernel_initializer='he_normal',\n kernel_regulaizer=l2_reg),\n tf.keras.layers.Dense(1, kernel_regularizer=l2_reg)\n])", "_____no_output_____" ], [ "def random_batch(X, y, batch_size=32):\n idx = np.random.randint(len(X), size=batch_size)\n return X[idx], y[idx]", "_____no_output_____" ], [ "def print_status_bar(iteration, total, loss, metrics=None):\n metrics = \" - \".join([\"{}: {:.4f}\".format(m.name, m.result())\n for m in [loss] + (metrics or [])])\n end = \"\" if iteration < total else \"\\n\"\n print(\"\\r{}/{} - \".format(iteration, total) + metrics,\n end=end)", "_____no_output_____" ], [ "n_epochs = 5\nbatch_size = 32\nn_steps = len(X_train) // batch_size\noptimizer = tf.keras.optimizers.Nadam(lr=0.01)\nloss_fn = tf.keras.losses.mean_squared_error\nmean_loss = tf.keras.metrics.Mean()\nmetrics = [tf.keras.metrics.MeanAbsoluteError()]\n\nfor epoch in range(1, n_epochs + 1):\n print('에포크 {}/{}'.format(epoch, n_epochs))\n for step in range(1, n_steps + 1):\n X_batch, y_batch = random_batch(X_train_scaled, y_train)\n with tf.GradientTape() as tape:\n y_pred = model(X_batch, training=True)\n main_loss = tf.reduce_mean(loss_fn(y_batch, y_pred))\n loss = tf.add_n([main_loss] + model.losses)\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n mean_loss(loss)\n for metric in metrics:\n metric(y_batch, y_pred)\n print_status_bar(step * batch_size, len(y_train), mean_loss, metrics)\n print_status_bar(len(y_train), len(y_train), mean_loss, metrics)\n for metric in [mean_loss] + metrics:\n metric.reset_states()", "_____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" ] ]
cb66a7148bb982a61dcf1a682484c7ed0cf29990
41,692
ipynb
Jupyter Notebook
general studies/learning python/5. Регулярные выражения.ipynb
Diyago/ML-DL-scripts
40718a9d4318d6d6531bcea5998c0a18afcd9cb3
[ "Apache-2.0" ]
142
2018-09-02T08:59:45.000Z
2022-03-30T17:08:24.000Z
general studies/learning python/5. Регулярные выражения.ipynb
Diyago/ML-DL-scripts
40718a9d4318d6d6531bcea5998c0a18afcd9cb3
[ "Apache-2.0" ]
4
2019-09-08T07:27:11.000Z
2021-10-19T05:50:24.000Z
general studies/learning python/5. Регулярные выражения.ipynb
Diyago/ML-DL-scripts
40718a9d4318d6d6531bcea5998c0a18afcd9cb3
[ "Apache-2.0" ]
75
2018-10-04T17:08:40.000Z
2022-03-08T18:50:52.000Z
30.951745
511
0.527679
[ [ [ "*Регулярное выражение* — это последовательность символов, используемая для поиска и замены текста в строке или файле", "_____no_output_____" ], [ "Регулярные выражения используют два типа символов:\n\n- специальные символы: как следует из названия, у этих символов есть специальные значения. Аналогично символу *, который как правило означает «любой символ» (но в регулярных выражениях работает немного иначе, о чем поговорим ниже);\n\n- литералы (например: a, b, 1, 2 и т. д.).", "_____no_output_____" ] ], [ [ "# Реализовано тут\nimport re", "_____no_output_____" ], [ "help(re)", "Help on module re:\n\nNAME\n re - Support for regular expressions (RE).\n\nDESCRIPTION\n This module provides regular expression matching operations similar to\n those found in Perl. It supports both 8-bit and Unicode strings; both\n the pattern and the strings being processed can contain null bytes and\n characters outside the US ASCII range.\n \n Regular expressions can contain both special and ordinary characters.\n Most ordinary characters, like \"A\", \"a\", or \"0\", are the simplest\n regular expressions; they simply match themselves. You can\n concatenate ordinary characters, so last matches the string 'last'.\n \n The special characters are:\n \".\" Matches any character except a newline.\n \"^\" Matches the start of the string.\n \"$\" Matches the end of the string or just before the newline at\n the end of the string.\n \"*\" Matches 0 or more (greedy) repetitions of the preceding RE.\n Greedy means that it will match as many repetitions as possible.\n \"+\" Matches 1 or more (greedy) repetitions of the preceding RE.\n \"?\" Matches 0 or 1 (greedy) of the preceding RE.\n *?,+?,?? Non-greedy versions of the previous three special characters.\n {m,n} Matches from m to n repetitions of the preceding RE.\n {m,n}? Non-greedy version of the above.\n \"\\\\\" Either escapes special characters or signals a special sequence.\n [] Indicates a set of characters.\n A \"^\" as the first character indicates a complementing set.\n \"|\" A|B, creates an RE that will match either A or B.\n (...) Matches the RE inside the parentheses.\n The contents can be retrieved or matched later in the string.\n (?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below).\n (?:...) Non-grouping version of regular parentheses.\n (?P<name>...) The substring matched by the group is accessible by name.\n (?P=name) Matches the text matched earlier by the group named name.\n (?#...) A comment; ignored.\n (?=...) Matches if ... matches next, but doesn't consume the string.\n (?!...) Matches if ... doesn't match next.\n (?<=...) Matches if preceded by ... (must be fixed length).\n (?<!...) Matches if not preceded by ... (must be fixed length).\n (?(id/name)yes|no) Matches yes pattern if the group with id/name matched,\n the (optional) no pattern otherwise.\n \n The special sequences consist of \"\\\\\" and a character from the list\n below. If the ordinary character is not on the list, then the\n resulting RE will match the second character.\n \\number Matches the contents of the group of the same number.\n \\A Matches only at the start of the string.\n \\Z Matches only at the end of the string.\n \\b Matches the empty string, but only at the start or end of a word.\n \\B Matches the empty string, but not at the start or end of a word.\n \\d Matches any decimal digit; equivalent to the set [0-9] in\n bytes patterns or string patterns with the ASCII flag.\n In string patterns without the ASCII flag, it will match the whole\n range of Unicode digits.\n \\D Matches any non-digit character; equivalent to [^\\d].\n \\s Matches any whitespace character; equivalent to [ \\t\\n\\r\\f\\v] in\n bytes patterns or string patterns with the ASCII flag.\n In string patterns without the ASCII flag, it will match the whole\n range of Unicode whitespace characters.\n \\S Matches any non-whitespace character; equivalent to [^\\s].\n \\w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]\n in bytes patterns or string patterns with the ASCII flag.\n In string patterns without the ASCII flag, it will match the\n range of Unicode alphanumeric characters (letters plus digits\n plus underscore).\n With LOCALE, it will match the set [0-9_] plus characters defined\n as letters for the current locale.\n \\W Matches the complement of \\w.\n \\\\ Matches a literal backslash.\n \n This module exports the following functions:\n match Match a regular expression pattern to the beginning of a string.\n fullmatch Match a regular expression pattern to all of a string.\n search Search a string for the presence of a pattern.\n sub Substitute occurrences of a pattern found in a string.\n subn Same as sub, but also return the number of substitutions made.\n split Split a string by the occurrences of a pattern.\n findall Find all occurrences of a pattern in a string.\n finditer Return an iterator yielding a match object for each match.\n compile Compile a pattern into a RegexObject.\n purge Clear the regular expression cache.\n escape Backslash all non-alphanumerics in a string.\n \n Some of the functions in this module takes flags as optional parameters:\n A ASCII For string patterns, make \\w, \\W, \\b, \\B, \\d, \\D\n match the corresponding ASCII character categories\n (rather than the whole Unicode categories, which is the\n default).\n For bytes patterns, this flag is the only available\n behaviour and needn't be specified.\n I IGNORECASE Perform case-insensitive matching.\n L LOCALE Make \\w, \\W, \\b, \\B, dependent on the current locale.\n M MULTILINE \"^\" matches the beginning of lines (after a newline)\n as well as the string.\n \"$\" matches the end of lines (before a newline) as well\n as the end of the string.\n S DOTALL \".\" matches any character at all, including the newline.\n X VERBOSE Ignore whitespace and comments for nicer looking RE's.\n U UNICODE For compatibility only. Ignored for string patterns (it\n is the default), and forbidden for bytes patterns.\n \n This module also defines an exception 'error'.\n\nCLASSES\n builtins.Exception(builtins.BaseException)\n sre_constants.error\n \n class error(builtins.Exception)\n | Common base class for all non-exit exceptions.\n | \n | Method resolution order:\n | error\n | builtins.Exception\n | builtins.BaseException\n | builtins.object\n | \n | Methods defined here:\n | \n | __init__(self, msg, pattern=None, pos=None)\n | Initialize self. See help(type(self)) for accurate signature.\n | \n | ----------------------------------------------------------------------\n | Data descriptors defined here:\n | \n | __weakref__\n | list of weak references to the object (if defined)\n | \n | ----------------------------------------------------------------------\n | Methods inherited from builtins.Exception:\n | \n | __new__(*args, **kwargs) from builtins.type\n | Create and return a new object. See help(type) for accurate signature.\n | \n | ----------------------------------------------------------------------\n | Methods inherited from builtins.BaseException:\n | \n | __delattr__(self, name, /)\n | Implement delattr(self, name).\n | \n | __getattribute__(self, name, /)\n | Return getattr(self, name).\n | \n | __reduce__(...)\n | helper for pickle\n | \n | __repr__(self, /)\n | Return repr(self).\n | \n | __setattr__(self, name, value, /)\n | Implement setattr(self, name, value).\n | \n | __setstate__(...)\n | \n | __str__(self, /)\n | Return str(self).\n | \n | with_traceback(...)\n | Exception.with_traceback(tb) --\n | set self.__traceback__ to tb and return self.\n | \n | ----------------------------------------------------------------------\n | Data descriptors inherited from builtins.BaseException:\n | \n | __cause__\n | exception cause\n | \n | __context__\n | exception context\n | \n | __dict__\n | \n | __suppress_context__\n | \n | __traceback__\n | \n | args\n\nFUNCTIONS\n compile(pattern, flags=0)\n Compile a regular expression pattern, returning a pattern object.\n \n escape(pattern)\n Escape all the characters in pattern except ASCII letters, numbers and '_'.\n \n findall(pattern, string, flags=0)\n Return a list of all non-overlapping matches in the string.\n \n If one or more capturing groups are present in the pattern, return\n a list of groups; this will be a list of tuples if the pattern\n has more than one group.\n \n Empty matches are included in the result.\n \n finditer(pattern, string, flags=0)\n Return an iterator over all non-overlapping matches in the\n string. For each match, the iterator returns a match object.\n \n Empty matches are included in the result.\n \n fullmatch(pattern, string, flags=0)\n Try to apply the pattern to all of the string, returning\n a match object, or None if no match was found.\n \n match(pattern, string, flags=0)\n Try to apply the pattern at the start of the string, returning\n a match object, or None if no match was found.\n \n purge()\n Clear the regular expression caches\n \n search(pattern, string, flags=0)\n Scan through string looking for a match to the pattern, returning\n a match object, or None if no match was found.\n \n split(pattern, string, maxsplit=0, flags=0)\n Split the source string by the occurrences of the pattern,\n returning a list containing the resulting substrings. If\n capturing parentheses are used in pattern, then the text of all\n groups in the pattern are also returned as part of the resulting\n list. If maxsplit is nonzero, at most maxsplit splits occur,\n and the remainder of the string is returned as the final element\n of the list.\n \n sub(pattern, repl, string, count=0, flags=0)\n Return the string obtained by replacing the leftmost\n non-overlapping occurrences of the pattern in string by the\n replacement repl. repl can be either a string or a callable;\n if a string, backslash escapes in it are processed. If it is\n a callable, it's passed the match object and must return\n a replacement string to be used.\n \n subn(pattern, repl, string, count=0, flags=0)\n Return a 2-tuple containing (new_string, number).\n new_string is the string obtained by replacing the leftmost\n non-overlapping occurrences of the pattern in the source\n string by the replacement repl. number is the number of\n substitutions that were made. repl can be either a string or a\n callable; if a string, backslash escapes in it are processed.\n If it is a callable, it's passed the match object and must\n return a replacement string to be used.\n \n template(pattern, flags=0)\n Compile a template pattern, returning a pattern object\n\nDATA\n A = <RegexFlag.ASCII: 256>\n ASCII = <RegexFlag.ASCII: 256>\n DOTALL = <RegexFlag.DOTALL: 16>\n I = <RegexFlag.IGNORECASE: 2>\n IGNORECASE = <RegexFlag.IGNORECASE: 2>\n L = <RegexFlag.LOCALE: 4>\n LOCALE = <RegexFlag.LOCALE: 4>\n M = <RegexFlag.MULTILINE: 8>\n MULTILINE = <RegexFlag.MULTILINE: 8>\n S = <RegexFlag.DOTALL: 16>\n U = <RegexFlag.UNICODE: 32>\n UNICODE = <RegexFlag.UNICODE: 32>\n VERBOSE = <RegexFlag.VERBOSE: 64>\n X = <RegexFlag.VERBOSE: 64>\n __all__ = ['match', 'fullmatch', 'search', 'sub', 'subn', 'split', 'fi...\n\nVERSION\n 2.2.1\n\nFILE\n c:\\users\\user\\anaconda3\\lib\\re.py\n\n\n" ], [ "re.match() # Try to apply the pattern at the start of the string, returning a match object, or None if no match was found.\n\nre.search() # Scan through string looking for a match to the pattern, returning a match object, or None if no match was found.\n\nre.findall() # Return a list of all non-overlapping matches in the string.\nre.split() # Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings.\nre.sub() # Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the \n #replacement repl\nre.compile() # Чтобы собрать регулярки в отдельный объект", "_____no_output_____" ] ], [ [ "## re.match(pattern, string):", "_____no_output_____" ] ], [ [ "Этот метод ищет по заданному шаблону в начале строки. Например, если мы вызовем метод match() на строке «AV Analytics AV» с шаблоном «AV», то он завершится успешно. Однако если мы будем искать «Analytics», то результат будет отрицательный. Давайте посмотрим на его работу:", "_____no_output_____" ] ], [ [ "result = re.match('AV', 'AV Analytics Vidhya')\nprint (result)", "<_sre.SRE_Match object; span=(0, 2), match='AV'>\n" ], [ "print (result.start()) # начало и конец найденной подстроки\nprint (result.end())", "0\n2\n" ], [ "result.group(0) # что именно", "_____no_output_____" ], [ "result = re.match(r'Analytics', 'AV Analytics Vidhya AV') \nprint (result)", "None\n" ] ], [ [ "## re.search(pattern, string): ", "_____no_output_____" ] ], [ [ "Этот метод похож на match(), но он ищет не только в начале строки. В отличие от предыдущего, search() вернет объект, если мы попытаемся найти «Analytics».\n\nМетод search() ищет по всей строке, но возвращает только первое найденное совпадение.", "_____no_output_____" ] ], [ [ "result = re.search(r'AV', 'AV Analytics Vidhya AV')\nprint (result.group(0))", "AV\n" ], [ "result", "_____no_output_____" ] ], [ [ "## re.findall(pattern, string):\n", "_____no_output_____" ] ], [ [ "Этот метод возвращает список всех найденных совпадений. У метода findall() нет ограничений на поиск в начале или конце строки. Если мы будем искать «AV» в нашей строке, он вернет все вхождения «AV». Для поиска рекомендуется использовать именно findall(), так как он может работать и как re.search(), и как re.match().", "_____no_output_____" ] ], [ [ "result = re.findall(r'AV', 'AV Analytics Vidhya AV')", "_____no_output_____" ], [ "result", "_____no_output_____" ] ], [ [ "## re.split(pattern, string, [maxsplit=0]):\n", "_____no_output_____" ] ], [ [ "result = re.split(r'y', 'Analytics')\nprint (result) ", "['Anal', 'tics']\n" ] ], [ [ "В примере мы разделили слово «Analytics» по букве «y». Метод split() принимает также аргумент maxsplit со значением по умолчанию, равным 0. В данном случае он разделит строку столько раз, сколько возможно, но если указать этот аргумент, то разделение будет произведено не более указанного количества раз. Давайте посмотрим на примеры:", "_____no_output_____" ] ], [ [ "result = re.split(r'i', 'Analytics Vidhya')\nprint (result) # все возможные участки.\n", "['Analyt', 'cs V', 'dhya']\n" ], [ "result = re.split(r'i', 'Analytics Vidhya',maxsplit=1)\nprint (result)", "['Analyt', 'cs Vidhya']\n" ] ], [ [ "## re.sub(pattern, repl, string):", "_____no_output_____" ] ], [ [ "Этот метод ищет шаблон в строке и заменяет его на указанную подстроку. Если шаблон не найден, строка остается неизменной.", "_____no_output_____" ] ], [ [ "result = re.sub(r'India', 'the World', 'AV is largest Analytics community of India')\nprint (result)", "AV is largest Analytics community of the World\n" ] ], [ [ "## re.compile(pattern, repl, string):", "_____no_output_____" ] ], [ [ "Мы можем собрать регулярное выражение в отдельный объект, который может быть использован для поиска. Это также избавляет от переписывания одного и того же выражения.", "_____no_output_____" ] ], [ [ "pattern = re.compile('AV')\nresult = pattern.findall('AV Analytics Vidhya AV')\nprint (result)", "['AV', 'AV']\n" ], [ "result2 = pattern.findall('AV is largest analytics community of India')\nprint (result2)", "['AV']\n" ] ], [ [ "До сих пор мы рассматривали поиск определенной последовательности символов. Но что, если у нас нет определенного шаблона, и нам надо вернуть набор символов из строки, отвечающий определенным правилам? ", "_____no_output_____" ], [ "Оператор\tОписание\n\n\n\\w\t Любая цифра или буква (\\W — все, кроме буквы или цифры)\n\\d\t Любая цифра [0-9] (\\D — все, кроме цифры)\n\\s\t Любой пробельный символ (\\S — любой непробельнй символ)\n\n\\b\t Граница слова\n\\A соответствует началу текста.\n\\Z соответствует концу текста.\n\\B соответствует границе не слова (re.ASCII)\n\n[..]\t Один из символов в скобках ([^..] — любой символ, кроме тех, что в скобках)\n[0-9] любая цифра\n[a-яА-ЯёЁ] любая русская буква\n[a-zA-Z] любая англ.\n[^3] не цифра 3 \n\\\t Экранирование специальных символов (\\. означает точку или \\+ — знак «плюс»)\n^ и $\t Начало и конец строки соответственно\n{n,m}\t От n до m вхождений ({,m} — от 0 до m)\na|b\t Соответствует a или b\n()\t Группирует выражение и возвращает найденный текст\n\\t, \\n, \\r\tСимвол табуляции, новой строки и возврата каретки соответственно\n\n^ если первый символ в классе, то инверсия.\n- если не первый символ в классе, то диапазон.\n\nre.I (ignore case) Сопоставление без учета регистра; Например, [A-Z] будет также соответствовать и строчным буквам, так что Spam будет соответствовать Spam, spam, spAM и так далее.\n\nre.M (multi-line)( .Обычно ^ ищет соответствие только в начале строки, а $ только в конце непосредственно перед символом новой строки (если таковые имеются). Если этот флаг указан, ^ сравнение происходит во всех строках, то есть и в начале, и сразу же после каждого символа новой строки. Аналогично для $.\n \n \nre.S (dot matches all) Сопоставление, такое же как '.', то есть с любым символом, но при включении этого флага, в рассмотрение добавляется и символ новой строки.\n\nre.X (verbose) Включает многословные (подробные) регулярные выражения, которые могут быть организованы более ясно и понятно. Если указан этот флаг, пробелы в строке регулярного выражения игнорируется, кроме случаев, когда они имеются в классе символов или им предшествует неэкранированный бэкслеш; это позволяет вам организовать регулярные выражения более ясным образом. Этот флаг также позволяет помещать в регулярные выражения комментарии, начинающиеся с '#', которые будут игнорироваться движком.", "_____no_output_____" ] ], [ [ "## Определение количества вхождений", "_____no_output_____" ] ], [ [ ".\t Один любой символ, кроме новой строки \\n.\n?\t 0 или 1 вхождение шаблона слева\n+\t 1 и более вхождений шаблона слева\n*\t 0 и более вхождений шаблона слева\n\ne? или e{0,1} Максимальный, соответствует нулевому или большему числу вхождений выражения e\ne?? или e{0,1}? Минимальный, соответствует нулевому или большему числу вхождений выражения e\ne+ или e{1,} Максимальный, соответствует одному или больше вхождению выражения e\ne+? или e{1,}? Минимальный, соответствует одному или больше вхождению выражения e\ne* или e{0,} Максимальный, соответствует нулевому или большему числу вхождений выражения e\ne*? или e{0,}? Минимальный, соответствует нулевому или большему числу вхождений выражения e\ne{m} Соответствует точно m вхождениям выражения e\ne{m,} Максимальный, соответствует по меньшей мере m вхождениям выражения e\ne{m,}? Минимальный, соответствует по меньшей мере m вхождениям выражения e\ne{,n} Максимальный, соответствует не более чем n вхождениям выражения e\ne{,n}? Минимальный, соответствует не более чем n вхождениям выражения e\ne{m,n} Максимальный, соответствует не менее чем m и не более чем n вхождениям выражения e\ne{m,n}? Минимальный, соответствует не менее чем m и не более чем n вхождениям выражения e", "_____no_output_____" ] ], [ [ "import re\n\nc = re.compile(r'[0-9]+?')\nstr = '32 43 23423424'\nprint(re.findall(c, str))", "['3', '2', '4', '3', '2', '3', '4', '2', '3', '4', '2', '4']\n" ], [ "# Пример 1. Как получить все числа из строки\n\nprice = '324234dfgdg34234DFDJ343'\nb = \"[a-zA-Z]*\" # регулярное выражение для последовательности букв любой длины\nnums = re.sub(b,\"\",price)\nprint (nums)", "32423434234343\n" ] ], [ [ "### Задача 1", "_____no_output_____" ] ], [ [ "#попробуем вытащить каждый символ (используя .)\n", "_____no_output_____" ], [ "# в конечный результат не попал пробел", "_____no_output_____" ], [ "# Теперь вытащим первое слово", "_____no_output_____" ], [ "# А теперь вытащим первое слово", "_____no_output_____" ] ], [ [ "### Задача 2", "_____no_output_____" ] ], [ [ "#используя \\w, вытащить два последовательных символа, кроме пробельных, из каждого слова\n", "_____no_output_____" ], [ "# вытащить два последовательных символа, используя символ границы слова (\\b)", "_____no_output_____" ] ], [ [ "### Задача 3 \n\nвернуть список доменов из списка адресов электронной почты", "_____no_output_____" ] ], [ [ "#Сначала вернем все символы после «@»:", "_____no_output_____" ], [ "str = '[email protected], [email protected], [email protected], [email protected] [email protected]@@'", "_____no_output_____" ], [ "#Если части «.com», «.in» и т. д. не попали в результат. Изменим наш код:", "_____no_output_____" ], [ "# вытащить только домен верхнего уровня, используя группировку — ( )", "_____no_output_____" ], [ "# Получить список почтовых адресов", "_____no_output_____" ] ], [ [ "### Задача 4: \n\n", "_____no_output_____" ] ], [ [ "# Извлечь дату из строки", "_____no_output_____" ], [ "str = 'Amit 34-3456 12-05-2007, XYZ 56-4532 11-11-2011, ABC 67-8945 12-01-2009'", "_____no_output_____" ], [ "#А теперь только года, с помощью скобок и группировок: ", "_____no_output_____" ] ], [ [ "### Задача 5", "_____no_output_____" ] ], [ [ "#Извлечь все слова, начинающиеся на гласную. Но сначала получить все слова (\\b - границы слов)", "_____no_output_____" ] ], [ [ "### Задача 6: \nПроверить телефонный номер (номер должен быть длиной 10 знаков и начинаться с 8 или 9)", "_____no_output_____" ] ], [ [ "li = ['9999999999', '999999-999', '99999x9999']\n\nfor val in li:\n print()", "\n\n\n" ] ], [ [ "### Задача 7: \nРазбить строку по нескольким разделителям\n", "_____no_output_____" ] ], [ [ "line = 'asdf fjdk;afed,fjek,asdf,foo' # String has multiple delimiters (\";\",\",\",\" \").", "_____no_output_____" ] ], [ [ "# Жадный против нежадного", "_____no_output_____" ] ], [ [ "При повторении в РВ, таком как a*, результирующее действие съедает настолько большую часть шаблона, насколько это возможно. На этом часто обжигаются те, кто хочет найти пару симметричных определителей, таких как угловые скобки <>, окружающие HTML-теги. Наивный подход к шаблону сопоставления тега HTML не будет работать из-за «жадного» характера .*:\n", "_____no_output_____" ] ], [ [ "s = '<html><head><title>Title</title>'\nprint (len(s))", "32\n" ], [ "print (re.match('<.*>', s).span())", "(0, 32)\n" ], [ "print (re.match('<.*>', s).group())", "<html><head><title>Title</title>\n" ] ], [ [ "В таком случае, решение заключается в использовании нежадных определителей *?, +?, ?? или {m,n}?, которые сопоставляют так мало текста, как это возможно. В примере выше, будет выбран первый символ '>' после '<', и только, если не получится, движок будет продолжать попытки найти символ '>' на следующей позиции, в зависимости от того, как длинно имя тега. Это дает нужный результат:\n", "_____no_output_____" ] ], [ [ "print re.match('<.*?>', s).group()", "_____no_output_____" ], [ "c = re.compile(r'\\d+')\nstr = '0123456789'\ntuples = re.findall(c, str)\nprint(tuples)", "['0123456789']\n" ], [ "#Но как сделать так, чтобы получить каждой отдельное число", "_____no_output_____" ] ], [ [ "## Разное", "_____no_output_____" ], [ "### Просмотр с возращением", "_____no_output_____" ] ], [ [ "# (?=e) - совпадение обнаруживается, усли текст справа от позиции проверки соответствует выражению e, \n при этом изменения позиции поиска в тексте не происходит.\n Эта проверка называется опережающей проверкой, или позитивной опережающей проверкой.\n Например выражение: \\w+(?=\\s+)\n найдет слово, за которым стоит один или несколько пробельных символов.\n\n(?!e) - совпадение обнаруживается, если текст справа от позиции проверки не соответствует выражению e, \n при этом изменения позиции поиска в тексте не происходит.\n Эта проверка называется негативной опережающей проверкой.\n\n(?<=e) - совпадение обнаруживается, если текст слева от позиции проверки соответствует выражению e,\n эта проверка называется позитивной ретроспективной проверкой.\n\n(?<!e) - совпадение обнаруживается, если текст слева от позиции проверки не соответствует выражению e,\n эта проверка называется негативной ретроспективной проверкой.", "_____no_output_____" ] ], [ [ "#(?=...) - положительный просмотр вперед\n\ns = \"textl, text2, textЗ text4\"\np = re.compile(r\"\\w+(?=[,])\", re.S | re.I) # все слова, после которых есть запятая\nprint (p.findall(s))\n", "['textl', 'text2']\n" ], [ "#(?!...) - отрицательный просмотр вперед\nimport re\ns = \"textl, text2, textЗ text4\"\np = re.compile(r\"[a-z]+[0-9](?![,])\", re.S | re.I) # все слова, после которых нет запятой\nprint(p.findall(s))", "['text4']\n" ], [ "#(?<=...) - положительный просмотр назад\nimport re\ns = \"textl, text2, textЗ text4\"\np = re.compile(r\"(?<=[,][ ])([a-z]+[0-9])\", re.S | re.I) # все слова, перед которыми есть запятая с пробелм\nprint (p.findall(s) )", "['text2']\n" ], [ "#(?<!...) - отрицательный просмотр назад\n\ns = \"textl, text2, textЗ text4\"\np = re.compile(r\"(?<![,]) ([a-z]+[0-9])\", re.S | re.I) # все слова, перед которыми есть пробел но нет запятой\nprint (p.findall(s))", "['text4']\n" ], [ "#Дано текст: \nstr = 'ruby python 456 java 789 j2not clash2win'\n#Задача: Найти все упоминания языков программирования в строке.\npattern = 'ruby|java|python|c#|fortran|c\\+\\+'\nstring = 'ruby python 456 java 789 j2not clash2win'\nre.findall(pattern, string)", "_____no_output_____" ] ], [ [ "## Определитесь, нужны ли вам регулярные выражения для данной задачи. Возможно, получится гораздо быстрее, если вы примените другой способ решения.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "raw", "code", "markdown", "raw", "code", "markdown", "raw", "code", "markdown", "code", "raw", "code", "markdown", "raw", "code", "markdown", "raw", "code", "raw", "markdown", "raw", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "raw", "code", "raw", "code", "markdown", "raw", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "raw" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "raw" ], [ "code", "code" ], [ "markdown" ], [ "raw" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "raw" ], [ "code", "code" ], [ "markdown" ], [ "raw" ], [ "code" ], [ "markdown" ], [ "raw" ], [ "code", "code" ], [ "raw", "raw" ], [ "markdown" ], [ "raw" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "raw" ], [ "code", "code", "code" ], [ "raw" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "raw" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ] ]
cb66a9074a3f03e7e81f42c221cdce9f3be6a1fd
2,019
ipynb
Jupyter Notebook
project/NNTest2.ipynb
SJSlavin/phys202-project
bc81aebefd38b4c31e10d95fe46277a707cb0e6d
[ "MIT" ]
null
null
null
project/NNTest2.ipynb
SJSlavin/phys202-project
bc81aebefd38b4c31e10d95fe46277a707cb0e6d
[ "MIT" ]
null
null
null
project/NNTest2.ipynb
SJSlavin/phys202-project
bc81aebefd38b4c31e10d95fe46277a707cb0e6d
[ "MIT" ]
null
null
null
23.206897
66
0.474492
[ [ [ "import numpy as np", "_____no_output_____" ], [ "\n#http://natureofcode.com/book/chapter-10-neural-networks/\n#translated into python\nclass Perceptron(object):\n def __init__(self, weights, lc):\n self.weights = weights\n self.lc = lc\n def createweights(self, n):\n weights = (np.random.rand(n) * 2) - 1\n def feedforward(self, inputs):\n sum_ = 0\n for n in range(len(inputs)):\n sum_ += inputs[n]*weights[n]\n return activate(sum_)\n def activate(self, sum_):\n if sum_ > 0:\n return 1\n else:\n return -1\n def train(self, inputs, expected):\n guess = feedforward(inputs)\n error = desired - guess\n for n in range(len(weights)):\n weights[n] += lc * error * inputs[n]\n\nclass Trainer(object):\n def __init__(self, inputs, answer):\n \n \ndef func(x):\n return 2*x + 1\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
cb66b2c00f5d387bd30d37806d9fbea12a81a583
204,273
ipynb
Jupyter Notebook
app_reviews/app_reviews_scattertext.ipynb
labs15-rv-life/data-science
297b43b248d5e07463ce555713ff97f64312b5ff
[ "MIT" ]
null
null
null
app_reviews/app_reviews_scattertext.ipynb
labs15-rv-life/data-science
297b43b248d5e07463ce555713ff97f64312b5ff
[ "MIT" ]
1
2021-06-02T00:23:07.000Z
2021-06-02T00:23:07.000Z
app_reviews/app_reviews_scattertext.ipynb
labs15-rv-life/data-science
297b43b248d5e07463ce555713ff97f64312b5ff
[ "MIT" ]
2
2019-08-21T00:11:51.000Z
2019-09-17T20:27:37.000Z
34.657788
601
0.283454
[ [ [ "import pandas as pd", "_____no_output_____" ], [ "ios = pd.read_csv('app_reviews/rv_ios_app_reviews.csv')\nios['Content'] = ios['label_title']+ios['review']\nios = ios.drop(['app_name','app_version','label_title','review'], axis=1)\nprint(ios.shape)\nios.head()", "(1962, 2)\n" ], [ "ios['store_rating'].value_counts()", "_____no_output_____" ], [ "android = pd.read_csv('app_reviews/rv_android_reviews.csv')\n# android = android.drop(['Unnamed: 0','Unnamed: 0.1','Date','App_name'], axis=1)\n# android = android.rename(columns={'Numbers':'store_rating'})\nprint(android.shape)\nandroid.head()", "(639, 2)\n" ], [ "android = pd.read_csv('app_reviews/rv_android_reviews.csv')\n# android = android.drop(['Unnamed: 0','Unnamed: 0.1','Date','App_name'], axis=1)\n# android = android.rename(columns={'Numbers':'store_rating'})\nprint(android.shape)\nandroid.head()", "(6746, 6)\n" ], [ "android['Star'].value_counts()", "_____no_output_____" ], [ "df = pd.concat([android, ios], join='outer', ignore_index=True, axis=0, sort=True)\nprint(df.shape)\ndf.head()", "(2601, 2)\n" ], [ "df.isnull().sum()", "_____no_output_____" ], [ "df['store_rating'].value_counts()", "_____no_output_____" ], [ "df['rating'] = df['store_rating'].replace({4:5, 2:1, 3:1}).astype(float).astype(str)\n# df['rating'] = df['store_rating']\n# df['rating'] = df['rating']\ndf['rating'].value_counts()", "_____no_output_____" ], [ "df.dtypes", "_____no_output_____" ], [ "import spacy\nimport scattertext\nimport pandas as pd\npd.set_option('display.max_columns', 500) # Make sure we can see all of the columns\npd.set_option('display.max_rows', 200)", "_____no_output_____" ], [ "nlp = spacy.load(\"en_core_web_lg\")", "_____no_output_____" ], [ "# add stop words\nwith open('stopwords.txt', 'r') as f:\n str = f.read()\n set_stopwords = set(str.split('\\n'))\nnlp.Defaults.stop_words |= set_stopwords", "_____no_output_____" ], [ "corpus = (scattertext.CorpusFromPandas(Shopping_yelp_sample, \n category_col='rating', \n text_col='Content',\n nlp=nlp)\n .build()\n .remove_terms(nlp.Defaults.stop_words, ignore_absences=True)\n )", "_____no_output_____" ], [ "term_freq_df = corpus.get_term_freq_df()\nterm_freq_df['highratingscore'] = corpus.get_scaled_f_scores('5.0')\nterm_freq_df['poorratingscore'] = corpus.get_scaled_f_scores('1.0')\n\ndf_high = term_freq_df.sort_values(by='highratingscore', \n ascending = False)\ndf_poor = term_freq_df.sort_values(by='poorratingscore', \n ascending=False)\n\n# df_high = df_high[['highratingscore', 'poorratingscore']]\ndf_high['highratingscore'] = round(df_high['highratingscore'], 2)\ndf_high['poorratingscore'] = round(df_high['poorratingscore'], 2)\ndf_high = df_high.reset_index(drop=False)\n# df_high = df_high.head(20)\n\n# df_poor = df_poor[['highratingscore', 'poorratingscore']]\ndf_poor['highratingscore'] = round(df_poor['highratingscore'], 2)\ndf_poor['poorratingscore'] = round(df_poor['poorratingscore'], 2)\ndf_poor = df_poor.reset_index(drop=False)\n# df_poor = df_poor.head(20)\n\n# df_terms = pd.concat([df_high, df_poor],\n# ignore_index=True)\n# df_terms", "_____no_output_____" ], [ "Shopping_yelp_sample_high = df_high\nShopping_yelp_sample_poor = df_poor", "_____no_output_____" ], [ "Shopping_yelp_sample_high.sort_values(by='5.0 freq', ascending = False).head(100)", "_____no_output_____" ], [ "Shopping_yelp_sample_poor.sort_values(by='1.0 freq', ascending = False).head(100)", "_____no_output_____" ], [ "Auto_Repair_yelp_high.sort_values(by='5.0 freq', ascending = False).head(100)", "_____no_output_____" ], [ "Auto_Repair_yelp_poor.sort_values(by='1.0 freq', ascending = False).head(100)", "_____no_output_____" ], [ "Hair_Salons_yelp_high.sort_values(by='5.0 freq', ascending = False).head(100)", "_____no_output_____" ], [ "Hair_Salons_yelp_poor.sort_values(by='1.0 freq', ascending = False).head(100)", "_____no_output_____" ], [ "Fashion_yelp_high.sort_values(by='5.0 freq', ascending = False)", "_____no_output_____" ], [ "Fashion_yelp_poor.sort_values(by='1.0 freq', ascending = False).head(100)", "_____no_output_____" ], [ "Professional_Services_yelp_poor_json = Professional_Services_yelp_poor_json.drop([136,3577,2707,664626,1979,2678])\nProfessional_Services_yelp_poor_json.sort_values(by='1 freq', ascending = False).head(10)", "_____no_output_____" ], [ "Professional_Services_yelp_poor.sort_values(by='1 freq', ascending = False).head(100)", "_____no_output_____" ], [ "Professional_Services_yelp_high_json = Professional_Services_yelp_high_json.drop([1777])\nProfessional_Services_yelp_best_json = Professional_Services_yelp_high_json.sort_values(by='5 freq', ascending = False).head()", "_____no_output_____" ], [ "Professional_Services_yelp_high.sort_values(by='5 freq', ascending = False).head()\nProfessional_Services_yelp_poor_json.sort_values(by='1 freq', ascending = False).head()", "_____no_output_____" ], [ "df = df.head()\ndf.to_json('Fashion_yelp_high_rating_words.json', orient='records', lines=True)", "_____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" ] ]
cb66bdb34ca3f191a401ba51c5e46c6952133e5c
8,440
ipynb
Jupyter Notebook
pytorch/nn_practice.ipynb
WNoxchi/Kawkasos
42c5070a8fa4a5e2d6386dc19d385e82a1d73fb2
[ "MIT" ]
7
2017-07-28T06:17:29.000Z
2021-03-19T08:43:07.000Z
pytorch/nn_practice.ipynb
WNoxchi/Kawkasos
42c5070a8fa4a5e2d6386dc19d385e82a1d73fb2
[ "MIT" ]
null
null
null
pytorch/nn_practice.ipynb
WNoxchi/Kawkasos
42c5070a8fa4a5e2d6386dc19d385e82a1d73fb2
[ "MIT" ]
1
2018-06-17T12:08:25.000Z
2018-06-17T12:08:25.000Z
26.049383
253
0.534597
[ [ [ "Define the network:", "_____no_output_____" ] ], [ [ "import torch # PyTorch base\nfrom torch.autograd import Variable # Tensor class w gradients\nimport torch.nn as nn # modules, layers, loss fns\nimport torch.nn.functional as F # Conv,Pool,Loss,Actvn,Nrmlz fns from here", "_____no_output_____" ], [ "class Net(nn.Module):\n \n def __init__(self):\n super(Net, self).__init__()\n # 1 input image channel, 6 output channels, 5x5 square convolution\n # Kernel\n self.conv1 = nn.Conv2d(1, 6, 5)\n self.conv2 = nn.Conv2d(6, 16, 5)\n # an Affine Operation: y = Wx + b\n self.fc1 = nn.Linear(16*5*5, 120) # Linear is Dense/Fully-Connected\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n \n def forward(self, x):\n # Max pooling over a (2, 2) window\n # x = torch.nn.functional.max_pool2d(torch.nn.functional.relu(self.conv1(x)), (2,2))\n x = F.max_pool2d(F.relu(self.conv1(x)), (2,2))\n # If size is a square you can only specify a single number\n x = F.max_pool2d(F.relu(self.conv2(x)), 2)\n x = x.view(-1, self.num_flat_features(x))\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n \n def num_flat_features(self, x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features", "_____no_output_____" ], [ "net = Net()\nprint(net)", "Net(\n (conv1): Conv2d (1, 6, kernel_size=(5, 5), stride=(1, 1))\n (conv2): Conv2d (6, 16, kernel_size=(5, 5), stride=(1, 1))\n (fc1): Linear(in_features=400, out_features=120)\n (fc2): Linear(in_features=120, out_features=84)\n (fc3): Linear(in_features=84, out_features=10)\n)\n" ] ], [ [ "You just have to define the `forward` function, and the `backward` function (where the gradients are computed) is automatically defined for you using `autograd`. You can use any of the Tensor operations in the `forward` function.\n\nThe learnable parameteres of a model are returns by `net.parameters()`", "_____no_output_____" ] ], [ [ "pars = list(net.parameters())\nprint(len(pars))\nprint(pars[0].size()) # conv1's .weight", "10\ntorch.Size([6, 1, 5, 5])\n" ] ], [ [ "The input to the forward is an `autograd.Variable`, and so is the output. **NOTE**: Expected input size to this net(LeNet) is 32x32. To use this net on MNIST dataset, please resize the images from the dataset to 32x32.", "_____no_output_____" ] ], [ [ "input = Variable(torch.randn(1, 1, 32, 32))\nout = net(input)\nprint(out)", "Variable containing:\n 0.1121 0.1057 0.1048 0.0035 0.0175 -0.0641 0.0898 -0.0121 0.0252 0.0690\n[torch.FloatTensor of size 1x10]\n\n" ] ], [ [ "Zero the gradient buffers of all parameters and backprops with random gradients:", "_____no_output_____" ] ], [ [ "net.zero_grad()\nout.backward(torch.randn(1, 10))", "_____no_output_____" ] ], [ [ "**!NOTE¡**:\n\n`torch.nn` only supports mini-batches. The entire `torch.nn` package only supports inputs that are a mini-batch of samples, and not a single sample.\n\nFor example, `nn.Conv2d` will take in a 4D Tensor of `nSamples x nChannels x Height x Width`.\n\nIf you have a single sample, just use `input.unsqueeze(0)` to add a fake batch dimension.", "_____no_output_____" ], [ "Before proceeding further, let's recap all the classes you've seen so far.\n\n**Recap**:\n\n* `torch.Tensor` - A *multi-dimensional array*.\n* `autograd.Variable` - *Wraps a Tensor and records the history of operations* applied to it. Has the same API as a `Tensor`, with some additions like `backward()`. Also *holds the gradient* wrt the tensor.\n* `nn.Module` - Neural network module. *Convenient way of encapsulating parameters*, with helpers for moving them to GPU, exporting, loading, etc.\n* `nn.Parameter` - A kind of Variable, that is *automatically registered as a parameter when assigned as an attribute to a* `Module`.\n* `autograd.Function` - Implements *forward and backward definitions of an autograd operation*. Every `Variable` operation creates at least a single `Function` node that connects to functions that created a `Variable` and *encodes its history*.\n\n**At this point, we covered:**\n* Defining a neural network\n* Processing inputs and calling backward.\n\n**Still Left:**\n* Computing the loss\n* Updating the weights of the network", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cb66be086376300f652edd6b877d3f7c8638b64e
29,750
ipynb
Jupyter Notebook
sagetrain/container/customkeras/train.ipynb
aws-samples/robocarrally
fb388b80f9224fd32a971b24d96fc1e4066329f0
[ "Apache-2.0" ]
11
2017-11-29T06:16:39.000Z
2021-12-24T01:41:39.000Z
sagetrain/container/customkeras/train.ipynb
aws-samples/robocarrally
fb388b80f9224fd32a971b24d96fc1e4066329f0
[ "Apache-2.0" ]
null
null
null
sagetrain/container/customkeras/train.ipynb
aws-samples/robocarrally
fb388b80f9224fd32a971b24d96fc1e4066329f0
[ "Apache-2.0" ]
12
2017-11-28T02:58:27.000Z
2021-10-30T01:53:05.000Z
42.744253
245
0.467664
[ [ [ "import os\nimport numpy as np\nimport keras\nimport tensorflow as tf\nimport pandas as pd\nimport glob\nimport json\nimport random\nimport time\nfrom PIL import Image\n\nBATCH_SIZE = 128\nTRAINING_SPLIT = 0.8\nEPOCHS = 20\n\nprefix = '/opt/ml/'\ninput_path = prefix + 'input/data'\noutput_path = os.path.join(prefix, 'output')\nmodel_path = os.path.join(prefix, 'model')\nparam_path = os.path.join(prefix, 'input/config/hyperparameters.json')\n\nmodel_loc = os.path.join(model_path, 'car-model.pkl')\n\n# This algorithm has a single channel of input data called 'training'. Since we run in\n# File mode, the input files are copied to the directory specified here.\nchannel_name='training'\ntraining_path = os.path.join(input_path, channel_name)\n\nINPUT_TENSOR_NAME = \"inputs\"\nSIGNATURE_NAME = \"serving_default\"\nLEARNING_RATE = 0.001\n\ndef train():\n\n print('Starting the training.')\n try:\n # Read in any hyperparameters that the user passed with the training job\n with open(param_path, 'r') as tc:\n trainingParams = json.load(tc)\n\n input_files = [ os.path.join(training_path, file) for file in os.listdir(training_path) ]\n if len(input_files) == 0:\n raise ValueError(('There are no files in {}.\\n' +\n 'This usually indicates that the channel ({}) was incorrectly specified,\\n' +\n 'the data specification in S3 was incorrectly specified or the role specified\\n' +\n 'does not have permission to access the data.').format(training_path, channel_name))\n\n tubgroup = TubGroup(input_path)\n\n\n total_records = len(tubgroup.df)\n total_train = int(total_records * TRAINING_SPLIT)\n total_val = total_records - total_train\n steps_per_epoch = total_train // BATCH_SIZE\n X_keys = ['cam/image_array']\n y_keys = ['user/angle', 'user/throttle']\n train_gen, val_gen = tubgroup.get_train_val_gen(X_keys, y_keys, record_transform=rt,\n batch_size=BATCH_SIZE,\n train_frac=TRAINING_SPLIT)\n save_best = keras.callbacks.ModelCheckpoint(model_loc, \n monitor='val_loss', \n verbose=1, \n save_best_only=True, \n mode='min')\n\n #stop training if the validation error stops improving.\n early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', \n min_delta=0.0005, \n patience=5, \n verbose=1, \n mode='auto')\n callbacks_list = [save_best]\n callbacks_list.append(early_stop)\n model = default_categorical()\n hist = model.fit_generator(\n train_gen, \n steps_per_epoch=11, \n epochs=EPOCHS, \n verbose=1, \n validation_data=val_gen,\n callbacks=callbacks_list, \n validation_steps=11*(1.0 - TRAINING_SPLIT))\n print('Training complete.')\n \n except Exception as e:\n # Write out an error file. This will be returned as the failureReason in the\n # DescribeTrainingJob result.\n trc = traceback.format_exc()\n with open(os.path.join(output_path, 'failure'), 'w') as s:\n s.write('Exception during training: ' + str(e) + '\\n' + trc)\n # Printing this causes the exception to be in the training job logs, as well.\n print('Exception during training: ' + str(e) + '\\n' + trc, file=sys.stderr)\n # A non-zero exit code causes the training job to be marked as Failed.\n sys.exit(255)\n \nif __name__ == '__main__':\n train()\n\n # A zero exit code causes the job to be marked a Succeeded.\n sys.exit(0)\n\n\nclass Tub(object):\n \"\"\"\n A datastore to store sensor data in a key, value format.\n\n Accepts str, int, float, image_array, image, and array data types.\n\n For example:\n\n #Create a tub to store speed values.\n >>> path = '~/mydonkey/test_tub'\n >>> inputs = ['user/speed', 'cam/image']\n >>> types = ['float', 'image']\n >>> t=Tub(path=path, inputs=inputs, types=types)\n\n \"\"\"\n\n def __init__(self, path, inputs=None, types=None):\n\n self.path = os.path.expanduser(path)\n print('path_in_tub:', self.path)\n self.meta_path = os.path.join(self.path, 'meta.json')\n self.df = None\n\n exists = os.path.exists(self.path)\n\n if exists:\n #load log and meta\n print(\"Tub exists: {}\".format(self.path))\n with open(self.meta_path, 'r') as f:\n self.meta = json.load(f)\n self.current_ix = self.get_last_ix() + 1\n\n elif not exists and inputs:\n print('Tub does NOT exist. Creating new tub...')\n #create log and save meta\n os.makedirs(self.path)\n self.meta = {'inputs': inputs, 'types': types}\n with open(self.meta_path, 'w') as f:\n json.dump(self.meta, f)\n self.current_ix = 0\n print('New tub created at: {}'.format(self.path))\n else:\n msg = \"The tub path you provided doesn't exist and you didnt pass any meta info (inputs & types)\" + \\\n \"to create a new tub. Please check your tub path or provide meta info to create a new tub.\"\n\n raise AttributeError(msg)\n\n self.start_time = time.time()\n\n\n def get_last_ix(self):\n index = self.get_index()\n return max(index)\n\n def update_df(self):\n df = pd.DataFrame([self.get_json_record(i) for i in self.get_index(shuffled=False)])\n self.df = df\n\n def get_df(self):\n if self.df is None:\n self.update_df()\n return self.df\n\n\n def get_index(self, shuffled=True):\n files = next(os.walk(self.path))[2]\n record_files = [f for f in files if f[:6]=='record']\n \n def get_file_ix(file_name):\n try:\n name = file_name.split('.')[0]\n num = int(name.split('_')[1])\n except:\n num = 0\n return num\n\n nums = [get_file_ix(f) for f in record_files]\n \n if shuffled:\n random.shuffle(nums)\n else:\n nums = sorted(nums)\n \n return nums \n\n\n @property\n def inputs(self):\n return list(self.meta['inputs'])\n\n @property\n def types(self):\n return list(self.meta['types'])\n\n def get_input_type(self, key):\n input_types = dict(zip(self.inputs, self.types))\n return input_types.get(key)\n\n def write_json_record(self, json_data):\n path = self.get_json_record_path(self.current_ix)\n try:\n with open(path, 'w') as fp:\n json.dump(json_data, fp)\n #print('wrote record:', json_data)\n except TypeError:\n print('troubles with record:', json_data)\n except FileNotFoundError:\n raise\n except:\n print(\"Unexpected error:\", sys.exc_info()[0])\n raise\n\n def get_num_records(self):\n import glob\n files = glob.glob(os.path.join(self.path, 'record_*.json'))\n return len(files)\n\n\n def make_record_paths_absolute(self, record_dict):\n #make paths absolute\n d = {}\n for k, v in record_dict.items():\n if type(v) == str: #filename\n if '.' in v:\n v = os.path.join(self.path, v)\n d[k] = v\n\n return d\n\n\n\n\n def check(self, fix=False):\n '''\n Iterate over all records and make sure we can load them.\n Optionally remove records that cause a problem.\n '''\n print('Checking tub:%s.' % self.path)\n print('Found: %d records.' % self.get_num_records())\n problems = False\n for ix in self.get_index(shuffled=False):\n try:\n self.get_record(ix)\n except:\n problems = True\n if fix == False:\n print('problems with record:', self.path, ix)\n else:\n print('problems with record, removing:', self.path, ix)\n self.remove_record(ix)\n if not problems:\n print(\"No problems found.\")\n\n def remove_record(self, ix):\n '''\n remove data associate with a record\n '''\n record = self.get_json_record_path(ix)\n os.unlink(record)\n\n def put_record(self, data):\n \"\"\"\n Save values like images that can't be saved in the csv log and\n return a record with references to the saved values that can\n be saved in a csv.\n \"\"\"\n json_data = {}\n self.current_ix += 1\n \n for key, val in data.items():\n typ = self.get_input_type(key)\n\n if typ in ['str', 'float', 'int', 'boolean']:\n json_data[key] = val\n\n elif typ is 'image':\n path = self.make_file_path(key)\n val.save(path)\n json_data[key]=path\n\n elif typ == 'image_array':\n img = Image.fromarray(np.uint8(val))\n name = self.make_file_name(key, ext='.jpg')\n img.save(os.path.join(self.path, name))\n json_data[key]=name\n\n else:\n msg = 'Tub does not know what to do with this type {}'.format(typ)\n raise TypeError(msg)\n\n self.write_json_record(json_data)\n return self.current_ix\n\n\n def get_json_record_path(self, ix):\n return os.path.join(self.path, 'record_'+str(ix)+'.json')\n\n def get_json_record(self, ix):\n path = self.get_json_record_path(ix)\n try:\n with open(path, 'r') as fp:\n json_data = json.load(fp)\n except UnicodeDecodeError:\n raise Exception('bad record: %d. You may want to run `python manage.py check --fix`' % ix)\n except FileNotFoundError:\n raise\n except:\n print(\"Unexpected error:\", sys.exc_info()[0])\n raise\n\n record_dict = self.make_record_paths_absolute(json_data)\n return record_dict\n\n\n def get_record(self, ix):\n\n json_data = self.get_json_record(ix)\n data = self.read_record(json_data)\n return data\n\n\n\n def read_record(self, record_dict):\n data={}\n for key, val in record_dict.items():\n typ = self.get_input_type(key)\n\n #load objects that were saved as separate files\n if typ == 'image_array':\n img = Image.open((val))\n val = np.array(img)\n\n data[key] = val\n\n\n return data\n\n\n def make_file_name(self, key, ext='.png'):\n name = '_'.join([str(self.current_ix), key, ext])\n name = name = name.replace('/', '-')\n return name\n\n def delete(self):\n \"\"\" Delete the folder and files for this tub. \"\"\"\n import shutil\n shutil.rmtree(self.path)\n\n def shutdown(self):\n pass\n\n\n def get_record_gen(self, record_transform=None, shuffle=True, df=None):\n\n if df is None:\n df = self.get_df()\n\n\n while True:\n for row in self.df.iterrows():\n if shuffle:\n record_dict = df.sample(n=1).to_dict(orient='record')[0]\n\n if record_transform:\n record_dict = record_transform(record_dict)\n\n record_dict = self.read_record(record_dict)\n\n yield record_dict\n\n\n def get_batch_gen(self, keys, record_transform=None, batch_size=128, shuffle=True, df=None):\n\n record_gen = self.get_record_gen(record_transform, shuffle=shuffle, df=df)\n\n if keys == None:\n keys = list(self.df.columns)\n\n while True:\n record_list = []\n for _ in range(batch_size):\n record_list.append(next(record_gen))\n\n batch_arrays = {}\n for i, k in enumerate(keys):\n arr = np.array([r[k] for r in record_list])\n # if len(arr.shape) == 1:\n # arr = arr.reshape(arr.shape + (1,))\n batch_arrays[k] = arr\n\n yield batch_arrays\n\n\n def get_train_gen(self, X_keys, Y_keys, batch_size=128, record_transform=None, df=None):\n\n batch_gen = self.get_batch_gen(X_keys + Y_keys,\n batch_size=batch_size, record_transform=record_transform, df=df)\n\n while True:\n batch = next(batch_gen)\n X = [batch[k] for k in X_keys]\n Y = [batch[k] for k in Y_keys]\n yield X, Y\n\n\n def get_train_val_gen(self, X_keys, Y_keys, batch_size=128, record_transform=None, train_frac=.8):\n train_df = train=self.df.sample(frac=train_frac,random_state=200)\n val_df = self.df.drop(train_df.index)\n\n train_gen = self.get_train_gen(X_keys=X_keys, Y_keys=Y_keys, batch_size=batch_size,\n record_transform=record_transform, df=train_df)\n\n val_gen = self.get_train_gen(X_keys=X_keys, Y_keys=Y_keys, batch_size=batch_size,\n record_transform=record_transform, df=val_df)\n\n return train_gen, val_gen\n\n\n\n\n\n\nclass TubHandler():\n def __init__(self, path):\n self.path = os.path.expanduser(path)\n\n def get_tub_list(self,path):\n folders = next(os.walk(path))[1]\n return folders\n\n def next_tub_number(self, path):\n def get_tub_num(tub_name):\n try:\n num = int(tub_name.split('_')[1])\n except:\n num = 0\n return num\n\n folders = self.get_tub_list(path)\n numbers = [get_tub_num(x) for x in folders]\n #numbers = [i for i in numbers if i is not None]\n next_number = max(numbers+[0]) + 1\n return next_number\n\n def create_tub_path(self):\n tub_num = self.next_tub_number(self.path)\n date = datetime.datetime.now().strftime('%y-%m-%d')\n name = '_'.join(['tub',str(tub_num),date])\n tub_path = os.path.join(self.path, name)\n return tub_path\n\n def new_tub_writer(self, inputs, types):\n tub_path = self.create_tub_path()\n tw = TubWriter(path=tub_path, inputs=inputs, types=types)\n return tw\n\n\n\nclass TubImageStacker(Tub):\n '''\n A Tub for training a NN with images that are the last three records stacked \n togther as 3 channels of a single image. The idea is to give a simple feedforward\n NN some chance of building a model based on motion.\n If you drive with the ImageFIFO part, then you don't need this.\n Just make sure your inference pass uses the ImageFIFO that the NN will now expect.\n '''\n \n def rgb2gray(self, rgb):\n '''\n take a numpy rgb image return a new single channel image converted to greyscale\n '''\n return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])\n\n def stack3Images(self, img_a, img_b, img_c):\n '''\n convert 3 rgb images into grayscale and put them into the 3 channels of\n a single output image\n '''\n width, height, _ = img_a.shape\n\n gray_a = self.rgb2gray(img_a)\n gray_b = self.rgb2gray(img_b)\n gray_c = self.rgb2gray(img_c)\n \n img_arr = np.zeros([width, height, 3], dtype=np.dtype('B'))\n\n img_arr[...,0] = np.reshape(gray_a, (width, height))\n img_arr[...,1] = np.reshape(gray_b, (width, height))\n img_arr[...,2] = np.reshape(gray_c, (width, height))\n\n return img_arr\n\n def get_record(self, ix):\n '''\n get the current record and two previous.\n stack the 3 images into a single image.\n '''\n data = super(TubImageStacker, self).get_record(ix)\n\n if ix > 1:\n data_ch1 = super(TubImageStacker, self).get_record(ix - 1)\n data_ch0 = super(TubImageStacker, self).get_record(ix - 2)\n\n json_data = self.get_json_record(ix)\n for key, val in json_data.items():\n typ = self.get_input_type(key)\n\n #load objects that were saved as separate files\n if typ == 'image':\n val = self.stack3Images(data_ch0[key], data_ch1[key], data[key])\n data[key] = val\n elif typ == 'image_array':\n img = self.stack3Images(data_ch0[key], data_ch1[key], data[key])\n val = np.array(img)\n\n return data\n\n\n\nclass TubTimeStacker(TubImageStacker):\n '''\n A Tub for training N with records stacked through time. \n The idea here is to force the network to learn to look ahead in time.\n Init with an array of time offsets from the current time.\n '''\n\n def __init__(self, frame_list, *args, **kwargs):\n '''\n frame_list of [0, 10] would stack the current and 10 frames from now records togther in a single record\n with just the current image returned.\n [5, 90, 200] would return 3 frames of records, ofset 5, 90, and 200 frames in the future.\n\n '''\n super(TubTimeStacker, self).__init__(*args, **kwargs)\n self.frame_list = frame_list\n \n def get_record(self, ix):\n '''\n stack the N records into a single record.\n Each key value has the record index with a suffix of _N where N is\n the frame offset into the data.\n '''\n data = {}\n for i, iOffset in enumerate(self.frame_list):\n iRec = ix + iOffset\n \n try:\n json_data = self.get_json_record(iRec)\n except FileNotFoundError:\n pass\n except:\n pass\n\n for key, val in json_data.items():\n typ = self.get_input_type(key)\n\n #load only the first image saved as separate files\n if typ == 'image' and i == 0:\n val = Image.open(os.path.join(self.path, val))\n data[key] = val \n elif typ == 'image_array' and i == 0:\n d = super(TubTimeStacker, self).get_record(ix)\n data[key] = d[key]\n else:\n '''\n we append a _offset to the key\n so user/angle out now be user/angle_0\n '''\n new_key = key + \"_\" + str(iOffset)\n data[new_key] = val\n return data\n\n\nclass TubGroup(Tub):\n def __init__(self, tub_paths_arg):\n tub_paths = expand_path_arg(tub_paths_arg)\n \n print('TubGroup:tubpaths:', tub_paths)\n tubs = [Tub(path) for path in tub_paths]\n self.input_types = {}\n\n record_count = 0\n for t in tubs:\n t.update_df()\n record_count += len(t.df)\n self.input_types.update(dict(zip(t.inputs, t.types)))\n\n print('joining the tubs {} records together. This could take {} minutes.'.format(record_count,\n int(record_count / 300000)))\n\n self.meta = {'inputs': list(self.input_types.keys()),\n 'types': list(self.input_types.values())}\n\n\n self.df = pd.concat([t.df for t in tubs], axis=0, join='inner')\n \n \n\ndef expand_path_arg(path_str):\n path_list = path_str.split(\",\")\n expanded_paths = []\n for path in path_list:\n paths = expand_path_mask(path)\n expanded_paths += paths\n return expanded_paths\n\n\ndef expand_path_mask(path):\n matches = []\n path = os.path.expanduser(path)\n for file in glob.glob(path):\n if os.path.isdir(file):\n matches.append(os.path.join(os.path.abspath(file)))\n return matches\n\ndef linear_bin(a):\n a = a + 1\n b = round(a / (2/14))\n arr = np.zeros(15)\n arr[int(b)] = 1\n return arr\n\ndef rt(record):\n record['user/angle'] = linear_bin(record['user/angle'])\n return record\n \n \ndef default_categorical():\n from keras.layers import Input, Dense, merge\n from keras.models import Model\n from keras.layers import Convolution2D, MaxPooling2D, Reshape, BatchNormalization\n from keras.layers import Activation, Dropout, Flatten, Dense\n \n img_in = Input(shape=(160, 120, 3), name='img_in') # First layer, input layer, Shape comes from camera.py resolution, RGB\n x = img_in\n x = Convolution2D(24, (5,5), strides=(2,2), activation='relu')(x) # 24 features, 5 pixel x 5 pixel kernel (convolution, feauture) window, 2wx2h stride, relu activation\n x = Convolution2D(32, (5,5), strides=(2,2), activation='relu')(x) # 32 features, 5px5p kernel window, 2wx2h stride, relu activatiion\n x = Convolution2D(64, (5,5), strides=(2,2), activation='relu')(x) # 64 features, 5px5p kernal window, 2wx2h stride, relu\n x = Convolution2D(64, (3,3), strides=(2,2), activation='relu')(x) # 64 features, 3px3p kernal window, 2wx2h stride, relu\n x = Convolution2D(64, (3,3), strides=(1,1), activation='relu')(x) # 64 features, 3px3p kernal window, 1wx1h stride, relu\n\n # Possibly add MaxPooling (will make it less sensitive to position in image). Camera angle fixed, so may not to be needed\n\n x = Flatten(name='flattened')(x) # Flatten to 1D (Fully connected)\n x = Dense(100, activation='relu')(x) # Classify the data into 100 features, make all negatives 0\n x = Dropout(.1)(x) # Randomly drop out (turn off) 10% of the neurons (Prevent overfitting)\n x = Dense(50, activation='relu')(x) # Classify the data into 50 features, make all negatives 0\n x = Dropout(.1)(x) # Randomly drop out 10% of the neurons (Prevent overfitting)\n #categorical output of the angle\n angle_out = Dense(15, activation='softmax', name='angle_out')(x) # Connect every input with every output and output 15 hidden units. Use Softmax to give percentage. 15 categories and find best one based off percentage 0.0-1.0\n \n #continous output of throttle\n throttle_out = Dense(1, activation='relu', name='throttle_out')(x) # Reduce to 1 number, Positive number only\n \n model = Model(inputs=[img_in], outputs=[angle_out, throttle_out])\n model.compile(optimizer='adam',\n loss={'angle_out': 'categorical_crossentropy', \n 'throttle_out': 'mean_absolute_error'},\n loss_weights={'angle_out': 0.9, 'throttle_out': .001})\n\n return model", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
cb66c333d0ded3426eec245213460b7fdb2cb62f
187,348
ipynb
Jupyter Notebook
Recommendations_with_IBM.ipynb
rabadzhiyski/recommendationsIBM
9da6a65f1221208c64759bda4f7b6acc1e0ce3e2
[ "MIT" ]
null
null
null
Recommendations_with_IBM.ipynb
rabadzhiyski/recommendationsIBM
9da6a65f1221208c64759bda4f7b6acc1e0ce3e2
[ "MIT" ]
null
null
null
Recommendations_with_IBM.ipynb
rabadzhiyski/recommendationsIBM
9da6a65f1221208c64759bda4f7b6acc1e0ce3e2
[ "MIT" ]
null
null
null
51.35636
19,828
0.645254
[ [ [ "# Recommendations with IBM\n\nFor this project I analyze the interactions that users have with articles on the IBM Watson Studio platform, and make recommendations to them about new articles they will like.\n\n\n## Table of Contents\n\nI. [Exploratory Data Analysis](#Exploratory-Data-Analysis)<br>\nII. [Rank Based Recommendations](#Rank)<br>\nIII. [User-User Based Collaborative Filtering](#User-User)<br>\nIV. [Content Based Recommendations (EXTRA - NOT REQUIRED)](#Content-Recs)<br>\nV. [Matrix Factorization](#Matrix-Fact)<br>\nVI. [Extras & Concluding](#conclusions)<br>\nVII. [Resources](#resources)\n", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport project_tests as t\nimport pickle\n\n%matplotlib inline\n\ndf = pd.read_csv('data/user-item-interactions.csv')\ndf_content = pd.read_csv('data/articles_community.csv')\ndel df['Unnamed: 0']\ndel df_content['Unnamed: 0']\n\n# Show df to get an idea of the data\ndf.head()", "_____no_output_____" ], [ "# Show df_content to get an idea of the data\ndf_content.head()", "_____no_output_____" ], [ "# check number of rows and columns\ndf.shape, df_content.shape", "_____no_output_____" ], [ "# check the data sets\ndf.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 45993 entries, 0 to 45992\nData columns (total 3 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 article_id 45993 non-null float64\n 1 title 45993 non-null object \n 2 email 45976 non-null object \ndtypes: float64(1), object(2)\nmemory usage: 1.1+ MB\n" ], [ "# check the data sets\ndf_content.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1056 entries, 0 to 1055\nData columns (total 5 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 doc_body 1042 non-null object\n 1 doc_description 1053 non-null object\n 2 doc_full_name 1056 non-null object\n 3 doc_status 1056 non-null object\n 4 article_id 1056 non-null int64 \ndtypes: int64(1), object(4)\nmemory usage: 41.4+ KB\n" ], [ "# check for missing values\ndf.isnull().sum()", "_____no_output_____" ], [ "# check for missing values\ndf_content.isnull().sum()", "_____no_output_____" ], [ "# number of unique articles\ndf['article_id'].nunique()", "_____no_output_____" ], [ "# number of unique users\ndf['email'].nunique()", "_____no_output_____" ] ], [ [ "### <a class=\"anchor\" id=\"Exploratory-Data-Analysis\">Part I : Exploratory Data Analysis</a>\n\nUse the dictionary and cells below to provide some insight into the descriptive statistics of the data.\n\n`1.` What is the distribution of how many articles a user interacts with in the dataset? Provide a visual and descriptive statistics to assist with giving a look at the number of times each user interacts with an article. \n\nUsing the seaborn distplot for vizualizations\nhttp://seaborn.pydata.org/generated/seaborn.distplot.html", "_____no_output_____" ] ], [ [ "# assigning pivot table to a variable\nuser_interact = df.groupby('email').count()['article_id']", "_____no_output_____" ], [ "# plotting with seaborn\nsns.distplot(user_interact, bins=40)", "/home/freemo/anaconda3/lib/python3.7/site-packages/seaborn/distributions.py:2551: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).\n warnings.warn(msg, FutureWarning)\n" ], [ "# seaborn rug plot version\nsns.distplot(user_interact, rug=True, hist=False, vertical=True)", "/home/freemo/anaconda3/lib/python3.7/site-packages/seaborn/distributions.py:2551: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `kdeplot` (an axes-level function for kernel density plots).\n warnings.warn(msg, FutureWarning)\n/home/freemo/anaconda3/lib/python3.7/site-packages/seaborn/distributions.py:1649: FutureWarning: The `vertical` parameter is deprecated and will be removed in a future version. Assign the data to the `y` variable instead.\n warnings.warn(msg, FutureWarning)\n/home/freemo/anaconda3/lib/python3.7/site-packages/seaborn/distributions.py:2055: FutureWarning: The `axis` variable is no longer used and will be removed. Instead, assign variables directly to `x` or `y`.\n warnings.warn(msg, FutureWarning)\n/home/freemo/anaconda3/lib/python3.7/site-packages/seaborn/distributions.py:2064: FutureWarning: Using `vertical=True` to control the orientation of the plot is deprecated. Instead, assign the data directly to `y`. \n warnings.warn(msg, FutureWarning)\n" ], [ "# plotting with pandas\nuser_interact.hist(bins=40)", "_____no_output_____" ], [ "# the max number of user_article interactions\ndf.groupby('email')['article_id'].count().max()", "_____no_output_____" ], [ "# the medin number of user_article interactions\ndf.groupby('email')['article_id'].count().median()", "_____no_output_____" ], [ "# Fill in the median and maximum number of user_article interactios below\n\n# 50% of individuals interact with ___ number of articles or fewer.\nmedian_val = df.groupby('email')['article_id'].count().median() \n\n# The maximum number of user-article interactions by any 1 user is ______.\nmax_views_by_user = df.groupby('email')['article_id'].count().max()", "_____no_output_____" ] ], [ [ "`2.` Explore and remove duplicate articles from the **df_content** dataframe. ", "_____no_output_____" ] ], [ [ "# check number of rows and columns of df_content\ndf_content.shape", "_____no_output_____" ], [ "# Find and explore duplicate articles\ndf_content.duplicated().sum()", "_____no_output_____" ], [ "# Remove any rows that have the same article_id - only keep the first\ndf_content.drop_duplicates(inplace = True)", "_____no_output_____" ] ], [ [ "`3.` Use the cells below to find:\n\n**a.** The number of unique articles that have an interaction with a user. \n**b.** The number of unique articles in the dataset (whether they have any interactions or not).<br>\n**c.** The number of unique users in the dataset. (excluding null values) <br>\n**d.** The number of user-article interactions in the dataset.", "_____no_output_____" ] ], [ [ "# checking df for uniuqe values\ndf.nunique()", "_____no_output_____" ], [ "# checking df_content for unique values\ndf_content.nunique()", "_____no_output_____" ], [ "# The number of unique articles that have at least one interaction\ndf.article_id.nunique()", "_____no_output_____" ], [ "# The number of unique articles on the IBM platform\ndf_content.article_id.nunique()", "_____no_output_____" ], [ "# The number of unique users (email column refers to users)\ndf.email.nunique()", "_____no_output_____" ], [ "# The number of user-article interactions = the number of rows in df\nlen(df)", "_____no_output_____" ], [ "# The number of unique articles that have at least one interaction\nunique_articles = df.article_id.nunique()\n\n# The number of unique articles on the IBM platform\ntotal_articles = df_content.article_id.nunique()\n\n# The number of unique users\nunique_users = df.email.nunique()\n\n# The number of user-article interactions\nuser_article_interactions = len(df)", "_____no_output_____" ] ], [ [ "`4.` Use the cells below to find the most viewed **article_id**, as well as how often it was viewed. After talking to the company leaders, the `email_mapper` function was deemed a reasonable way to map users to ids. There were a small number of null values, and it was found that all of these null values likely belonged to a single user (which is how they are stored using the function below).", "_____no_output_____" ] ], [ [ "# check for the most viewed article_id\ndf['article_id'].value_counts()", "_____no_output_____" ], [ "most_viewed_article_id = '1429.0' # The most viewed article in the dataset as a string with one value following the decimal \nmax_views = 937 # The most viewed article in the dataset was viewed how many times?", "_____no_output_____" ], [ "## No need to change the code here - this will be helpful for later parts of the notebook\n# Run this cell to map the user email to a user_id column and remove the email column\n\ndef email_mapper():\n coded_dict = dict()\n cter = 1\n email_encoded = []\n \n for val in df['email']:\n if val not in coded_dict:\n coded_dict[val] = cter\n cter+=1\n \n email_encoded.append(coded_dict[val])\n return email_encoded\n\nemail_encoded = email_mapper()\ndel df['email']\ndf['user_id'] = email_encoded\n\n# show header\ndf.head()", "_____no_output_____" ], [ "## If you stored all your results in the variable names above, \n## you shouldn't need to change anything in this cell\n\nsol_1_dict = {\n '`50% of individuals have _____ or fewer interactions.`': median_val,\n '`The total number of user-article interactions in the dataset is ______.`': user_article_interactions,\n '`The maximum number of user-article interactions by any 1 user is ______.`': max_views_by_user,\n '`The most viewed article in the dataset was viewed _____ times.`': max_views,\n '`The article_id of the most viewed article is ______.`': most_viewed_article_id,\n '`The number of unique articles that have at least 1 rating ______.`': unique_articles,\n '`The number of unique users in the dataset is ______`': unique_users,\n '`The number of unique articles on the IBM platform`': total_articles\n}\n\n# Test your dictionary against the solution\nt.sol_1_test(sol_1_dict)", "It looks like you have everything right here! Nice job!\n" ] ], [ [ "### <a class=\"anchor\" id=\"Rank\">Part II: Rank-Based Recommendations</a>\n\nUnlike in the earlier lessons, we don't actually have ratings for whether a user liked an article or not. We only know that a user has interacted with an article. In these cases, the popularity of an article can really only be based on how often an article was interacted with.\n\n`1.` Fill in the function below to return the **n** top articles ordered with most interactions as the top. Test your function using the tests below.", "_____no_output_____" ] ], [ [ "df.head()", "_____no_output_____" ], [ "# testing a function\ndf['article_id'].value_counts().iloc[:10].index", "_____no_output_____" ], [ "# testing a function 2\ndf.groupby(by='title').count().sort_values(by='user_id', ascending=False).head().index.tolist()", "_____no_output_____" ], [ "# testing a function 3\ndf.groupby(by='article_id').count().sort_values(by='user_id', ascending=False).head(10).index.tolist()", "_____no_output_____" ], [ "# testing a funciton 4\nlist(df.groupby(by='article_id').count().sort_values(by='user_id', ascending=False).head(10).index)", "_____no_output_____" ], [ "def get_top_articles(n, df=df):\n '''\n INPUT:\n n - (int) the number of top articles to return\n df - (pandas dataframe) df as defined at the top of the notebook \n \n OUTPUT:\n top_articles - (list) A list of the top 'n' article titles \n \n '''\n # creating a list with top articles using 'title'\n top_articles = df['title'].value_counts().iloc[:n].index.tolist()\n \n return top_articles # Return the top article titles from df (not df_content)\n\ndef get_top_article_ids(n, df=df):\n '''\n INPUT:\n n - (int) the number of top articles to return\n df - (pandas dataframe) df as defined at the top of the notebook \n \n OUTPUT:\n top_articles - (list) A list of the top 'n' article titles \n \n '''\n # creating a list with top article ids\n top_articles_ids = df['article_id'].value_counts().iloc[:n].index.tolist()\n \n return top_articles_ids # Return the top article ids", "_____no_output_____" ], [ "print(get_top_articles(10))\nprint(get_top_article_ids(10))", "['use deep learning for image classification', 'insights from new york car accident reports', 'visualize car data with brunel', 'use xgboost, scikit-learn & ibm watson machine learning apis', 'predicting churn with the spss random tree algorithm', 'healthcare python streaming application demo', 'finding optimal locations of new store using decision optimization', 'apache spark lab, part 1: basic concepts', 'analyze energy consumption in buildings', 'gosales transactions for logistic regression model']\n[1429.0, 1330.0, 1431.0, 1427.0, 1364.0, 1314.0, 1293.0, 1170.0, 1162.0, 1304.0]\n" ], [ "print(get_top_articles(20))\nprint(get_top_article_ids(20))", "['use deep learning for image classification', 'insights from new york car accident reports', 'visualize car data with brunel', 'use xgboost, scikit-learn & ibm watson machine learning apis', 'predicting churn with the spss random tree algorithm', 'healthcare python streaming application demo', 'finding optimal locations of new store using decision optimization', 'apache spark lab, part 1: basic concepts', 'analyze energy consumption in buildings', 'gosales transactions for logistic regression model', 'welcome to pixiedust', 'customer demographics and sales', 'total population by country', 'deep learning with tensorflow course by big data university', 'model bike sharing data with spss', 'the nurse assignment problem', 'classify tumors with machine learning', 'analyze accident reports on amazon emr spark', 'movie recommender system with spark machine learning', 'putting a human face on machine learning']\n[1429.0, 1330.0, 1431.0, 1427.0, 1364.0, 1314.0, 1293.0, 1170.0, 1162.0, 1304.0, 1436.0, 1271.0, 1398.0, 43.0, 1351.0, 1393.0, 1185.0, 1160.0, 1354.0, 1368.0]\n" ], [ "# Test your function by returning the top 5, 10, and 20 articles\ntop_5 = get_top_articles(5)\ntop_10 = get_top_articles(10)\ntop_20 = get_top_articles(20)\n\n# Test each of your three lists from above\nt.sol_2_test(get_top_articles)", "Your top_5 looks like the solution list! Nice job.\nYour top_10 looks like the solution list! Nice job.\nYour top_20 looks like the solution list! Nice job.\n" ] ], [ [ "### <a class=\"anchor\" id=\"User-User\">Part III: User-User Based Collaborative Filtering</a>\n\n\n`1.` Use the function below to reformat the **df** dataframe to be shaped with users as the rows and articles as the columns. \n\n* Each **user** should only appear in each **row** once.\n\n\n* Each **article** should only show up in one **column**. \n\n\n* **If a user has interacted with an article, then place a 1 where the user-row meets for that article-column**. It does not matter how many times a user has interacted with the article, all entries where a user has interacted with an article should be a 1. \n\n\n* **If a user has not interacted with an item, then place a zero where the user-row meets for that article-column**. \n\nUse the tests to make sure the basic structure of your matrix matches what is expected by the solution.", "_____no_output_____" ] ], [ [ "df.groupby(['user_id', 'article_id']).agg(lambda x: 1).unstack().fillna(0)", "_____no_output_____" ], [ "# create the user-article matrix with 1's and 0's\n\ndef create_user_item_matrix(df):\n '''\n INPUT:\n df - pandas dataframe with article_id, title, user_id columns\n \n OUTPUT:\n user_item - user item matrix \n \n Description:\n Return a matrix with user ids as rows and article ids on the columns with 1 values where a user interacted with \n an article and a 0 otherwise\n '''\n # Using groupby and lambda function to create the matrix\n user_item = df.groupby(['user_id', 'article_id']).agg(lambda x: 1).unstack().fillna(0)\n \n return user_item # return the user_item matrix \n\nuser_item = create_user_item_matrix(df)", "_____no_output_____" ], [ "## Tests: You should just need to run this cell. Don't change the code.\nassert user_item.shape[0] == 5149, \"Oops! The number of users in the user-article matrix doesn't look right.\"\nassert user_item.shape[1] == 714, \"Oops! The number of articles in the user-article matrix doesn't look right.\"\nassert user_item.sum(axis=1)[1] == 36, \"Oops! The number of articles seen by user 1 doesn't look right.\"\nprint(\"You have passed our quick tests! Please proceed!\")", "You have passed our quick tests! Please proceed!\n" ] ], [ [ "`2.` Complete the function below which should take a user_id and provide an ordered list of the most similar users to that user (from most similar to least similar). The returned result should not contain the provided user_id, as we know that each user is similar to him/herself. Because the results for each user here are binary, it (perhaps) makes sense to compute similarity as the dot product of two users. \n\nUse the tests to test your function.", "_____no_output_____" ] ], [ [ "def find_similar_users(user_id, user_item=user_item):\n '''\n INPUT:\n user_id - (int) a user_id\n user_item - (pandas dataframe) matrix of users by articles: \n 1's when a user has interacted with an article, 0 otherwise\n \n OUTPUT:\n similar_users - (list) an ordered list where the closest users (largest dot product users)\n are listed first\n \n Description:\n Computes the similarity of every pair of users based on the dot product\n Returns an ordered list\n \n '''\n # compute similarity of each user to the provided user\n similar_mat = user_item.dot(user_item.loc[user_id].T)\n \n # sort by similarity\n most_similar_users = similar_mat.sort_values(ascending=False).index.tolist()\n\n most_similar_users.remove(user_id)\n\n return most_similar_users # return a list of the users in order from most to least similar ", "_____no_output_____" ], [ "# Do a spot check of your function\nprint(\"The 10 most similar users to user 1 are: {}\".format(find_similar_users(1)[:10]))\nprint(\"The 5 most similar users to user 3933 are: {}\".format(find_similar_users(3933)[:5]))\nprint(\"The 3 most similar users to user 46 are: {}\".format(find_similar_users(46)[:3]))", "The 10 most similar users to user 1 are: [3933, 23, 3782, 203, 4459, 131, 3870, 46, 4201, 49]\nThe 5 most similar users to user 3933 are: [1, 23, 3782, 203, 4459]\nThe 3 most similar users to user 46 are: [4201, 23, 3782]\n" ] ], [ [ "`3.` Now that you have a function that provides the most similar users to each user, you will want to use these users to find articles you can recommend. Complete the functions below to return the articles you would recommend to each user. ", "_____no_output_____" ] ], [ [ "def get_article_names(article_ids, df=df):\n '''\n INPUT:\n article_ids - (list) a list of article ids\n df - (pandas dataframe) df as defined at the top of the notebook\n \n OUTPUT:\n article_names - (list) a list of article names associated with the list of article ids \n (this is identified by the title column)\n '''\n # create article names \n article_names = [df[df['article_id'] == float(id)]['title'].values[0] for id in article_ids]\n \n return article_names # Return the article names associated with list of article ids\n\n\ndef get_user_articles(user_id, user_item=user_item):\n '''\n INPUT:\n user_id - (int) a user id\n user_item - (pandas dataframe) matrix of users by articles: \n 1's when a user has interacted with an article, 0 otherwise\n \n OUTPUT:\n article_ids - (list) a list of the article ids seen by the user\n article_names - (list) a list of article names associated with the list of article ids \n (this is identified by the doc_full_name column in df_content)\n \n Description:\n Provides a list of the article_ids and article titles that have been seen by a user\n '''\n # Your code here\n article_ids = [str(id) for id in list(user_item.loc[user_id][user_item.loc[user_id]==1].title.index)]\n \n article_names = get_article_names(article_ids)\n \n return article_ids, article_names # return the ids and names\n\n\ndef user_user_recs(user_id, m=10):\n '''\n INPUT:\n user_id - (int) a user id\n m - (int) the number of recommendations you want for the user\n \n OUTPUT:\n recs - (list) a list of recommendations for the user\n \n Description:\n Loops through the users based on closeness to the input user_id\n For each user - finds articles the user hasn't seen before and provides them as recs\n Does this until m recommendations are found\n \n Notes:\n Users who are the same closeness are chosen arbitrarily as the 'next' user\n \n For the user where the number of recommended articles starts below m \n and ends exceeding m, the last items are chosen arbitrarily\n \n '''\n # create user-user recommendation\n recs = []\n most_similar_users = find_similar_users(user_id)\n the_user_articles, the_article_names = get_user_articles(user_id)\n for user in most_similar_users:\n article_ids, article_names = get_user_articles(user)\n for id in article_ids:\n if id not in the_user_articles:\n recs.append(id)\n if len(recs) >= m:\n break\n if len(recs) >= m:\n break\n \n if len(recs) < m:\n for id in str(df['article_id']):\n if id not in the_user_articles:\n recs.append(id)\n if len(recs) >= m:\n break\n \n return recs # return your recommendations for this user_id ", "_____no_output_____" ], [ "# Check Results\nget_article_names(user_user_recs(1, 10)) # Return 10 recommendations for user 1", "_____no_output_____" ] ], [ [ "`4.` Now we are going to improve the consistency of the **user_user_recs** function from above. \n\n* Instead of arbitrarily choosing when we obtain users who are all the same closeness to a given user - choose the users that have the most total article interactions before choosing those with fewer article interactions.\n\n\n* Instead of arbitrarily choosing articles from the user where the number of recommended articles starts below m and ends exceeding m, choose articles with the articles with the most total interactions before choosing those with fewer total interactions. This ranking should be what would be obtained from the **top_articles** function you wrote earlier.", "_____no_output_____" ] ], [ [ "def get_top_sorted_users(user_id, df=df, user_item=user_item):\n '''\n INPUT:\n user_id - (int)\n df - (pandas dataframe) df as defined at the top of the notebook \n user_item - (pandas dataframe) matrix of users by articles: \n 1's when a user has interacted with an article, 0 otherwise\n \n \n OUTPUT:\n neighbors_df - (pandas dataframe) a dataframe with:\n neighbor_id - is a neighbor user_id\n similarity - measure of the similarity of each user to the provided user_id\n num_interactions - the number of articles viewed by the user - if a u\n \n Other Details - sort the neighbors_df by the similarity and then by number of interactions where \n highest of each is higher in the dataframe\n \n '''\n # creating a variable based on panda dataframe of the columns we need\n neighbors_df = pd.DataFrame(columns=['neighbor_id', 'similarity', 'num_interactions'])\n \n for i in user_item.index.values:\n if i == user_id:\n continue\n neighbor_id = i\n similarity = user_item[user_item.index == user_id].dot(user_item.loc[i].T).values[0]\n num_interactions = user_item.loc[i].values.sum()\n neighbors_df.loc[neighbor_id] = [neighbor_id, similarity, num_interactions]\n \n neighbors_df['similarity'] = neighbors_df['similarity'].astype('int')\n neighbors_df['neighbor_id'] = neighbors_df['neighbor_id'].astype('int')\n neighbors_df = neighbors_df.sort_values(by = ['similarity', 'neighbor_id'], ascending = [False, True])\n \n return neighbors_df # Return the dataframe specified in the doc_string\n\ndef user_user_recs_part2(user_id, m=10):\n '''\n INPUT:\n user_id - (int) a user id\n m - (int) the number of recommendations you want for the user\n \n OUTPUT:\n recs - (list) a list of recommendations for the user by article id\n rec_names - (list) a list of recommendations for the user by article title\n \n Description:\n Loops through the users based on closeness to the input user_id\n For each user - finds articles the user hasn't seen before and provides them as recs\n Does this until m recommendations are found\n \n Notes:\n * Choose the users that have the most total article interactions \n before choosing those with fewer article interactions.\n\n * Choose articles with the articles with the most total interactions \n before choosing those with fewer total interactions. \n \n '''\n # create a list with recommendations based on total article interactions\n \n top_df = get_top_sorted_users(user_id)\n uid_list = top_df['neighbor_id'].values.tolist()\n recs = []\n name_ids = []\n\n exp_article_ids = list(set(df[df['user_id'] == user_id]['article_id'].values.tolist()))\n\n for uid in uid_list:\n recs += df[df['user_id'] == uid]['article_id'].values.tolist()\n\n recs = list(set(recs))\n recs = [ x for x in recs if x not in exp_article_ids ]\n\n rec_all = df[df.article_id.isin(recs)][['article_id','title']].drop_duplicates().head(m)\n recs = rec_all['article_id'].values.tolist()\n rec_names = rec_all['title'].values.tolist()\n \n return recs, rec_names", "_____no_output_____" ], [ "# Quick spot check - don't change this code - just use it to test your functions\nrec_ids, rec_names = user_user_recs_part2(20, 10)\nprint(\"The top 10 recommendations for user 20 are the following article ids:\")\nprint(rec_ids)\nprint()\nprint(\"The top 10 recommendations for user 20 are the following article names:\")\nprint(rec_names)", "The top 10 recommendations for user 20 are the following article ids:\n[1430.0, 1314.0, 1429.0, 1338.0, 1276.0, 1432.0, 593.0, 1185.0, 993.0, 14.0]\n\nThe top 10 recommendations for user 20 are the following article names:\n['using pixiedust for fast, flexible, and easier data analysis and experimentation', 'healthcare python streaming application demo', 'use deep learning for image classification', 'ml optimization using cognitive assistant', 'deploy your python model as a restful api', 'visualize data with the matplotlib library', 'upload files to ibm data science experience using the command line', 'classify tumors with machine learning', 'configuring the apache spark sql context', 'got zip code data? prep it for analytics. – ibm watson data lab – medium']\n" ] ], [ [ "`5.` Use your functions from above to correctly fill in the solutions to the dictionary below. Then test your dictionary against the solution. Provide the code you need to answer each following the comments below.", "_____no_output_____" ] ], [ [ "# Find the user that is most similar to user 1 \nfind_similar_users(1)[0]", "_____no_output_____" ], [ "# Find the 10th most similar user to user 131\nfind_similar_users(131)[10]", "_____no_output_____" ], [ "get_top_sorted_users(1).head()", "_____no_output_____" ], [ "get_top_sorted_users(131).head(10)", "_____no_output_____" ], [ "### Tests with a dictionary of results\n\n# Find the user that is most similar to user 1 \nuser1_most_sim = find_similar_users(1)[0] \n\n# Find the 10th most similar user to user 131\nuser131_10th_sim = find_similar_users(131)[10]", "_____no_output_____" ], [ "## Dictionary Test Here\nsol_5_dict = {\n 'The user that is most similar to user 1.': user1_most_sim, \n 'The user that is the 10th most similar to user 131': user131_10th_sim,\n}\n\nt.sol_5_test(sol_5_dict)", "This all looks good! Nice job!\n" ] ], [ [ "`6.` If we were given a new user, which of the above functions would you be able to use to make recommendations? Explain. Can you think of a better way we might make recommendations? Use the cell below to explain a better method for new users.", "_____no_output_____" ], [ "**Provide your response here.**\n\nRESPONSE:\n\nThe reccomendations for new users is always challenging. New users have no previous records thus it's impossible to use user collaborative filtering based recommendations methods. The solution would be to use a content based recommendations. While in collaborative filtering we used the connections of users and items, in content based method, we would use the information about the users and items, but not the connections between them. **Rank based filtering would help here with new users: get_top_articles and get_top_articles_ids are the fucntions that we can use.**", "_____no_output_____" ], [ "`7.` Using your existing functions, provide the top 10 recommended articles you would provide for the a new user below. You can test your function against our thoughts to make sure we are all on the same page with how we might make a recommendation.", "_____no_output_____" ] ], [ [ "new_user = '0.0'\n\n# What would your recommendations be for this new user '0.0'? As a new user, they have no observed articles.\n# Provide a list of the top 10 article ids you would give to \nnew_user = get_top_article_ids(10)\nnew_user_recs = map(str, new_user)", "_____no_output_____" ], [ "assert set(new_user_recs) == set(['1314.0','1429.0','1293.0','1427.0','1162.0','1364.0','1304.0','1170.0','1431.0','1330.0']), \"Oops! It makes sense that in this case we would want to recommend the most popular articles, because we don't know anything about these users.\"\n\nprint(\"That's right! Nice job!\")", "That's right! Nice job!\n" ] ], [ [ "### <a class=\"anchor\" id=\"Content-Recs\">Part IV: Content Based Recommendations (EXTRA - NOT REQUIRED)</a>\n\nAnother method we might use to make recommendations is to perform a ranking of the highest ranked articles associated with some term. You might consider content to be the **doc_body**, **doc_description**, or **doc_full_name**. There isn't one way to create a content based recommendation, especially considering that each of these columns hold content related information. \n\n`1.` Use the function body below to create a content based recommender. Since there isn't one right answer for this recommendation tactic, no test functions are provided. Feel free to change the function inputs if you decide you want to try a method that requires more input values. The input values are currently set with one idea in mind that you may use to make content based recommendations. One additional idea is that you might want to choose the most popular recommendations that meet your 'content criteria', but again, there is a lot of flexibility in how you might make these recommendations.\n\n### This part is NOT REQUIRED to pass this project. However, you may choose to take this on as an extra way to show off your skills.", "_____no_output_____" ] ], [ [ "def make_content_recs():\n '''\n INPUT:\n \n OUTPUT:\n \n '''\n", "_____no_output_____" ] ], [ [ "`2.` Now that you have put together your content-based recommendation system, use the cell below to write a summary explaining how your content based recommender works. Do you see any possible improvements that could be made to your function? Is there anything novel about your content based recommender?\n\n### This part is NOT REQUIRED to pass this project. However, you may choose to take this on as an extra way to show off your skills.\n\nhttps://view3f484599.udacity-student-workspaces.com/notebooks/Content%20Based%20Recommendations%20-%20Solution.ipynb", "_____no_output_____" ], [ "**Write an explanation of your content based recommendation system here.**", "_____no_output_____" ], [ "`3.` Use your content-recommendation system to make recommendations for the below scenarios based on the comments. Again no tests are provided here, because there isn't one right answer that could be used to find these content based recommendations.\n\n### This part is NOT REQUIRED to pass this project. However, you may choose to take this on as an extra way to show off your skills.", "_____no_output_____" ] ], [ [ "# make recommendations for a brand new user\n\n\n# make a recommendations for a user who only has interacted with article id '1427.0'\n\n", "_____no_output_____" ] ], [ [ "### <a class=\"anchor\" id=\"Matrix-Fact\">Part V: Matrix Factorization</a>\n\nIn this part of the notebook, you will build user matrix factorization to make article recommendations to the users on the IBM Watson Studio platform.\n\n`1.` You should have already created a **user_item** matrix above in **question 1** of **Part III** above. This first question here will just require that you run the cells to get things set up for the rest of **Part V** of the notebook. ", "_____no_output_____" ] ], [ [ "# Load the matrix here\nuser_item_matrix = pd.read_pickle('user_item_matrix.p')", "_____no_output_____" ], [ "# quick look at the matrix\nuser_item_matrix.head()", "_____no_output_____" ] ], [ [ "`2.` In this situation, you can use Singular Value Decomposition from [numpy](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.linalg.svd.html) on the user-item matrix. Use the cell to perform SVD, and explain why this is different than in the lesson.", "_____no_output_____" ] ], [ [ "# Perform SVD on the User-Item Matrix Here\n\nu, s, vt = np.linalg.svd(user_item_matrix) # use the built in to get the three matrices", "_____no_output_____" ], [ "s.shape, u.shape, vt.shape", "_____no_output_____" ] ], [ [ "**Provide your response here.**\n\nRESPONSE: \n\nLatent features in the lesson were just 4, however here we're talking about 714 latent features. So, the scale is very different comparing to the lesson. Plus, in the lessons there were null values in the data so FunkSVD was used, while here there were no null values.\n", "_____no_output_____" ], [ "`3.` Now for the tricky part, how do we choose the number of latent features to use? Running the below cell, you can see that as the number of latent features increases, we obtain a lower error rate on making predictions for the 1 and 0 values in the user-item matrix. Run the cell below to get an idea of how the accuracy improves as we increase the number of latent features.", "_____no_output_____" ] ], [ [ "num_latent_feats = np.arange(10,700+10,20)\nsum_errs = []\n\nfor k in num_latent_feats:\n # restructure with k latent features\n s_new, u_new, vt_new = np.diag(s[:k]), u[:, :k], vt[:k, :]\n \n # take dot product\n user_item_est = np.around(np.dot(np.dot(u_new, s_new), vt_new))\n \n # compute error for each prediction to actual value\n diffs = np.subtract(user_item_matrix, user_item_est)\n \n # total errors and keep track of them\n err = np.sum(np.sum(np.abs(diffs)))\n sum_errs.append(err)\n \n# plot results with seaborn\ngraph = sns.lineplot(num_latent_feats, 1 - np.array(sum_errs)/df.shape[0])\ngraph.set(xlabel ='Number of Latent Features',\n ylabel = 'Accuracy', \n title ='Accuracy vs. Number of Latent Features')", "/home/freemo/anaconda3/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n FutureWarning\n" ] ], [ [ "`4.` From the above, we can't really be sure how many features to use, because simply having a better way to predict the 1's and 0's of the matrix doesn't exactly give us an indication of if we are able to make good recommendations. Instead, we might split our dataset into a training and test set of data, as shown in the cell below. \n\nUse the code from question 3 to understand the impact on accuracy of the training and test sets of data with different numbers of latent features. Using the split below: \n\n* How many users can we make predictions for in the test set? \n* How many users are we not able to make predictions for because of the cold start problem?\n* How many articles can we make predictions for in the test set? \n* How many articles are we not able to make predictions for because of the cold start problem?", "_____no_output_____" ] ], [ [ "df_train = df.head(40000)\ndf_test = df.tail(5993)\n\ndef create_test_and_train_user_item(df_train, df_test):\n '''\n INPUT:\n df_train - training dataframe\n df_test - test dataframe\n \n OUTPUT:\n user_item_train - a user-item matrix of the training dataframe \n (unique users for each row and unique articles for each column)\n user_item_test - a user-item matrix of the testing dataframe \n (unique users for each row and unique articles for each column)\n test_idx - all of the test user ids\n test_arts - all of the test article ids\n \n '''\n # create matrix\n user_item_train = create_user_item_matrix(df_train)\n user_item_test = create_user_item_matrix(df_test)\n test_idx = list(user_item_test.index.values)\n test_arts = user_item_test.title.columns.values\n \n return user_item_train, user_item_test, test_idx, test_arts\n\nuser_item_train, user_item_test, test_idx, test_arts = create_test_and_train_user_item(df_train, df_test)", "_____no_output_____" ], [ "user_item_train.head()", "_____no_output_____" ], [ "user_item_train.shape", "_____no_output_____" ], [ "# 'How many users can we make predictions for in the test set\nusers = user_item_train.index.isin(test_idx)\nusers.sum()", "_____no_output_____" ], [ "# How many users in the test set are we not able to make predictions for because of the cold start problem?\nlen(test_idx)", "_____no_output_____" ], [ "# How many movies can we make predictions for in the test set?'\narticles = user_item_train.title.columns.isin(test_arts)\narticles.sum()", "_____no_output_____" ], [ "# Replace the values in the dictionary below\na = 662 \nb = 574 \nc = 20 \nd = 0 \n\n\nsol_4_dict = {\n 'How many users can we make predictions for in the test set?': c, # letter here, \n 'How many users in the test set are we not able to make predictions for because of the cold start problem?': a, # letter here, \n 'How many movies can we make predictions for in the test set?': b, # letter here,\n 'How many movies in the test set are we not able to make predictions for because of the cold start problem?':d # letter here\n}\n\nt.sol_4_test(sol_4_dict)", "Awesome job! That's right! All of the test movies are in the training data, but there are only 20 test users that were also in the training set. All of the other users that are in the test set we have no data on. Therefore, we cannot make predictions for these users using SVD.\n" ] ], [ [ "`5.` Now use the **user_item_train** dataset from above to find U, S, and V transpose using SVD. Then find the subset of rows in the **user_item_test** dataset that you can predict using this matrix decomposition with different numbers of latent features to see how many features makes sense to keep based on the accuracy on the test data. This will require combining what was done in questions `2` - `4`.\n\nUse the cells below to explore how well SVD works towards making predictions for recommendations on the test data. ", "_____no_output_____" ] ], [ [ "# fit SVD on the user_item_train matrix\n # fit svd similar to above then use the cells below\nu_train, s_train, vt_train = np.linalg.svd(user_item_train)", "_____no_output_____" ], [ "s_train.shape, u_train.shape, vt_train.shape", "_____no_output_____" ], [ "# Use these cells to see how well you can use the training \n# decomposition to predict on test data", "_____no_output_____" ], [ "# find the users that exists in both training and test datasets\nuser_present_both = np.intersect1d(user_item_test.index, user_item_train.index)\nuser_item_test_predictable = user_item_test[user_item_test.index.isin(user_present_both)]", "_____no_output_____" ], [ "user_present_both.shape, user_item_test_predictable.shape", "_____no_output_____" ], [ "# create u_test and vt_test variables\ncommon_ids = user_item_train.index.isin(test_idx)\ncommon_articles = user_item_train.title.columns.isin(test_arts)\nu_test = u_train[common_ids, :]\nvt_test = vt_train[:, common_articles]", "_____no_output_____" ], [ "# initialize testing parameters\nnum_latent_feats = np.arange(10,700+10,20)\nsum_errs_train = []\nsum_errs_test = []\n\nfor k in num_latent_feats:\n # restructure with k latent features for both training and test sets\n s_train_lat, u_train_lat, vt_train_lat = np.diag(s_train[:k]), u_train[:, :k], vt_train[:k, :]\n u_test_lat, vt_test_lat = u_test[:, :k], vt_test[:k, :]\n \n # take dot product for both training and test sets\n user_item_train_est = np.around(np.dot(np.dot(u_train_lat, s_train_lat), vt_train_lat))\n user_item_test_est = np.around(np.dot(np.dot(u_test_lat, s_train_lat), vt_test_lat))\n \n # compute error for each prediction to actual value\n diffs_train = np.subtract(user_item_train, user_item_train_est)\n diffs_test = np.subtract(user_item_test_predictable, user_item_test_est)\n \n # total errors and keep track of them for both training and test sets\n err_train = np.sum(np.sum(np.abs(diffs_train)))\n err_test = np.sum(np.sum(np.abs(diffs_test)))\n sum_errs_train.append(err_train)\n sum_errs_test.append(err_test)", "_____no_output_____" ], [ "# plot the results with seaborn, set graph size to fit the screen\nplt.figure(figsize=(5, 5))\n\n# plot the train data \npic = sns.lineplot(num_latent_feats, 1 - np.array(sum_errs_train)/(user_item_train.shape[0] \n * user_item_test_predictable.shape[1]), label='Train')\n# plot the test data \npic = sns.lineplot(num_latent_feats, 1 - np.array(sum_errs_test)/(user_item_test_predictable.shape[0] \n * user_item_test_predictable.shape[1]), label='Test')\n# add labels and title\npic.set(xlabel ='Latent Features',\n ylabel = 'Accuracy', \n title ='Train & Test Accuracy vs. Latent Features')", "/home/freemo/anaconda3/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n FutureWarning\n/home/freemo/anaconda3/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n FutureWarning\n" ] ], [ [ "`6.` Use the cell below to comment on the results you found in the previous question. Given the circumstances of your results, discuss what you might do to determine if the recommendations you make with any of the above recommendation systems are an improvement to how users currently find articles? ", "_____no_output_____" ], [ "**Your response here.**\n\nRESPONSE:\nThe train set and test set are showing completely different patterns. **While the accuracy of the train test increases, the one of the test set decreases with the higher number of latent features**. \n\nIt appears that there are only 20 matched users in the two data sets for whcih collaborative filtering method can be used. For the rest content based and rank based filtering recommendations can be used. In collaborative filtering, we are using the connections of users and items. In content based techniques, we are using information about the users and items, but not connections (hence the usefulness when we do not have a lot of internal data already available to use).\n\nFor just 20 users we can confirm that the number of users is not enough to make conclusive results about the model. Furheremore, we should be careful with the accuracy metric (number of correct predictions/number of rows in data). As many authors claim, counting only on accuracy is very often misleading. \n\n\n\nAs for validating the test, we can use A/B test experiment to get more isnights and vlaidate the methods in use. We can separate two groups of users (A and B). One half will use our recommendation engine and the other half will use a random recommendation. The below steps can help:\n1. Plan the experiment (we should divide users by cookie, as we can split visitors on their initial visit and it's fairly reliable for tracking). The test can be run for 21 days.\n2. Decide on metrics (ex. invariant metric can be the number of cookies at the home page)\n3. Decide on sizing - we should take into consideration the number of unique visitors per day.\n4. Analize data\n5. Draw conclusions\n\n", "_____no_output_____" ], [ "### <a class=\"anchor\" id=\"resources\">Part VII : Resources </a>\n", "_____no_output_____" ], [ "During my work I used several sources to complete the exercises like Udacity Lessons, Scikitlearn, Github, Pandas, and more. I list a few links below that might help other students.\n", "_____no_output_____" ], [ "- Machine Learning Overfitting - https://elitedatascience.com/overfitting-in-machine-learning\n- T function in python https://www.geeksforgeeks.org/pandas-dataframe-t-function-in-python/\n- Seaborn https://seaborn.pydata.org/generated/seaborn.lineplot.html\n- Seaborn labels https://www.geeksforgeeks.org/how-to-set-axes-labels-limits-in-a-seaborn-plot/\n- duplicate values https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html\n- Pandas https://pandas.pydata.org/\n- Numpy https://numpy.org/", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cb66cc0f5b4b839543bef01f863c71aea9d27623
49,056
ipynb
Jupyter Notebook
JTV_naive.ipynb
julepe7993/JTV---Projects
80d15db400e4417ba0102da6cefc09add70d4485
[ "Unlicense" ]
null
null
null
JTV_naive.ipynb
julepe7993/JTV---Projects
80d15db400e4417ba0102da6cefc09add70d4485
[ "Unlicense" ]
null
null
null
JTV_naive.ipynb
julepe7993/JTV---Projects
80d15db400e4417ba0102da6cefc09add70d4485
[ "Unlicense" ]
null
null
null
127.75
19,338
0.862198
[ [ [ "# sample try with jewelry", "_____no_output_____" ], [ "from os import listdir\ndirectory_name = \"/Users/J.Alvarez/jtv/images\"\nimage_names = listdir(\"/Users/J.Alvarez/jtv/images\")\n#image_names.remove('.DS_Store')\n#image_names.remove('._.DS_Store')", "_____no_output_____" ], [ "from keras import backend as K", "Using TensorFlow backend.\n" ], [ "#\"/Users/J.Alvarez/the_simpsons/kaggle_simpson_testset\"", "_____no_output_____" ], [ "from PIL import Image\nimport cv2\n\nimported_images = []\n\n#resize all images in the dataset for processing\nfor image_name in image_names:\n foo = cv2.imread(\"/Users/J.Alvarez/jtv/images/\" + image_name)\n foo = cv2.resize(foo, (256, 256))\n imported_images.append(foo)", "_____no_output_____" ], [ "import numpy as np\n\n#turn image into a 1D array\ndef process_image(image, width):\n out = []\n for x in range(width):\n for y in range(width):\n for z in range(3): #account for RGB\n out.append(image[x][y][z])\n return np.asarray(out)\n\n#process all images into 1D arrays\nimage_set = np.array([process_image(image, width = 256) for image in imported_images])", "_____no_output_____" ], [ "print(image_set)", "[[255 255 255 ..., 255 255 255]\n [255 255 255 ..., 255 255 255]\n [255 255 255 ..., 255 255 255]\n ..., \n [255 255 255 ..., 255 255 255]\n [255 255 255 ..., 255 255 255]\n [212 203 183 ..., 212 203 183]]\n" ], [ "#Script for Autoencoder\nimport pandas as pd\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom keras import backend as K\n\nimage_width = 256\npixels = image_width * image_width * 3\nhidden = 1000\ncorruption_level = 0.25\nX = tf.placeholder(\"float\", [None, pixels], name = 'X')\nmask = tf.placeholder(\"float\", [None, pixels], name = 'mask')\n\nweight_max = 4 * np.sqrt(4 / (6. * (pixels + hidden)))\nweight_initial = tf.random_uniform(shape = [pixels, hidden], minval = -weight_max, maxval = weight_max)\n\nW = tf.Variable(weight_initial, name = 'W')\nb = tf.Variable(tf.zeros([hidden]), name = 'b')\n\nW_prime = tf.transpose(W)\nb_prime = tf.Variable(tf.zeros([pixels]), name = 'b_prime')\n\ndef reparameterize(W = W, b = b):\n epsilon = K.random_normal(shape = (1, hidden), mean = 0.)\n return W + K.exp(b/2) * epsilon\n\ndef model(X, mask, W, b, W_prime, b_prime):\n tilde_X = mask * X\n\n hidden_state = tf.nn.sigmoid(tf.matmul(tilde_X, W) + b)\n out = tf.nn.sigmoid(tf.matmul(hidden_state, W_prime) + b_prime)\n return out\n\nout = model(X, mask, W, b, W_prime, b_prime)\n\ncost = tf.reduce_sum(tf.pow(X-out, 2))\noptimization = tf.train.GradientDescentOptimizer(0.02).minimize(cost)\n\nx_train, x_test = train_test_split(image_set)\n\nsess = tf.Session()\n#you need to initialize all variables\nsess.run(tf.global_variables_initializer())\nfor i in range(1):\n for start, end in zip(range(0, len(x_train), 128), range(128, len(x_train), 128)):\n input_ = x_train[start:end]\n mask_np = np.random.binomial(1, 1 - corruption_level, input_.shape)\n sess.run(optimization, feed_dict = {X: input_, mask: mask_np})\n mask_np = np.random.binomial(1, 1 - corruption_level, x_test.shape)\n print(i, sess.run(cost, feed_dict = {X: x_test, mask: mask_np}))", "0 1.38319e+12\n" ], [ "masknp = np.random.binomial(1, 1 - corruption_level, image_set.shape)\n\ndef hidden_state(X, mask, W, b):\n tilde_X = mask * X\n \n state = tf.nn.sigmoid(tf.matmul(tilde_X, W) + b)\n return state\n\ndef euclidean_distance(arr1, arr2):\n x = 0\n for i in range(len(arr1)):\n x += pow(arr1[i] - arr2[i], 2)\n return np.sqrt(x)\n\ndef search(image):\n hidden_states = [sess.run(hidden_state(X, mask, W, b),\n feed_dict={X: im.reshape(1, pixels), mask: np.random.binomial(1, 1-corruption_level, (1, pixels))})\n for im in image_set]\n query = sess.run(hidden_state(X, mask, W, b),\n feed_dict={X: image.reshape(1,pixels), mask: np.random.binomial(1, 1-corruption_level, (1, pixels))})\n starting_state = int(np.random.random()*len(hidden_states)) #choose random starting state\n best_states = [imported_images[starting_state]]\n distance = euclidean_distance(query[0], hidden_states[starting_state][0]) #Calculate similarity between hidden states\n for i in range(len(hidden_states)):\n dist = euclidean_distance(query[0], hidden_states[i][0])\n if dist <= distance:\n distance = dist #as the method progresses, it gets better at identifying similiar images\n best_states.append(imported_images[i])\n if len(best_states)>0:\n return best_states\n else:\n return best_states[len(best_states)-101:]", "_____no_output_____" ], [ "image_name = \"/Users/J.Alvarez/jtv/test/ABA054.jpg\" #Image to be used as query\nimage = cv2.imread(image_name)\nplt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)); plt.axis('off')\nplt.show()", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimage_name = \"/Users/J.Alvarez/jtv/test/ABA054.jpg\" #Image to be used as query\n#image_name = \"/Users/J.Alvarez/the_simpsons/test.jpg\" #Image to be used as query\n\nimage = cv2.imread(image_name)\nimage = cv2.resize(image, (256, 256))\nplt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)); plt.axis('off')\nimage = process_image(image, 256)", "_____no_output_____" ], [ "plt.show()", "_____no_output_____" ], [ "results = search(image) #Search the database using image", "_____no_output_____" ], [ "print(len(results))\nslots = 0\nplt.figure(figsize = (256,256))\nfor im in results[::-1]: #reads through results backwards (more similiar images first)\n plt.subplot(20, 20, slots + 1) \n plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)); plt.axis('off')\n slots += 1", "297\n" ], [ "plt.show()", "IOPub data rate exceeded.\nThe notebook server will temporarily stop sending output\nto the client in order to avoid crashing it.\nTo change this limit, set the config variable\n`--NotebookApp.iopub_data_rate_limit`.\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb66de12dcb3cf9f6dc06822722b3cc07a380945
3,111
ipynb
Jupyter Notebook
DEMO.ipynb
e2forks/jsonschema
055c7f6e70d2a463a8fc9a9bc50e4cb98900a5de
[ "MIT" ]
2
2019-09-10T00:36:37.000Z
2020-01-08T23:36:55.000Z
DEMO.ipynb
0x416c616e/jsonschema
3b8e3da631c5499f20468eb9154df603afbdc2b0
[ "MIT" ]
null
null
null
DEMO.ipynb
0x416c616e/jsonschema
3b8e3da631c5499f20468eb9154df603afbdc2b0
[ "MIT" ]
1
2021-09-03T10:09:27.000Z
2021-09-03T10:09:27.000Z
20.201299
150
0.48441
[ [ [ "# jsonschema\n---", "_____no_output_____" ], [ "`jsonschema` is an implementation of [JSON Schema](https://json-schema.org) for Python (supporting 2.7+ including Python 3).", "_____no_output_____" ], [ "## Usage", "_____no_output_____" ] ], [ [ "from jsonschema import validate", "_____no_output_____" ], [ "# A sample schema, like what we'd get from json.load()\nschema = {\n \"type\" : \"object\",\n \"properties\" : {\n \"price\" : {\"type\" : \"number\"},\n \"name\" : {\"type\" : \"string\"},\n },\n}", "_____no_output_____" ], [ "# If no exception is raised by validate(), the instance is valid.\nvalidate({\"name\" : \"Eggs\", \"price\" : 34.99}, schema)", "_____no_output_____" ], [ "validate(\n {\"name\" : \"Eggs\", \"price\" : \"Invalid\"}, schema\n)", "_____no_output_____" ] ], [ [ "It can also be used from console:", "_____no_output_____" ] ], [ [ "!echo '{\"name\" : \"Eggs\", \"price\" : 34.99}' > /tmp/sample.json", "_____no_output_____" ], [ "!echo '{\"type\" : \"object\", \"properties\" : {\"price\" : {\"type\" : \"number\"}, \"name\" : {\"type\" : \"string\"}}}' > /tmp/sample.schema", "_____no_output_____" ], [ "!jsonschema -i /tmp/sample.json /tmp/sample.schema", "_____no_output_____" ] ], [ [ "## Do your own experiments here...", "_____no_output_____" ], [ "Try `jsonschema` youself by adding your code below and running your own experiments 👇", "_____no_output_____" ] ], [ [ "import jsonschema\n\n# your code here\njsonschema.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ] ]
cb66fb4c754846a680a86cb82bbe6f3511244356
2,052
ipynb
Jupyter Notebook
Python Absolute Beginner/Module_2.2_Required_Code.ipynb
Mt9555/pythonteachingcode
613391c4c263afa34d440b3c120d9a446471b9ad
[ "MIT" ]
12
2019-08-23T18:52:20.000Z
2022-02-23T18:55:27.000Z
Python Absolute Beginner/Module_2.2_Required_Code.ipynb
Mt9555/pythonteachingcode
613391c4c263afa34d440b3c120d9a446471b9ad
[ "MIT" ]
null
null
null
Python Absolute Beginner/Module_2.2_Required_Code.ipynb
Mt9555/pythonteachingcode
613391c4c263afa34d440b3c120d9a446471b9ad
[ "MIT" ]
510
2019-05-23T17:45:22.000Z
2022-03-16T02:13:45.000Z
32.571429
380
0.60039
[ [ [ "# Module 2 Required Coding Activity \n\n| Requirements | \n|:-------------------------------| \n| **NOTE:** This program requires a **function** be defined, created and called. The call will send values based on user input. The function call must capture a `return` value that is used in print output. The function will have parameters and `return` a string and should otherwise use code syntax covered in module 2. | \n \n## Program: fishstore()\ncreate and test fishstore()\n- **fishstore() takes 2 string arguments: fish & price**\n- **fishstore returns a string in sentence form** \n- **gather input for fish_entry and price_entry to use in calling fishstore()**\n- **print the return value of fishstore()**\n>example of output: **`Fish Type: Guppy costs $1`**", "_____no_output_____" ] ], [ [ "# [ ] create, call and test fishstore() function \n", "_____no_output_____" ] ], [ [ "When finished and tested, copy your code to the clipboard on your computer. Then, create a python file (.py) in Visual Studio Code by selecting New File and saving the file with a .py extension. Then, paste in your code and test it. Finally, save the file and upload it to D2L to submit. Be sure to test that it works. Use this same process for all Required Code Activities.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ] ]
cb66fc4c986f05e717eabaf8854906eb29701ac7
132
ipynb
Jupyter Notebook
01-Lesson-Plans/07-SQL/3/Activities/08-Stu_Feeding_Pandas_SQL/Solved/stu_feeding_pandas_sql.ipynb
tatianegercina/FinTech
b40687aa362d78674e223eb15ecf14bc59f90b62
[ "ADSL" ]
1
2021-04-13T07:14:34.000Z
2021-04-13T07:14:34.000Z
01-Lesson-Plans/07-SQL/3/Activities/08-Stu_Feeding_Pandas_SQL/Solved/stu_feeding_pandas_sql.ipynb
tatianegercina/FinTech
b40687aa362d78674e223eb15ecf14bc59f90b62
[ "ADSL" ]
2
2021-06-02T03:14:19.000Z
2022-02-11T23:21:24.000Z
01-Lesson-Plans/07-SQL/3/Activities/08-Stu_Feeding_Pandas_SQL/Solved/stu_feeding_pandas_sql.ipynb
tatianegercina/FinTech
b40687aa362d78674e223eb15ecf14bc59f90b62
[ "ADSL" ]
1
2021-05-07T13:26:50.000Z
2021-05-07T13:26:50.000Z
33
75
0.886364
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb671869dbefab2449d1e353ca0bfb98d17410de
298,234
ipynb
Jupyter Notebook
examples/notebooks/01_intro.ipynb
nogueirapeterson/JUDI.jl
19a3af0d5501e2c5d5e4f85226c755654eee9be9
[ "MIT" ]
null
null
null
examples/notebooks/01_intro.ipynb
nogueirapeterson/JUDI.jl
19a3af0d5501e2c5d5e4f85226c755654eee9be9
[ "MIT" ]
null
null
null
examples/notebooks/01_intro.ipynb
nogueirapeterson/JUDI.jl
19a3af0d5501e2c5d5e4f85226c755654eee9be9
[ "MIT" ]
null
null
null
527.847788
220,766
0.934065
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb67210c20bae4920d36cd2475d9e3c38c399f68
12,777
ipynb
Jupyter Notebook
book/_build/jupyter_execute/tutorials/tutorials/Train_networks_tutorial_v1.0.1.ipynb
jeremyforest/annolid
88bb528ee5a39a84a08631b27b934191a8822048
[ "MIT" ]
null
null
null
book/_build/jupyter_execute/tutorials/tutorials/Train_networks_tutorial_v1.0.1.ipynb
jeremyforest/annolid
88bb528ee5a39a84a08631b27b934191a8822048
[ "MIT" ]
null
null
null
book/_build/jupyter_execute/tutorials/tutorials/Train_networks_tutorial_v1.0.1.ipynb
jeremyforest/annolid
88bb528ee5a39a84a08631b27b934191a8822048
[ "MIT" ]
null
null
null
27.715835
415
0.592706
[ [ [ "<a href=\"https://colab.research.google.com/github/healthonrails/annolid/blob/main/docs/tutorials/Train_networks_tutorial_v1.0.1.ipynb\" target=\"_blank\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n", "_____no_output_____" ], [ "# Annolid (A segmenation based on mutiple animal tracking package) \n\n\nIn this tutorial, we will show how to track multiple animals by detection and instance segmentation. The instance segmenatation on images and video is based on [YOLACT](https://github.com/dbolya/yolact).\n\n## Runtime environment in Google Colab\nColab is google's free version of Jupyter notebook. \nThis notebook is only tested inside Colab. It might not run in your workstation esp if you are running Windows system. \n\n### How to use the free GPU?\n- Click **Runtime** > **Change Runtime Type**\n- Choose **GPU** > **Save**\n\n## YOLACT(You Only Look At CoefficienTs)\nA simple, fully convolutional model for real-time instance segmentation. This is the code for their papers: \n- [YOLACT: Real-time Instance Segmentation](https://arxiv.org/abs/1904.02689)\n- [YOLACT++: Better Real-time Instance Segmentation](https://arxiv.org/abs/1912.06218)\n\n## Reference\n```\n@inproceedings{yolact-iccv2019,\n author = {Daniel Bolya and Chong Zhou and Fanyi Xiao and Yong Jae Lee},\n title = {YOLACT: {Real-time} Instance Segmentation},\n booktitle = {ICCV},\n year = {2019},\n}\n```\n```\n@misc{yolact-plus-arxiv2019,\n title = {YOLACT++: Better Real-time Instance Segmentation},\n author = {Daniel Bolya and Chong Zhou and Fanyi Xiao and Yong Jae Lee},\n year = {2019},\n eprint = {1912.06218},\n archivePrefix = {arXiv},\n primaryClass = {cs.CV}\n}\n```\nThis notebook was inspired and modified from https://colab.research.google.com/drive/1ncRxvmNR-iTtQCscj2UFSGV8ZQX_LN0M. \nhttps://www.immersivelimit.com/tutorials/yolact-with-google-colab", "_____no_output_____" ], [ "# Install required packages", "_____no_output_____" ] ], [ [ "# Cython needs to be installed before pycocotools\n!pip install cython\n!pip install opencv-python pillow pycocotools matplotlib \n!pip install -U PyYAML", "_____no_output_____" ], [ "!nvidia-smi", "_____no_output_____" ], [ "# DCNv2 will not work if Pytorch is greater than 1.4.0\n!pip install torchvision==0.5.0\n!pip install torch==1.4.0", "_____no_output_____" ] ], [ [ "## Clone and install Annolid from GitHub", "_____no_output_____" ] ], [ [ "# The root folder\n%cd /content\n# Clone the repo\n!git clone --recurse-submodules https://github.com/healthonrails/annolid.git", "_____no_output_____" ], [ "# install annolid\n%cd /content/annolid/\n!pip install -e .", "_____no_output_____" ] ], [ [ "### Please uncomment the following cell and update opencv-python in Colab for the errors as follows.\nFile \"eval.py\", line 804, in cleanup_and_exit cv2.destroyAllWindows() cv2.error: OpenCV(4.1.2) /io/opencv/modules/highgui/src/window.cpp:645: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvDestroyAllWindows'", "_____no_output_____" ] ], [ [ "#!pip install -U opencv-python", "_____no_output_____" ] ], [ [ "## DCNv2\nIf you want to use YOLACT++, compile deformable convolutional layers (from DCNv2).\n\nNote: Make sure you have selected GPU option as discribed in the previous cell.", "_____no_output_____" ] ], [ [ "# Change to the DCNv2 directory\n%cd /content/annolid/annolid/segmentation/yolact/external/DCNv2\n\n# Build DCNv2\n!python setup.py build develop", "_____no_output_____" ] ], [ [ "## Download Pretrained Weights\nWe need to download pre-trained weights for inference. The creator of the GitHub repo shared them on Google Drive. We're going to use a **gdown** to easily access the Drive file from Colab.\n", "_____no_output_____" ] ], [ [ "# Make sure we're in the yolact folder\n%cd /content/annolid/annolid/segmentation/\n\n# Create a new directory for the pre-trained weights\n!mkdir -p /content/annolid/annolid/segmentation/yolact/weights\n\n# Download the file\n!gdown --id 1ZPu1YR2UzGHQD0o1rEqy-j5bmEm3lbyP -O ./yolact/weights/yolact_plus_resnet50_54_800000.pth", "_____no_output_____" ] ], [ [ "## Train a model\nYou can let the model traing for a few hours. Click the stop by for the cell will interrupt the training and save a interrupted model. \nThen you can eval the model based with a save model in the yolact/weigths folder. ", "_____no_output_____" ] ], [ [ "# Check the GPU availbe for your run\n!nvidia-smi", "_____no_output_____" ] ], [ [ "## Download an example dataset", "_____no_output_____" ] ], [ [ "#https://drive.google.com/file/d/1_kkJ8rlnoMymj0uw8VZkVEuFIMfLDwPh/view?usp=sharing\n!gdown --id 1_kkJ8rlnoMymj0uw8VZkVEuFIMfLDwPh -O /content/novelctrl_coco_dataset.zip", "_____no_output_____" ], [ "%%shell\n#rm -rf /content/novelctrl_coco_dataset//\n#rm -rf /content/annolid/annolid/datasets/novelctrl_coco_dataset\nunzip /content/novelctrl_coco_dataset.zip -d /content/novelctrl_coco_dataset/\n# the following command is only for the demo dataset with relative \n# paths to the dataset in the dataset data.yaml file.\nmv /content/novelctrl_coco_dataset/novelctrl_coco_dataset/ /content/annolid/annolid/datasets/", "_____no_output_____" ] ], [ [ "\nNote please change the path highlighted with ** ** as in the e.g. config data.yaml file to your dataset's location. \n```bash\nDATASET:\n name: 'novelctrl'\n train_info: '**/Users/xxxxxx/xxxxxx/novelctrl_coco_dataset/***train/annotations.json'\n train_images: '**/Users/xxxxxx/xxxxxx/novelctrl_coco_dataset/**train'\n valid_info: '**/Users/xxxxxx/xxxxxx/novelctrl_coco_dataset/**valid/annotations.json'\n valid_images: '**/Users/xxxxxx/xxxxxx/novelctrl_coco_dataset/**valid'\n class_names: ['nose', 'left_ear', 'right_ear', 'centroid', 'tail_base', 'tail_end', 'grooming', 'rearing', 'object_investigation', 'left_lateral', 'right_lateral', 'wall_1', 'wall_2', 'wall_3', 'wall_4', 'object_1', 'object_2', 'object_3', 'object_4', 'object_5', 'object_6', 'mouse']\nYOLACT:\n name: 'novelctrl'\n dataset: 'dataset_novelctrl_coco'\n max_size: 512\n\n```", "_____no_output_____" ], [ "## Start Tensorboard", "_____no_output_____" ] ], [ [ "# Start tensorboard for visualization of training\n%cd /content/annolid/annolid/segmentation/yolact/\n%load_ext tensorboard\n%tensorboard --logdir /content/annolid/runs/logs ", "_____no_output_____" ], [ "%cd /content/annolid/annolid/segmentation/yolact/\n!python train.py --config=../../datasets/novelctrl_coco_dataset/data.yaml --batch_size=16 --keep_latest_interval=100 # --resume=weights/novelctrl_244_2202_interrupt.pth --start_iter=244", "_____no_output_____" ] ], [ [ "## Mount your GOOGLE Drive", "_____no_output_____" ] ], [ [ "from google.colab import drive\ndrive.mount('/content/drive')", "_____no_output_____" ] ], [ [ "## Save a trained model to your Google Drive\nPlease replace and put your_model_xxx.pth", "_____no_output_____" ] ], [ [ "# e.g. \n!cp /content/annolid/annolid/segmentation/yolact/weights/your_model_xxxx.pth /content/drive/My\\ Drive", "_____no_output_____" ], [ "# optional\n#!cp /content/annolid/annolid/segmentation/yolact/weights/resnet50-19c8e357.pth /content/drive/My\\ Drive", "_____no_output_____" ] ], [ [ "## Download the original video and test it based on your trained model", "_____no_output_____" ] ], [ [ "# https://drive.google.com/file/d/1_UDnyYKQplOLMzv1hphk1gVqepmLeyGD/view?usp=sharing\n!gdown --id 1_UDnyYKQplOLMzv1hphk1gVqepmLeyGD -O /content/novelctrl.mkv", "_____no_output_____" ], [ "!python eval.py --trained_model=weights/novelctrl_xxxx_xxxx.pth --config=../../datasets/novelctrl_coco/data.yaml --score_threshold=0.15 --top_k=9 --video_multiframe=1 --video=/content/novelctrl.mkv:novelctrl_tracked.mkv --display_mask=False --mot", "_____no_output_____" ] ], [ [ "The output results are located at /content/annolid/annolid/segmentation/yolact/results.\n\ntracking_results.csv\n\nxxxx_video_tracked.mp4", "_____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" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
cb6728f501e569e97947c60991552527e9c13e2b
141,077
ipynb
Jupyter Notebook
Model_Selection_with_Yellowbric_preliminaryMLscript_2013.ipynb
georgetown-analytics/Paddle-Your-Loan-Canoe
62b40c28ea9ff757a4fbcd31f6e899670f35df6b
[ "MIT" ]
null
null
null
Model_Selection_with_Yellowbric_preliminaryMLscript_2013.ipynb
georgetown-analytics/Paddle-Your-Loan-Canoe
62b40c28ea9ff757a4fbcd31f6e899670f35df6b
[ "MIT" ]
null
null
null
Model_Selection_with_Yellowbric_preliminaryMLscript_2013.ipynb
georgetown-analytics/Paddle-Your-Loan-Canoe
62b40c28ea9ff757a4fbcd31f6e899670f35df6b
[ "MIT" ]
null
null
null
148.815401
14,660
0.830327
[ [ [ "### Model Selection\nIn order to select the best model for our data, I am going to look at scores for a variety of scikit-learn models and compare them using visual tools from Yellowbrick. ", "_____no_output_____" ], [ "### Imports", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport warnings\nwarnings.filterwarnings('ignore')\nimport os\nimport pandas as pd\n\nfrom sklearn.metrics import f1_score\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.svm import LinearSVC, NuSVC, SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder\nfrom sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB\nfrom sklearn.linear_model import LogisticRegressionCV, LogisticRegression, SGDClassifier\nfrom sklearn.ensemble import BaggingClassifier, ExtraTreesClassifier, RandomForestClassifier\n\nfrom yellowbrick.classifier import ClassificationReport", "_____no_output_____" ] ], [ [ "### About the Data", "_____no_output_____" ], [ "I am using Home Mortgage Disclosure Act (HMDA) data for one year 2013,sample of 25,000 observations. https://www.consumerfinance.gov/data-research/hmda/explore \n\nLet's load the data:", "_____no_output_____" ] ], [ [ "dataset = pd.read_csv(\"/Users/tamananaheeme/Desktop/fixtures/hmda2013sample.csv\")\ndataset.head(5)", "_____no_output_____" ], [ "dataset['action_taken'] = dataset.action_taken_name.apply(lambda x: 1 if x in ['Loan purchased by the institution', 'Loan originated'] else 0)\npd.crosstab(dataset['action_taken_name'],dataset['action_taken'], margins=True)", "_____no_output_____" ], [ "print(dataset.describe())", " Unnamed: 0 tract_to_msamd_income rate_spread population \\\ncount 25000.000000 25000.000000 670.000000 25000.000000 \nmean 12499.500000 117.659708 2.532134 5330.473960 \nstd 7217.022701 42.180985 1.541076 2393.740737 \nmin 0.000000 13.040000 1.500000 158.000000 \n25% 6249.750000 90.489998 1.660000 3803.000000 \n50% 12499.500000 110.830002 1.920000 4972.000000 \n75% 18749.250000 138.389999 2.792500 6425.250000 \nmax 24999.000000 405.700012 13.500000 33201.000000 \n\n minority_population number_of_owner_occupied_units \\\ncount 25000.000000 25000.000000 \nmean 30.654104 1409.926200 \nstd 25.230882 694.167618 \nmin 1.000000 6.000000 \n25% 10.940000 929.750000 \n50% 22.129999 1330.000000 \n75% 43.320000 1780.000000 \nmax 99.870003 6886.000000 \n\n number_of_1_to_4_family_units loan_amount_000s \\\ncount 25000.00000 25000.000000 \nmean 1821.22132 216.371720 \nstd 845.79343 210.610144 \nmin 1.00000 1.000000 \n25% 1275.75000 101.000000 \n50% 1717.00000 169.000000 \n75% 2261.00000 277.000000 \nmax 9464.00000 10000.000000 \n\n hud_median_family_income applicant_income_000s sequence_number \\\ncount 25000.000000 25000.000000 2.500000e+04 \nmean 70200.892000 113.075120 2.014616e+05 \nstd 16193.235984 166.405326 4.080680e+05 \nmin 16400.000000 1.000000 1.000000e+00 \n25% 60000.000000 52.000000 2.209750e+03 \n50% 66000.000000 82.000000 2.297950e+04 \n75% 77800.000000 129.000000 1.727290e+05 \nmax 112200.000000 8814.000000 2.242964e+06 \n\n co_applicant_race_name_5 co_applicant_race_name_4 \\\ncount 0.0 0.0 \nmean NaN NaN \nstd NaN NaN \nmin NaN NaN \n25% NaN NaN \n50% NaN NaN \n75% NaN NaN \nmax NaN NaN \n\n co_applicant_race_name_3 census_tract_number as_of_year \\\ncount 0.0 25000.000000 25000.0 \nmean NaN 2145.460709 2013.0 \nstd NaN 3241.109438 0.0 \nmin NaN 1.000000 2013.0 \n25% NaN 90.000000 2013.0 \n50% NaN 251.030000 2013.0 \n75% NaN 3462.015000 2013.0 \nmax NaN 9813.000000 2013.0 \n\n application_date_indicator applicant_race_name_5 action_taken \ncount 25000.000000 0.0 25000.000000 \nmean 0.242240 NaN 0.686800 \nstd 0.652546 NaN 0.463804 \nmin 0.000000 NaN 0.000000 \n25% 0.000000 NaN 0.000000 \n50% 0.000000 NaN 1.000000 \n75% 0.000000 NaN 1.000000 \nmax 2.000000 NaN 1.000000 \n" ], [ "features = ['tract_to_msamd_income', \n 'population', \n 'minority_population', \n 'number_of_owner_occupied_units', \n 'number_of_1_to_4_family_units', \n 'loan_amount_000s', \n 'hud_median_family_income', \n 'applicant_income_000s']\n\ntarget = ['action_taken']\n", "_____no_output_____" ], [ "# Extract our X and y data\nX = dataset[features]\ny = dataset[target]\n\nprint(X.shape, y.shape)", "(25000, 8) (25000, 1)\n" ], [ "# add line of code to fill in missing values\nX.fillna(X.mean(), inplace=True)", "_____no_output_____" ], [ "X.describe()", "_____no_output_____" ] ], [ [ "### Modeling and Evaluation\n", "_____no_output_____" ] ], [ [ "def score_model(X, y, estimator, **kwargs):\n \"\"\"\n Test various estimators.\n \"\"\" \n\n model = Pipeline([\n ('estimator', estimator)\n ])\n\n # Instantiate the classification model and visualizer\n model.fit(X, y, **kwargs) \n \n expected = y\n predicted = model.predict(X)\n \n # Compute and return F1 (harmonic mean of precision and recall)\n print(\"{}: {}\".format(estimator.__class__.__name__, f1_score(expected, predicted)))", "_____no_output_____" ], [ "# Try them all!\n\nmodels = [\n GaussianNB(), BernoulliNB(), MultinomialNB(),\n LogisticRegression(solver='lbfgs', max_iter=4000), LogisticRegressionCV(cv=3, max_iter=4000), \n BaggingClassifier(), ExtraTreesClassifier(n_estimators=100), \n RandomForestClassifier(n_estimators=100)\n]\n\nfor model in models:\n score_model(X, y, model)", "GaussianNB: 0.7935713744219545\nBernoulliNB: 0.8143229784206782\nMultinomialNB: 0.5886471787899388\nLogisticRegression: 0.8140529241294124\nLogisticRegressionCV: 0.8140705904707616\nBaggingClassifier: 0.9903065234477338\nExtraTreesClassifier: 0.9996212893640574\nRandomForestClassifier: 0.9996214658008911\n" ] ], [ [ "### Visual Model Evaluation\n", "_____no_output_____" ] ], [ [ "def visualize_model(X, y, estimator):\n \"\"\"\n Test various estimators.\n \"\"\" \n model = Pipeline([\n ('estimator', estimator)\n ])\n\n # Instantiate the classification model and visualizer\n visualizer = ClassificationReport(\n model, classes=[1,0], \n cmap=\"greens\", size=(600, 360)\n )\n visualizer.fit(X, y) \n visualizer.score(X, y)\n visualizer.poof() \n\nfor model in models:\n visualize_model(X, y, model)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
cb6732a25372a0d083182224e2af01ca1aaa7260
63,914
ipynb
Jupyter Notebook
ace_cruise_track_data_processing.ipynb
Swiss-Polar-Institute/science-data-utils
6a85570ee586fa1ba1644ba2b1c9dea3a5257eae
[ "MIT" ]
null
null
null
ace_cruise_track_data_processing.ipynb
Swiss-Polar-Institute/science-data-utils
6a85570ee586fa1ba1644ba2b1c9dea3a5257eae
[ "MIT" ]
null
null
null
ace_cruise_track_data_processing.ipynb
Swiss-Polar-Institute/science-data-utils
6a85570ee586fa1ba1644ba2b1c9dea3a5257eae
[ "MIT" ]
null
null
null
39.067237
1,413
0.479879
[ [ [ "# Antarctic Circumnavigation Expedition Cruise Track data processing", "_____no_output_____" ], [ "## GLONASS and Trimble GPS data", "_____no_output_____" ], [ "Follow the steps as described here: http://epic.awi.de/48174/", "_____no_output_____" ], [ "Import relevant packages", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport csv\nimport MySQLdb\nimport datetime\nimport math\nimport numpy as np", "_____no_output_____" ] ], [ [ "### STEP 1 - Extract data from database", "_____no_output_____" ], [ "Import data from a database table into a dataframe", "_____no_output_____" ] ], [ [ "def get_data_from_database(query, db_connection):\n \n dataframe = pd.read_sql(query, con=db_connection)\n\n return dataframe", "_____no_output_____" ] ], [ [ "**GPS data**", "_____no_output_____" ] ], [ [ "query_trimble = 'select * from ship_data_gpggagpsfix where device_id=63 order by date_time;'\npassword = input()", "ace\n" ], [ "db_connection = MySQLdb.connect(host = 'localhost', user = 'ace', passwd = password, db = 'ace2016', port = 3306); \n\ngpsdb_df = get_data_from_database(query_trimble, db_connection)\n#gpsdb_df_opt = optimise_dataframe(gpsdb_df_opt)", "_____no_output_____" ] ], [ [ "Preview data", "_____no_output_____" ] ], [ [ "gpsdb_df.sample(5)", "_____no_output_____" ] ], [ [ "Number of data points output", "_____no_output_____" ] ], [ [ "len(gpsdb_df)", "_____no_output_____" ] ], [ [ "Dates and times covered by the Trimble data set: ", "_____no_output_____" ] ], [ [ "print(\"Start date:\", gpsdb_df['date_time'].min())\nprint(\"End date:\", gpsdb_df['date_time'].max())", "Start date: 2016-12-21 06:59:14.440000\nEnd date: 2017-04-11 08:07:13.600000\n" ] ], [ [ "Output the data into monthly files (to be able to plot them to visually screen the obvious outliers).", "_____no_output_____" ] ], [ [ "gpsdb_df.dtypes", "_____no_output_____" ], [ "gpsdb_df['date_time_day'] = gpsdb_df['date_time'].dt.strftime('%Y-%m-%d')", "_____no_output_____" ], [ "gpsdb_df.sample(5)", "_____no_output_____" ], [ "days = gpsdb_df.groupby('date_time_day')\nfor day in days.groups:\n path = '/home/jen/ace_trimble_gps_' + str(day) + '.csv'\n days.get_group(day).to_csv(path, index=False)", "_____no_output_____" ] ], [ [ "**GLONASS data**", "_____no_output_____" ] ], [ [ "query_glonass = 'select * from ship_data_gpggagpsfix where device_id=64;'\n\npassword = input()\n", "_____no_output_____" ], [ "db_connection = MySQLdb.connect(host = 'localhost', user = 'ace', passwd = password, db = 'ace2016', port = 3306); \n\nglonassdb_df = get_data_from_database(query_glonass, db_connection)", "_____no_output_____" ] ], [ [ "Preview data", "_____no_output_____" ] ], [ [ "glonassdb_df.sample(5)", "_____no_output_____" ] ], [ [ "Number of data points output", "_____no_output_____" ] ], [ [ "len(glonassdb_df)", "_____no_output_____" ] ], [ [ "Dates and times covered by the GLONASS data set: ", "_____no_output_____" ] ], [ [ "print(\"Start date:\", glonassdb_df['date_time'].min())\nprint(\"End date:\", glonassdb_df['date_time'].max())", "_____no_output_____" ] ], [ [ "Output the data into monthly files (to be able to plot them to visually screen the obvious outliers).", "_____no_output_____" ] ], [ [ "glonassdb_df['date_time_day'] = glonassdb_df['date_time'].dt.strftime('%Y-%m-%d')", "_____no_output_____" ], [ "glonassdb_df.sample(5)", "_____no_output_____" ], [ "days = glonassdb_df.groupby('date_time_day')\nfor day in days.groups:\n path = '/home/jen/ace_glonass_' + str(day) + '.csv'\n days.get_group(day).to_csv(path, index=False)", "_____no_output_____" ] ], [ [ "### STEP 2 - Visual inspection", "_____no_output_____" ], [ "### Trimble GPS", "_____no_output_____" ], [ "Data in the form of the daily csv files, were imported into QGIS mapping software in order to manually visually inspect the data points. This was done at a resolution of 1:100,000.\n\nThere were no obvious outlying points. \nNumber of points flagged as outliers: 0\n\nThe following sections were identified as unusual and have been classified in the table below: \n| Start date and time (UTC) | End date and time (UTC) | Potential problem |\n|---------|-----------|----------|\n| 2016-12-21 10:15:46.620 | 2016-12-21 10:16:35.620 | Overlapping track |\n| 2016-12-21 07:37:16.470 | 2016-12-21 07:40:02.470 | Overlapping track |\n| 2016-12-22 04:43:10.010 | 2016-12-22 04:43:14.010 | Overlapping track |\n| 2016-12-22 09:38:40.270 | 2016-12-22 09:38:41.270 | Strange gap |\n| 2016-12-23 00:15:22.060 | 2016-12-23 00:15:33.060 | Overlapping track |\n| 2016-12-23 04:57:57.310 | 2016-12-23 04:57:58.310 | Large gap |\n| 2016-12-23 05:05:05.310 | 2016-12-23 05:11:43.540 | Overlapping track |\n| 2016-12-23 05:30:01.560 | 2016-12-23 05:30:04.560 | Large gap |\n| 2016-12-25 06:04:50.900 | 2016-12-25 06:09:52.980 | Overlapping track |\n| 2016-12-29 12:57:59.390 | 2016-12-29 14:57:34.730 | Strange diversion |\n| 2016-12-30 04:53:24.840 | 2016-12-30 08:51:12.670 | Strange diversion, missing data |\n| 2016-12-31 00:51:37.580 | 2016-12-31 00:51:39.580 | |\n| 2017-01-01 11:54:29.820 | 2017-01-01 11:54:41.820 | Overlapping track |\n| 2017-01-01 22:51:51.680 | 2017-01-01 22:54:41.700 | Strange deflection |\n| 2017-01-01 22:56:05.700 | 2017-01-01 22:59:57.700 | Strange deflection |\n| 2017-01-04 00:34:30.360 | 2017-01-04 00:34:33.360 | Large move |\n| 2017-01-13 08:26:40.850 | 2017-01-13 08:30:36.840 | Strange deflection |\n| 2017-03-11 06:47:22.300 | 2017-03-11 08:21:40.970 | Strange deflection |\n| 2017-03-16 17:51:36.490 | 2017-03-16 18:12:21.470 | Gap with jump |\n| 2017-03-17 15:29:07.620 | 2017-03-17 15:29:10.620 | Gap with jump |\n| 2017-03-18 04:07:31.290 | 2017-03-18 04:07:32.290 | Gap with jump |\n| 2017-03-18 12:43:22.100 | 2017-03-18 12:43:42.100 | Overlapping track |\n| 2017-03-18 13:01:04.100 | 2017-03-18 19:09:28.440 | Large gap with large time difference |\n| 2017-03-24 10:13:24.720 | 2017-03-24 10:13:25.720 | Gap with jump |\n| 2017-03-25 10:07:08.990 | 2017-03-25 10:07:15.990 | Gap with jump |\n| 2017-03-26 22:25:49.940 | 2017-03-26 22:25:50.940 | Gap with jump |\nThese points have not been flagged but will be returned to later on in the processing. ", "_____no_output_____" ], [ "### GLONASS", "_____no_output_____" ], [ "Data in the form of the daily csv files, were imported into QGIS mapping software in order to manually visually inspect the data points. This was done at a resolution of 1:100,000.\n\nThere were no obvious outlying points. \nNumber of points flagged as outliers: 0\n \nThe following sections were identified as unusual and have been classified in the table below: \n| Start date and time (UTC) | End date and time (UTC) | Potential problem |\n|---------|-----------|----------|\n| 2017-04-06 15:26:30 | 2017-04-06 15:26:32 | Gap with jump |\n| 2017-04-06 18:22:07 | 2017-04-06 18:22:09 | Gap with jump |\n| 2017-04-06 21:41:21 | 2017-04-06 21:41:45 | Strange deflection |\n| 2017-04-07 15:25:06 | 2017-04-07 15:25:13 | Strange deflection |\n| 2017-04-08 04:12:44 | 2017-04-08 04:13:27 | Strange deflection |\n| 2017-04-08 05:01:34 | 2017-04-08 05:01:49 | Strange deflection |\n| 2017-04-08 18:42:12 | 2017-04-08 18:43:04 | Strange deflection |\n| 2017-04-08 18:56:02 | 2017-04-08 18:57:27 | Strange deflection |\n| 2017-04-08 19:00:26 | 2017-04-08 19:01:03 | Strange deflection |\n| 2017-04-08 19:05:31 | 2017-04-08 19:05:46 | Strange deflection |\n| 2017-04-10 02:43:40 | 2017-04-10 02:44:25 | Strange deflection |", "_____no_output_____" ], [ "### STEP 3 - Motion data correction", "_____no_output_____" ], [ "### STEP 4 - Automated data filtering", "_____no_output_____" ], [ "Each data point will be compared with the one before and after to automatically filter out points that are out of the conceivable range of the ship's movement.'\n\nThe second of two consecutive points to be flagged as \"likely incorrect\" when any of the following cases occur: \n - speed between two points >= 20 knots\n - acceleration between two points >= 1 ms^-2\n - direction between two points >= 5 degrees", "_____no_output_____" ] ], [ [ "# Test\ndf_test = gpsdb_df.head(10000)\ndf_test.head(5)", "_____no_output_____" ], [ "def get_location(datetime, position_df):\n \"\"\"Create a tuple of the date_time, latitude and longitude of a location in a dataframe from a given date_time.\"\"\"\n \n latitude = position_df[position_df.date_time == datetime].latitude.item()\n longitude = position_df[position_df.date_time == datetime].longitude.item()\n \n location = (datetime, latitude, longitude)\n \n return location", "_____no_output_____" ], [ "def calculate_distance(origin, destination):\n \"\"\"Calculate the haversine or great-circle distance in metres between two points with latitudes and longitudes, where they are known as the origin and destination.\"\"\"\n \n datetime1, lat1, lon1 = origin\n datetime2, lat2, lon2 = destination\n radius = 6371 # km\n \n dlat = math.radians(lat2 - lat1)\n dlon = math.radians(lon2 - lon1)\n a = math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(math.radians(lat1)) \\\n * math.cos(math.radians(lat2)) * math.sin(dlon / 2) * math.sin(dlon / 2)\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))\n d = radius * c # Distance in km\n d_m = d*1000 # Distance in metres\n \n return d_m", "_____no_output_____" ], [ "def knots_two_points(origin, destination):\n \"\"\"Calculate the speed in knots between two locations which are dictionaries containing latitude, longitude and date_time.\"\"\"\n \n distance = calculate_distance(origin, destination)\n \n datetime1_timestamp, lat1, lon1 = origin\n datetime2_timestamp, lat2, lon2 = destination\n #datetime1 = datetime.datetime.strptime(datetime_str1,\"%Y-%m-%d %H:%M:%S.%f\")\n #datetime2 = datetime.datetime.strptime(datetime_str2,\"%Y-%m-%d %H:%M:%S.%f\")\n \n datetime1 = datetime1_timestamp.timestamp()\n datetime2 = datetime2_timestamp.timestamp()\n \n seconds = abs((datetime1) - (datetime2))\n #seconds = abs((datetime_str1)-(datetime_str2)).total_seconds()\n conversion = 3600/1852 # convert 1 ms-1 to knots (nautical miles per hour; 1 nm = 1852 metres)\n speed_knots = (distance/seconds) * conversion\n \n if seconds > 0:\n return speed_knots\n else:\n return \"N/A\"", "_____no_output_____" ], [ "destination = (Timestamp('2016-12-21 06:59:14.440000'), -35.8380768456667, 18.0307165761667)\norigin = (Timestamp('2016-12-21 06:59:14.440000'), -35.8380768456667, 18.0307165761667)\nknots_two_points(origin, destination)", "_____no_output_____" ], [ "def set_utc(date_time):\n \"\"\"Set the timezone to be UTC.\"\"\"\n utc = datetime.timezone(datetime.timedelta(0))\n date_time = date_time.replace(tzinfo=utc)\n return date_time", "_____no_output_____" ], [ "def analyse_speed(position_df):\n \"\"\"Analyse the cruise track to ensure each point lies within a reasonable distance and direction from the previous point.\"\"\"\n \n total_data_points = len(position_df)\n \n earliest_date_time = position_df['date_time'].min()\n latest_date_time = position_df['date_time'].max()\n\n current_date = earliest_date_time\n\n previous_position = get_location(earliest_date_time, position_df)\n datetime_previous, latitude_previous, longitude_previous = previous_position\n \n count_speed_errors = 0\n \n line_number = -1\n for position in position_df.itertuples():\n line_number += 1\n if line_number == 0:\n continue\n\n current_position = position[2:5]\n row_index = position[0]\n \n #print(current_position)\n speed_knots = knots_two_points(previous_position, current_position)\n\n error_message = \"\"\n\n if speed_knots == \"N/A\":\n error_message = \"No speed?\"\n position_df.at[row_index, 'measureland_qualifier_flag_speed'] = 9\n position_df.loc[position_df['id'] == row_index, 'measureland_qualifier_flag_speed'] = 9\n print(position_df['id' == row_index])\n elif speed_knots >= 20:\n error_message += \"** Too fast **\"\n #print(row_id)\n #print(position_df[position_df['id'] == row_id])\n position_df.loc[position_df['id'] == row_index, 'measureland_qualifier_flag_speed'] = 4\n count_speed_errors += 1\n elif speed_knots < 20:\n position_df.loc[position_df['id'] == row_index, 'measureland_qualifier_flag_speed'] = 1\n\n if error_message != \"\":\n print(\"Error {} {} ({:.4f}, {:.4f}) speed: {} knots\".format(error_message, current_position[0], current_position[1], current_position[2], speed_knots))\n\n previous_position = current_position\n \n return count_speed_errors", "_____no_output_____" ], [ "def calculate_bearing(origin, destination):\n \"\"\"Calculate the direction turned between two points.\"\"\"\n \n datetime1, lat1, lon1 = origin\n datetime2, lat2, lon2 = destination\n \n dlon = math.radians(lon2 - lon1)\n \n bearing = math.atan2(math.sin(dlon) * math.cos(math.radians(lat2)), \n math.cos(math.radians(lat1)) * math.sin(math.radians(lat2)) \n - math.sin(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.cos(dlon))\n \n bearing_degrees = math.degrees(bearing)\n \n return bearing_degrees\n ", "_____no_output_____" ], [ "def calculate_bearing_difference(current_bearing, previous_bearing):\n \"\"\"Calculate the difference between two bearings, based on bearings between 0 and 360.\"\"\"\n \n difference = current_bearing - previous_bearing\n\n while difference < -180:\n difference += 360\n while difference > 180:\n difference -= 360\n \n return difference", "_____no_output_____" ], [ "def analyse_course(position_df):\n \"\"\"Analyse the change in the course between two points regarding the bearing and acceleration - these features need information from previous points.\"\"\"\n \n total_data_points = len(position_df)\n \n earliest_date_time = position_df['date_time'].min()\n current_date = earliest_date_time\n \n previous_position = get_location(earliest_date_time, position_df)\n datetime_previous, latitude_previous, longitude_previous = previous_position\n \n previous_bearing = 0\n previous_speed_knots = 0\n\n count_bearing_errors = 0\n count_acceleration_errors = 0 \n\n line_number = -1\n for position in position_df.itertuples():\n line_number += 1\n if line_number == 0:\n continue\n \n current_position = position[2:5]\n row_index = position[0]\n\n # Calculate bearing and change in bearing\n current_bearing = calculate_bearing(previous_position, current_position)\n difference_in_bearing = calculate_bearing_difference(current_bearing, previous_bearing)\n \n # Calculate acceleration between two points\n current_speed_knots = knots_two_points(previous_position, current_position)\n\n time_difference = (current_position[0] - previous_position[0]).total_seconds()\n speed_difference_metres_per_sec = (current_speed_knots - previous_speed_knots) * (1852/3600) # convert knots to ms-1 \n \n if time_difference >0:\n acceleration = speed_difference_metres_per_sec / time_difference\n else:\n acceleration = 0\n\n # Print errors where data do not meet requirements\n error_message_bearing = \"\"\n error_message_acceleration = \"\"\n\n if difference_in_bearing == \"N/A\":\n error_message_bearing = \"No bearing?\"\n position_df.at[row_index, 'measureland_qualifier_flag_course'] = 9\n #position_df.loc[position_df['id'] == row_index, 'measureland_qualifier_flag_course'] = 9\n print(row_index)\n #print(position_df['id' == row_id])\n elif difference_in_bearing >= 5:\n error_message_bearing = \"** Turn too tight **\"\n position_df.at[row_index, 'measureland_qualifier_flag_course'] = 4\n #position_df.loc[position_df['id'] == row_index, 'measureland_qualifier_flag_course'] = 4\n print(row_index)\n #print(position_df['id' == row_id])\n count_bearing_errors += 1\n\n if error_message_bearing != \"\":\n print(\"Error: {} {} ({:.4f}, {:.4f}) bearing change: {} degrees\".format(error_message_bearing, current_position[0], current_position[1], current_position[2], difference_in_bearing))\n \n if acceleration ==\"N/A\":\n error_message_acceleration = \"No acceleration\"\n position_df.at[row_index, 'measureland_qualifier_flag_acceleration'] = 9\n #position_df.loc[position_df['id'] == row_index, 'measureland_qualifier_flag_acceleration'] = 9\n print(row_index)\n #print(position_df['id' == row_id])\n elif acceleration > 1:\n count_acceleration_errors += 1\n error_message_acceleration = \"** Acceleration to quick **\"\n position_df.at[row_index, 'measureland_qualifier_flag_acceleration'] = 4 \n #position_df.loc[position_df['id'] == row_index, 'measureland_qualifier_flag_acceleration'] = 4\n print(row_index)\n #print(position_df['id' == row_id])\n \n if error_message_acceleration != \"\":\n print(\"Error: {} {} ({:.4f}, {:.4f}) acceleration: {} ms-2\".format(error_message_acceleration, current_position[0], current_position[1], current_position[2], acceleration))\n\n previous_position = current_position\n previous_bearing = current_bearing\n previous_speed_knots = current_speed_knots\n \n return (count_bearing_errors, count_acceleration_errors)", "_____no_output_____" ], [ "analyse_speed(df_test)", "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py:543: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n self.obj[item] = s\n" ], [ "analyse_course(df_test)", "1\nError: ** Turn too tight ** 2016-12-21 06:59:15.440000 (999.0000, 18.0307) bearing change: 89.9999885944378 degrees\n1\nError: ** Acceleration to quick ** 2016-12-21 06:59:15.440000 (999.0000, 18.0307) acceleration: 20015086.79602057 ms-2\n3\nError: ** Turn too tight ** 2016-12-21 06:59:17.440000 (-35.8383, 18.0307) bearing change: 175.92133451484625 degrees\n2360\nError: ** Acceleration to quick ** 2016-12-21 07:38:34.470000 (-35.9918, 18.0735) acceleration: 766.005631429995 ms-2\n2361\nError: ** Turn too tight ** 2016-12-21 07:38:35.470000 (-35.9918, 18.0735) bearing change: 153.5151020875811 degrees\n" ], [ "df_test.head()\n#df_test.loc[df_test['id'] == 613, 'latitude'] = 99\n#df_test.at[1, 'latitude'] = 999", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb673d983982339f78a67ce1e8d76b2347e597de
16,223
ipynb
Jupyter Notebook
Section 2.2 - Condition Numbers.ipynb
jesus-lua-8/fall2021math434
e6c6931676922193a6718b51c92232a3de7fa650
[ "MIT" ]
1
2021-08-31T21:01:22.000Z
2021-08-31T21:01:22.000Z
Section 2.2 - Condition Numbers.ipynb
jesus-lua-8/fall2021math434
e6c6931676922193a6718b51c92232a3de7fa650
[ "MIT" ]
null
null
null
Section 2.2 - Condition Numbers.ipynb
jesus-lua-8/fall2021math434
e6c6931676922193a6718b51c92232a3de7fa650
[ "MIT" ]
1
2021-11-16T19:28:56.000Z
2021-11-16T19:28:56.000Z
21.290026
196
0.418048
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb673e87e4e023add577fd06bcd231b87e89216e
4,110
ipynb
Jupyter Notebook
researchmap.ipynb
m053m716/GitIO
f1cd0ebb4fbdc1ed83508df75096f3603aed1eb2
[ "MIT" ]
null
null
null
researchmap.ipynb
m053m716/GitIO
f1cd0ebb4fbdc1ed83508df75096f3603aed1eb2
[ "MIT" ]
null
null
null
researchmap.ipynb
m053m716/GitIO
f1cd0ebb4fbdc1ed83508df75096f3603aed1eb2
[ "MIT" ]
null
null
null
25.849057
274
0.545012
[ [ [ "# Leaflet cluster map of talk locations\n\nRun this from the _talks/ directory, which contains .md files of all your talks. This scrapes the location YAML field from each .md file, geolocates it with geopy/Nominatim, and uses the getorg library to output data, HTML, and Javascript for a standalone cluster map.", "_____no_output_____" ] ], [ [ "!pip install getorg --upgrade\nimport glob\nimport getorg\nfrom geopy import Nominatim", "Requirement already up-to-date: getorg in /home/vm/anaconda3/lib/python3.5/site-packages\nRequirement already up-to-date: geopy in /home/vm/.local/lib/python3.5/site-packages (from getorg)\nRequirement already up-to-date: retrying in /home/vm/.local/lib/python3.5/site-packages (from getorg)\nRequirement already up-to-date: pygithub in /home/vm/anaconda3/lib/python3.5/site-packages (from getorg)\nRequirement already up-to-date: six>=1.7.0 in /home/vm/.local/lib/python3.5/site-packages (from retrying->getorg)\nIPywidgets and ipyleaflet support enabled.\n" ], [ "g = glob.glob(\"*.md\")", "_____no_output_____" ], [ "geocoder = Nominatim()\nlocation_dict = {}\nlocation = \"\"\npermalink = \"\"\ntitle = \"\"", "_____no_output_____" ], [ "\nfor file in g:\n with open(file, 'r') as f:\n lines = f.read()\n if lines.find('location: \"') > 1:\n loc_start = lines.find('location: \"') + 11\n lines_trim = lines[loc_start:]\n loc_end = lines_trim.find('\"')\n location = lines_trim[:loc_end]\n \n \n location_dict[location] = geocoder.geocode(location)\n print(location, \"\\n\", location_dict[location])\n", "Berkeley CA, USA \n Berkeley, Alameda County, California, United States of America\nLos Angeles, CA \n LA, Los Angeles County, California, United States of America\nLondon, UK \n London, Greater London, England, UK\nSan Francisco, California \n SF, California, United States of America\n" ], [ "m = getorg.orgmap.create_map_obj()\ngetorg.orgmap.output_html_cluster_map(location_dict, folder_name=\"../researchmap\", hashed_usernames=False)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cb674d0b157c0b6efc3e55e16afccde2f2506c1f
1,816
ipynb
Jupyter Notebook
.ipynb_checkpoints/Lesson #03e -- Exercise Manipulate data-checkpoint.ipynb
Adobe-Marketing-Cloud/python-pandas-lab
363aaa9a11f8ca22b4522c28fe92abfde5c8bbe6
[ "Apache-2.0" ]
22
2015-03-12T16:13:32.000Z
2020-12-03T00:49:03.000Z
.ipynb_checkpoints/Lesson #03e -- Exercise Manipulate data-checkpoint.ipynb
Adobe-Marketing-Cloud/python-pandas-lab
363aaa9a11f8ca22b4522c28fe92abfde5c8bbe6
[ "Apache-2.0" ]
2
2015-05-07T06:50:44.000Z
2016-09-07T15:40:08.000Z
.ipynb_checkpoints/Lesson #03e -- Exercise Manipulate data-checkpoint.ipynb
Adobe-Marketing-Cloud/python-pandas-lab
363aaa9a11f8ca22b4522c28fe92abfde5c8bbe6
[ "Apache-2.0" ]
14
2015-03-11T00:08:25.000Z
2020-11-09T12:26:55.000Z
26.318841
129
0.537996
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb674f52b308571fb2f664e41498027d9ba19bc7
30,010
ipynb
Jupyter Notebook
exercises/templates/ex01/gertingold-numpy-tutorial-exercises.ipynb
adilsheraz/reinforcement_learning_course_materials
e086ae7dcee2a0c1dbb329c2b25cf583c339c75a
[ "MIT" ]
557
2020-07-20T08:38:15.000Z
2022-03-31T19:30:35.000Z
exercises/templates/ex01/gertingold-numpy-tutorial-exercises.ipynb
BochraCHEMAM/reinforcement_learning_course_materials
09a211da5707ba61cd653ab9f2a899b08357d6a3
[ "MIT" ]
7
2020-07-22T07:27:55.000Z
2021-05-12T14:37:08.000Z
exercises/templates/ex01/gertingold-numpy-tutorial-exercises.ipynb
BochraCHEMAM/reinforcement_learning_course_materials
09a211da5707ba61cd653ab9f2a899b08357d6a3
[ "MIT" ]
115
2020-09-08T17:12:25.000Z
2022-03-31T18:13:08.000Z
17.276914
153
0.476341
[ [ [ "# EuroSciPy 2018: NumPy tutorial (https://github.com/gertingold/euroscipy-numpy-tutorial)", "_____no_output_____" ], [ "## Let's do some slicing", "_____no_output_____" ] ], [ [ "mylist = list(range(10))\nprint(mylist)", "_____no_output_____" ] ], [ [ "Use slicing to produce the following outputs:", "_____no_output_____" ], [ "[2, 3, 4, 5]", "_____no_output_____" ], [ "[0, 1, 2, 3, 4]", "_____no_output_____" ], [ "[6, 7, 8, 9]", "_____no_output_____" ], [ "[0, 2, 4, 6, 8]", "_____no_output_____" ], [ "[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]", "_____no_output_____" ], [ "[7, 5, 3]", "_____no_output_____" ], [ "## Matrices and lists of lists", "_____no_output_____" ] ], [ [ "matrix = [[0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]]", "_____no_output_____" ] ], [ [ "Get the second row by slicing twice", "_____no_output_____" ], [ "Try to get the second column by slicing. ~~Do not use a list comprehension!~~", "_____no_output_____" ], [ "## Getting started", "_____no_output_____" ], [ "Import the NumPy package", "_____no_output_____" ], [ "## Create an array", "_____no_output_____" ] ], [ [ "np.lookfor('create array')", "_____no_output_____" ], [ "help(np.array) # remember Shift + Tab give a pop up help. Wh Shift + Tab ", "_____no_output_____" ] ], [ [ "Press Shift + Tab when your cursor in a Code cell. This will open a pop up with some helping text. \nWhat happens Shift + Tab is pressed a second time?", "_____no_output_____" ], [ "The variable `matrix` contains a list of lists. Turn it into an `ndarray` and assign it to the variable `myarray`. Verify that its type is correct.", "_____no_output_____" ], [ "For practicing purposes, arrays can conveniently be created with the `arange` method.", "_____no_output_____" ] ], [ [ "myarray1 = np.arange(6)\nmyarray1", "_____no_output_____" ], [ "def array_attributes(a):\n for attr in ('ndim', 'size', 'itemsize', 'dtype', 'shape', 'strides'):\n print('{:8s}: {}'.format(attr, getattr(a, attr)))", "_____no_output_____" ], [ "array_attributes(myarray1)", "_____no_output_____" ] ], [ [ "## Data types", "_____no_output_____" ], [ "Use `np.array()` to create arrays containing\n * floats\n * complex numbers\n * booleans\n * strings\n \nand check the `dtype` attribute.", "_____no_output_____" ], [ "Do you understand what is happening in the following statement?", "_____no_output_____" ] ], [ [ "np.arange(1, 160, 10, dtype=np.int8)", "_____no_output_____" ] ], [ [ "## Strides/Reshape", "_____no_output_____" ] ], [ [ "myarray2 = myarray1.reshape(2, 3)\nmyarray2", "_____no_output_____" ], [ "array_attributes(myarray2)", "_____no_output_____" ], [ "myarray3 = myarray1.reshape(3, 2)", "_____no_output_____" ], [ "array_attributes(myarray3)", "_____no_output_____" ] ], [ [ "## Views", "_____no_output_____" ], [ "Set the first entry of `myarray1` to a new value, e.g. 42.", "_____no_output_____" ], [ "What happened to `myarray2`?", "_____no_output_____" ], [ "What happens when a matrix is transposed?", "_____no_output_____" ] ], [ [ "a = np.arange(9).reshape(3, 3)\na", "_____no_output_____" ], [ "a.T", "_____no_output_____" ] ], [ [ "Check the strides!", "_____no_output_____" ] ], [ [ "a.strides", "_____no_output_____" ], [ "a.T.strides", "_____no_output_____" ] ], [ [ "## View versus copy", "_____no_output_____" ], [ "identical object", "_____no_output_____" ] ], [ [ "a = np.arange(4)\nb = a\nid(a), id(b)", "_____no_output_____" ] ], [ [ "view: a different object working on the same data", "_____no_output_____" ] ], [ [ "b = a[:]\nid(a), id(b)", "_____no_output_____" ], [ "a[0] = 42\na, b", "_____no_output_____" ] ], [ [ "an independent copy", "_____no_output_____" ] ], [ [ "a = np.arange(4)\nb = np.copy(a)\nid(a), id(b)", "_____no_output_____" ], [ "a[0] = 42\na, b", "_____no_output_____" ] ], [ [ "## Some array creation routines", "_____no_output_____" ], [ "### numerical ranges", "_____no_output_____" ], [ "`arange(`*start*, *stop*, *step*`)`, *stop* is not included in the array", "_____no_output_____" ] ], [ [ "np.arange(5, 30, 5)", "_____no_output_____" ] ], [ [ "`arange` resembles `range`, but also works for floats\n\nCreate the array [1, 1.1, 1.2, 1.3, 1.4, 1.5]", "_____no_output_____" ], [ "`linspace(`*start*, *stop*, *num*`)` determines the step to produce *num* equally spaced values, *stop* is included by default\n\nCreate the array [1., 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.]", "_____no_output_____" ], [ "For equally spaced values on a logarithmic scale, use `logspace`.", "_____no_output_____" ] ], [ [ "np.logspace(-2, 2, 5)", "_____no_output_____" ], [ "np.logspace(0, 4, 9, base=2)", "_____no_output_____" ] ], [ [ "### Application", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt", "_____no_output_____" ], [ "%matplotlib inline", "_____no_output_____" ], [ "x = np.linspace(0, 10, 100)\ny = np.cos(x)", "_____no_output_____" ], [ "plt.plot(x, y)", "_____no_output_____" ] ], [ [ "### Homogeneous data", "_____no_output_____" ] ], [ [ "np.zeros((4, 4))", "_____no_output_____" ] ], [ [ "Create a 4x4 array with integer zeros", "_____no_output_____" ] ], [ [ "np.ones((2, 3, 3))", "_____no_output_____" ] ], [ [ "Create a 3x3 array filled with tens", "_____no_output_____" ], [ "### Diagonal elements", "_____no_output_____" ] ], [ [ "np.diag([1, 2, 3, 4])", "_____no_output_____" ] ], [ [ "`diag` has an optional argument `k`. Try to find out what its effect is.", "_____no_output_____" ], [ "Replace the 1d array by a 2d array. What does `diag` do?", "_____no_output_____" ] ], [ [ "np.info(np.eye)", "_____no_output_____" ] ], [ [ "Create the 3x3 array\n\n```[[2, 1, 0],\n [1, 2, 1],\n [0, 1, 2]]\n```", "_____no_output_____" ], [ "### Random numbers\nWhat is the effect of np.random.seed?", "_____no_output_____" ] ], [ [ "np.random.seed()\nnp.random.rand(5, 2)", "_____no_output_____" ], [ "np.random.seed(1234)\nnp.random.rand(5, 2)", "_____no_output_____" ], [ "data = np.random.rand(20, 20)\nplt.imshow(data, cmap=plt.cm.hot, interpolation='none')\nplt.colorbar()", "_____no_output_____" ], [ "casts = np.random.randint(1, 7, (100, 3))\nplt.hist(casts, np.linspace(0.5, 6.5, 7))", "_____no_output_____" ] ], [ [ "## Indexing and slicing", "_____no_output_____" ], [ "### 1d arrays", "_____no_output_____" ] ], [ [ "a = np.arange(10)", "_____no_output_____" ] ], [ [ "Create the array [7, 8, 9]", "_____no_output_____" ], [ "Create the array [2, 4, 6, 8]", "_____no_output_____" ], [ "Create the array [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]", "_____no_output_____" ], [ "### Higher dimensions", "_____no_output_____" ] ], [ [ "a = np.arange(40).reshape(5, 8)", "_____no_output_____" ] ], [ [ "Create the array [[21, 22, 23], [29, 30, 31], [37, 38, 39]]", "_____no_output_____" ], [ "Create the array [ 3, 11, 19, 27, 35]", "_____no_output_____" ], [ "Create the array [11, 12, 13]", "_____no_output_____" ], [ "Create the array [[ 8, 11, 14], [24, 27, 30]]", "_____no_output_____" ], [ "## Fancy indexing ‒ Boolean mask", "_____no_output_____" ] ], [ [ "a = np.arange(40).reshape(5, 8)", "_____no_output_____" ], [ "a % 3 == 0", "_____no_output_____" ], [ "a[a % 3 == 0]", "_____no_output_____" ], [ "a[(1, 1, 2, 2, 3, 3), (3, 4, 2, 5, 3, 4)]", "_____no_output_____" ] ], [ [ "## Axes", "_____no_output_____" ], [ "Create an array and calculate the sum over all elements", "_____no_output_____" ], [ "Now calculate the sum along axis 0 ...", "_____no_output_____" ], [ "and now along axis 1", "_____no_output_____" ], [ "Identify the axis in the following array", "_____no_output_____" ] ], [ [ "a = np.arange(24).reshape(2, 3, 4)\na", "_____no_output_____" ] ], [ [ "## Axes in more than two dimensions", "_____no_output_____" ], [ "Create a three-dimensional array", "_____no_output_____" ], [ "Produce a two-dimensional array by cutting along axis 0 ...", "_____no_output_____" ], [ "and axis 1 ...", "_____no_output_____" ], [ "and axis 2", "_____no_output_____" ], [ "What do you get by simply using the index `[0]`?", "_____no_output_____" ], [ "What do you get by using `[..., 0]`?", "_____no_output_____" ], [ "## Exploring numerical operations", "_____no_output_____" ] ], [ [ "a = np.arange(4)\nb = np.arange(4, 8)\na, b", "_____no_output_____" ], [ "a+b", "_____no_output_____" ], [ "a*b", "_____no_output_____" ] ], [ [ "Operations are elementwise. Check this by multiplying two 2d array...", "_____no_output_____" ], [ "... and now do a real matrix multiplication", "_____no_output_____" ], [ "## Application: Random walk", "_____no_output_____" ] ], [ [ "length_of_walk = 10000\nrealizations = 5\nangles = 2*np.pi*np.random.rand(length_of_walk, realizations)\nx = np.cumsum(np.cos(angles), axis=0)\ny = np.cumsum(np.sin(angles), axis=0)\nplt.plot(x, y)\nplt.axis('scaled')", "_____no_output_____" ], [ "plt.plot(np.hypot(x, y))", "_____no_output_____" ], [ "plt.plot(np.mean(x**2+y**2, axis=1))\nplt.axis('scaled')", "_____no_output_____" ] ], [ [ "## Let's check the speed", "_____no_output_____" ] ], [ [ "%%timeit a = np.arange(1000000)\na**2", "_____no_output_____" ], [ "%%timeit xvals = range(1000000)\n[xval**2 for xval in xvals]", "_____no_output_____" ], [ "%%timeit a = np.arange(100000)\nnp.sin(a)", "_____no_output_____" ], [ "import math", "_____no_output_____" ], [ "%%timeit xvals = range(100000)\n[math.sin(xval) for xval in xvals]", "_____no_output_____" ] ], [ [ "## Broadcasting", "_____no_output_____" ] ], [ [ "a = np.arange(12).reshape(3, 4)\na", "_____no_output_____" ], [ "a+1", "_____no_output_____" ], [ "a+np.arange(4)", "_____no_output_____" ], [ "a+np.arange(3)", "_____no_output_____" ], [ "np.arange(3)", "_____no_output_____" ], [ "np.arange(3).reshape(3, 1)", "_____no_output_____" ], [ "a+np.arange(3).reshape(3, 1)", "_____no_output_____" ] ], [ [ "Create a multiplication table for the numbers from 1 to 10 starting from two appropriately chosen 1d arrays.", "_____no_output_____" ], [ "As an alternative to `reshape` one can add additional axes with `newaxes` or `None`:", "_____no_output_____" ] ], [ [ "a = np.arange(5)\nb = a[:, np.newaxis]", "_____no_output_____" ] ], [ [ "Check the shapes.", "_____no_output_____" ], [ "## Functions of two variables", "_____no_output_____" ] ], [ [ "x = np.linspace(-40, 40, 200)\ny = x[:, np.newaxis]\nz = np.sin(np.hypot(x-10, y))+np.sin(np.hypot(x+10, y))\nplt.imshow(z, cmap='viridis')", "_____no_output_____" ], [ "x, y = np.mgrid[-10:10:0.1, -10:10:0.1]", "_____no_output_____" ], [ "x", "_____no_output_____" ], [ "y", "_____no_output_____" ], [ "plt.imshow(np.sin(x*y))", "_____no_output_____" ], [ "x, y = np.mgrid[-10:10:50j, -10:10:50j]", "_____no_output_____" ], [ "x", "_____no_output_____" ], [ "y", "_____no_output_____" ], [ "plt.imshow(np.arctan2(x, y))", "_____no_output_____" ] ], [ [ "It is natural to use broadcasting. Check out what happens when you replace `mgrid` by `ogrid`.", "_____no_output_____" ], [ "## Linear Algebra in NumPy", "_____no_output_____" ] ], [ [ "a = np.arange(4).reshape(2, 2)\neigenvalues, eigenvectors = np.linalg.eig(a)\neigenvalues", "_____no_output_____" ], [ "eigenvectors", "_____no_output_____" ] ], [ [ "Explore whether the eigenvectors are the rows or the columns.", "_____no_output_____" ], [ "Try out `eigvals` and other methods offered by `linalg` which your are interested in", "_____no_output_____" ], [ "## Application: identify entry closest to ½", "_____no_output_____" ], [ "Create a 2d array containing random numbers and generate a vector containing for each row the entry closest to one-half.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ] ]
cb676773f46da75b4ca15704215fed891f1c6402
564,197
ipynb
Jupyter Notebook
uhecr_model/figures/verification/figures_kappa_gmf.ipynb
uhecr-project/uhecr_model
8a2e8ab6f11cd2700f6455dff54c746cf3ffb143
[ "MIT" ]
null
null
null
uhecr_model/figures/verification/figures_kappa_gmf.ipynb
uhecr-project/uhecr_model
8a2e8ab6f11cd2700f6455dff54c746cf3ffb143
[ "MIT" ]
2
2021-07-12T08:01:11.000Z
2021-08-04T03:01:30.000Z
uhecr_model/figures/verification/figures_kappa_gmf.ipynb
uhecr-project/uhecr_model
8a2e8ab6f11cd2700f6455dff54c746cf3ffb143
[ "MIT" ]
null
null
null
857.442249
163,682
0.950631
[ [ [ "'''Check that the simulated kappa_gmf values are properly simulated, and also check them as a function of Z'''\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport h5py\nimport matplotlib.lines as mlines\n\nfrom fancy import Uhecr\nfrom fancy.interfaces.stan import uv_to_coord\nfrom fancy.plotting.allskymap_cartopy import AllSkyMapCartopy as AllSkyMap\n\nptypes_list = [\"p\", \"He\", \"N\", \"Si\", \"Fe\"]\n# ptypes_list = [\"p\", \"He\", \"N\"]\nseed = 19990308\n\nuhecr_file = \"../../data/UHECRdata.h5\"\nuhecr = Uhecr()\n\n# read kappa_gmf values for each particle type\n\nkappa_gmf_list = []\ncoord_gal_list = []\ncoord_rand_list = []\n\ncoord_true_list = []\nkappa_gmf_rand_list = []\n\ngmf_model = \"PT11\"\ndetector = \"TA2015\"\n\nwith h5py.File(uhecr_file, \"r\") as f:\n\n detector_dict = f[detector]\n\n kappa_gmf_dict = detector_dict[\"kappa_gmf\"]\n\n gmf_model_dict = kappa_gmf_dict[gmf_model]\n\n for ptype in ptypes_list:\n gmf_model_dict_ptype = gmf_model_dict[ptype]\n coord_true_list.append(gmf_model_dict_ptype[\"omega_true\"][()])\n coord_rand_list.append(gmf_model_dict_ptype[\"omega_rand\"][()])\n coord_gal_list.append(gmf_model_dict_ptype[\"omega_gal\"][()])\n kappa_gmf_list.append(gmf_model_dict_ptype[\"kappa_gmf\"][()])\n kappa_gmf_rand_list.append(gmf_model_dict_ptype[\"kappa_gmf_rand\"][()])\n\n glon = detector_dict['glon'][()]\n glat = detector_dict['glat'][()]\n uhecr_coord = uhecr.get_coordinates(glon, glat)\n# for ptype in ptypes_list:\n# sim_output_file = \"../../output/{0}_sim_{1}_{2}_{3}_{4}.h5\".format(\n# \"joint_gmf\", \"SBG_23\", \"TA2015\", seed, ptype)\n\n# with h5py.File(sim_output_file, \"r\") as f:\n# uhecr_coord_list.append(uv_to_coord(f[\"uhecr/unit_vector\"][()]))\n\n# kappa_gmf_list.append(f[\"uhecr/kappa_gmf\"][()])\n# coord_gmf_list.append(f[\"plotvars/omega_rand_kappa_gmf\"][()])\n# coord_defl_list.append(f[\"plotvars/omega_defl_kappa_gmf\"][()])\n# # print(f[\"uhecr\"].keys(), type(uhecr_coord))\n\n# # kappa_gmf\n\nlen(kappa_gmf_list[0])", "_____no_output_____" ], [ "plt.style.use(\"minimalist\")\n\nskymap = AllSkyMap(lon_0 = 180)\nskymap.set_gridlines(label_fmt=\"default\")\n\nptype = \"N\"\n\nptype_idx = np.argwhere([p == ptype for p in ptypes_list])[0][0]\n# print(ptype_idx)\n\nskymap.scatter(np.rad2deg(coord_true_list[ptype_idx][:, 0]), np.rad2deg(coord_true_list[ptype_idx][:, 1]), color=\"k\", alpha=1, marker=\"+\", s=20.0)\nskymap.scatter(np.rad2deg(coord_rand_list[ptype_idx][:, :, 0]), np.rad2deg(coord_rand_list[ptype_idx][:, :, 1]), color=\"b\", alpha=0.1, s=5.0, lw=0)\nskymap.scatter(np.rad2deg(coord_gal_list[ptype_idx][:, :, 0]), np.rad2deg(coord_gal_list[ptype_idx][:, :, 1]), color=\"r\", alpha=0.1, s=5.0, lw=0)\n# skymap.scatter(180. - 177.14668051, 49.59823616, color=\"g\", marker=\"o\", s=200)\n# skymap.scatter(180. - uhecr_coord.galactic.l.deg, uhecr_coord.galactic.b.deg, color=\"purple\", alpha=1, marker=\"+\", s=50.0)\n\nhandles = [mlines.Line2D([], [], color='k', marker='+', lw=0,\n markersize=6, alpha=1, label=\"Original UHECR\"),\n mlines.Line2D([], [], color='b', marker='o', lw=0,\n markersize=3, alpha=0.3, label=\"Randomized UHECR\"),\n mlines.Line2D([], [], color='r', marker='o', lw=0,\n markersize=3, alpha=0.3, label=\"Deflected UHECR\")]\n\nskymap.legend(handles=handles, bbox_to_anchor=(1.25, 0.27), fontsize=14) \n# skymap.title(\"Deflection skymap with data - {0}\".format(ptype))\nskymap.save(f\"defl_skymap_{detector}_{ptype}_{gmf_model}.png\")\n\n", "_____no_output_____" ], [ "plt.style.use(\"minimalist\")\n\nskymap = AllSkyMap(lon_0 = 180)\nskymap.set_gridlines(label_fmt=\"default\", zorder=1)\n\n# ptype = \"p\"\n# for sel_uhecr_idx in np.arange(0, 72, 8):\n# print(sel_uhecr_idx)\n\nsel_uhecr_idx = 24\nsel_uhecr_lon, sel_uhecr_lat = 180-np.rad2deg(coord_true_list[ptype_idx][sel_uhecr_idx, 0]), np.rad2deg(coord_true_list[ptype_idx][sel_uhecr_idx, 1])\n\nptype_idx = np.argwhere([p == ptype for p in ptypes_list])[0][0]\n# print(ptype_idx)\n\nskymap.scatter(np.rad2deg(coord_true_list[ptype_idx][:, 0]), np.rad2deg(coord_true_list[ptype_idx][:, 1]), color=\"k\", alpha=1, marker=\"+\", s=20.0)\nskymap.scatter(np.rad2deg(coord_rand_list[ptype_idx][:, :, 0]), np.rad2deg(coord_rand_list[ptype_idx][:, :, 1]), color=\"b\", alpha=0.1, s=5.0, lw=0)\nskymap.scatter(np.rad2deg(coord_gal_list[ptype_idx][:, :, 0]), np.rad2deg(coord_gal_list[ptype_idx][:, :, 1]), color=\"r\", alpha=0.1, s=5.0, lw=0)\n\n# skymap.scatter(180. - uhecr_coord.galactic.l.deg, uhecr_coord.galactic.b.deg, color=\"purple\", alpha=1, marker=\"+\", s=50.0)\n\nskymap.scatter(np.rad2deg(coord_rand_list[ptype_idx][sel_uhecr_idx, :, 0]), np.rad2deg(coord_rand_list[ptype_idx][sel_uhecr_idx, :, 1]), color=\"g\", alpha=0.1, s=5.0, lw=0)\nskymap.scatter(np.rad2deg(coord_gal_list[ptype_idx][sel_uhecr_idx, :, 0]), np.rad2deg(coord_gal_list[ptype_idx][sel_uhecr_idx, :, 1]), color=\"g\", alpha=0.8, s=5.0, lw=0)\n\nfor i in range(100):\n skymap.geodesic(np.rad2deg(coord_rand_list[ptype_idx][sel_uhecr_idx, i, 0]), np.rad2deg(coord_rand_list[ptype_idx][sel_uhecr_idx, i, 1]), \n np.rad2deg(coord_gal_list[ptype_idx][sel_uhecr_idx, i, 0]), np.rad2deg(coord_gal_list[ptype_idx][sel_uhecr_idx, i, 1]), alpha=0.05, color=\"k\")\n\nhandles = [mlines.Line2D([], [], color='k', marker='+', lw=0,\n markersize=6, alpha=1, label=\"Original UHECR\"),\n mlines.Line2D([], [], color='b', marker='o', lw=0,\n markersize=3, alpha=0.3, label=\"Randomized UHECR\"),\n mlines.Line2D([], [], color='r', marker='o', lw=0,\n markersize=3, alpha=0.3, label=\"Deflected UHECR\")]\n\n# sel_uhecr_handles = [mlines.Line2D([], [], color='g', marker='o', lw=0,\n# markersize=4, alpha=0.3, label=\"UHECR Coordinate (Gal):\\n ({0:.1f}$^\\circ$, {1:.1f}$^\\circ$)\".format(sel_uhecr_lon, sel_uhecr_lat))]\n\nlegend1 = skymap.legend(handles=handles, bbox_to_anchor=(1.25, 0.27)) \n# legend2 = skymap.legend(handles=sel_uhecr_handles, bbox_to_anchor=(1.25, 1.05)) \n\nskymap.ax.add_artist(legend1)\n# skymap.ax.add_artist(legend2)\n\n\n\n# skymap.title(\"Deflection skymap with data - {0}\".format(ptype))\n# skymap.save(\"skymap_banana.png\")\n\n", "_____no_output_____" ], [ "# evaluate dot product between deflected and randomized vector\n# then obtain the effective thetea_rms for each (true) UHECR\n\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\n\nfrom fancy.interfaces.stan import coord_to_uv\nfrom scipy.optimize import root\nptype = \"p\"\n\n'''Integral of Fischer distribution used to evaluate kappa_d'''\ndef fischer_int(kappa, cos_thetaP):\n '''Integral of vMF function over all angles'''\n return (1. - np.exp(-kappa * (1 - cos_thetaP))) / (1. - np.exp(-2.*kappa))\n\ndef fischer_int_eq_P(cos_thetaP, kappa, P):\n '''Equation to find roots for'''\n return fischer_int(kappa, cos_thetaP) - P\n\nptype_idx = np.argwhere([p == ptype for p in ptypes_list])[0][0]\n# print(kappa_gmf_list[ptype_idx])\n\ncos_theta_arr = np.zeros(len(kappa_gmf_list[ptype_idx]))\nfor i, kappa_gmf in enumerate(kappa_gmf_list[ptype_idx]):\n sol = root(fischer_int_eq_P, x0=1, args=(kappa_gmf, 0.683))\n cos_theta = sol.x[0]\n cos_theta_arr[i] = cos_theta\n\nthetas = np.rad2deg(np.arccos(cos_theta_arr))\n# print(np.rad2deg(np.arccos(cos_theta_arr)))\n\nskymap = AllSkyMap(lon_0 = 180)\nskymap.set_gridlines(label_fmt=\"default\")\n\nang_err = 1.7\nskymap.scatter(np.rad2deg(coord_true_list[ptype_idx][:, 0]), np.rad2deg(coord_true_list[ptype_idx][:, 1]), color=\"k\", alpha=1, marker=\"+\", s=10.0)\n\nfor i, (lon, lat) in enumerate(coord_true_list[ptype_idx][:]):\n skymap.tissot(np.rad2deg(lon), np.rad2deg(lat), ang_err, color=\"b\", alpha=0.2)\n skymap.tissot(np.rad2deg(lon), np.rad2deg(lat), thetas[i], color=\"r\", alpha=0.05)\n\nhandles = [mlines.Line2D([], [], color='k', marker='+', lw=0,\n markersize=8, alpha=1, label=\"Original UHECR\"),\n mlines.Line2D([], [], color='b', marker='o', lw=0,\n markersize=8, alpha=0.3, label=\"Angular Uncertainty Circle\"),\n mlines.Line2D([], [], color='r', marker='o', lw=0,\n markersize=8, alpha=0.3, label=\"Deflection Circle\")]\n\nskymap.legend(handles=handles, bbox_to_anchor=(1.3, 0.27)) \n# skymap.title(\"Deflection skymap with data - {0}\".format(ptype))\n\n# skymap.scatter(np.rad2deg(coord_true_list[ptype_idx][:, 0]), np.rad2deg(coord_true_list[ptype_idx][:, 1]), color=\"k\", alpha=1, marker=\"+\", s=20.0)\n# skymap.scatter(np.rad2deg(coord_rand_list[ptype_idx][:, :, 0]), np.rad2deg(coord_rand_list[ptype_idx][:, :, 1]), color=\"b\", alpha=0.05, s=4.0)\n\n\n", "_____no_output_____" ], [ "# evaluate dot product between deflected and randomized vector\n# then obtain the effective thetea_rms for each (true) UHECR\n\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\n\nfrom fancy.interfaces.stan import coord_to_uv\nfrom scipy.optimize import root\nptype = \"N\"\n\n'''Integral of Fischer distribution used to evaluate kappa_d'''\ndef fischer_int(kappa, cos_thetaP):\n '''Integral of vMF function over all angles'''\n return (1. - np.exp(-kappa * (1 - cos_thetaP))) / (1. - np.exp(-2.*kappa))\n\ndef fischer_int_eq_P(cos_thetaP, kappa, P):\n '''Equation to find roots for'''\n return fischer_int(kappa, cos_thetaP) - P\n\nptype_idx = np.argwhere([p == ptype for p in ptypes_list])[0][0]\n# print(kappa_gmf_list[ptype_idx])\n\ncos_theta_arr = np.zeros(len(kappa_gmf_list[ptype_idx]))\nfor i, kappa_gmf in enumerate(kappa_gmf_list[ptype_idx]):\n sol = root(fischer_int_eq_P, x0=1, args=(kappa_gmf, 0.683))\n cos_theta = sol.x[0]\n cos_theta_arr[i] = cos_theta\n\nthetas = np.rad2deg(np.arccos(cos_theta_arr))\n# print(np.rad2deg(np.arccos(cos_theta_arr)))\n\nskymap = AllSkyMap(lon_0 = 180)\nskymap.set_gridlines(label_fmt=\"default\")\n\nang_err = 1.7\nskymap.scatter(np.rad2deg(coord_true_list[ptype_idx][:, 0]), np.rad2deg(coord_true_list[ptype_idx][:, 1]), color=\"k\", alpha=1, marker=\"+\", s=10.0)\n\nfor i, (lon, lat) in enumerate(coord_true_list[ptype_idx][:]):\n skymap.tissot(np.rad2deg(lon), np.rad2deg(lat), ang_err, color=\"b\", alpha=0.2)\n skymap.tissot(np.rad2deg(lon), np.rad2deg(lat), thetas[i], color=\"r\", alpha=0.05)\n\nsel_uhecr_idx = 24\nskymap.tissot(np.rad2deg(coord_true_list[ptype_idx][sel_uhecr_idx, 0]), np.rad2deg(coord_true_list[ptype_idx][sel_uhecr_idx, 1]), ang_err, color=\"b\", alpha=0.2)\nskymap.tissot(np.rad2deg(coord_true_list[ptype_idx][sel_uhecr_idx, 0]), np.rad2deg(coord_true_list[ptype_idx][sel_uhecr_idx, 1]), thetas[sel_uhecr_idx], color=\"g\", alpha=0.3)\n\nhandles = [mlines.Line2D([], [], color='k', marker='+', lw=0,\n markersize=8, alpha=1, label=\"Original UHECR\"),\n mlines.Line2D([], [], color='b', marker='o', lw=0,\n markersize=8, alpha=0.3, label=\"Angular Uncertainty Circle\"),\n mlines.Line2D([], [], color='r', marker='o', lw=0,\n markersize=8, alpha=0.3, label=\"Deflection Circle\")]\n\n# sel_uhecr_handles = [mlines.Line2D([], [], color='g', marker='o', lw=0,\n# markersize=4, alpha=0.3, label=\"UHECR Coordinate (Gal):\\n ({0:.1f}$^\\circ$, {1:.1f}$^\\circ$)\\n\".format(sel_uhecr_lon, sel_uhecr_lat))]\n\nlegend1 = skymap.legend(handles=handles, bbox_to_anchor=(1.3, 0.27)) \n# legend2 = skymap.legend(handles=sel_uhecr_handles, bbox_to_anchor=(0.9, 1.05)) \n\nskymap.ax.add_artist(legend1)\n# skymap.ax.add_artist(legend2)\n\n# skymap.title(\"Deflection skymap with data - {0}\".format(ptype))\n\n# skymap.save(\"GMFPlots_N_defl_circles_selUHECR.png\")\n\n# skymap.scatter(np.rad2deg(coord_true_list[ptype_idx][:, 0]), np.rad2deg(coord_true_list[ptype_idx][:, 1]), color=\"k\", alpha=1, marker=\"+\", s=20.0)\n# skymap.scatter(np.rad2deg(coord_rand_list[ptype_idx][:, :, 0]), np.rad2deg(coord_rand_list[ptype_idx][:, :, 1]), color=\"b\", alpha=0.05, s=4.0)\n\n\n", "_____no_output_____" ], [ "len(thetas)\n\n# somehow the circles that cover all sky (fior N) disappeared, need to invesitagte why ", "_____no_output_____" ], [ "ptype_idx = np.argwhere([p == \"p\" for p in ptypes_list])[0][0]\n# plt.hist(kappa_gmf_list[ptype_idx], bins=np.logspace(-2, 3, 10))\nplt.hist(kappa_gmf_list[ptype_idx], bins=np.linspace(1e-2, 1e2, 10))\n# plt.xscale(\"log\")", "_____no_output_____" ], [ "colors = [\"b\", \"r\", \"g\"]\n\nfig, ax = plt.subplots(figsize=(6,4))\n# plt.hist(kappa_gmf_list[ptype_idx], bins=np.logspace(-2, 3, 10))\nfor i, ptype in enumerate([\"p\", \"N\", \"Fe\"]):\n\n ptype_idx = np.argwhere([p == ptype for p in ptypes_list])[0][0]\n # print(kappa_gmf_list[ptype_idx])\n\n not_zero_idces = np.argwhere(kappa_gmf_list[ptype_idx] > 1e-9)\n\n cos_theta_arr = np.zeros_like(kappa_gmf_list[ptype_idx])\n for j, kappa_gmf in enumerate(kappa_gmf_list[ptype_idx]):\n if kappa_gmf < 1e-9:\n kappa_gmf = 0\n sol = root(fischer_int_eq_P, x0=1, args=(kappa_gmf, 0.683))\n cos_theta = sol.x[0]\n cos_theta_arr[j] = cos_theta\n\n thetas = np.rad2deg(np.arccos(cos_theta_arr))\n\n thetas = thetas[not_zero_idces]\n\n # print(thetas)\n\n ax.hist(thetas, bins=np.linspace(0, 180, 25), alpha=0.4, color=colors[i], label=ptype, weights=np.ones_like(thetas) / len(thetas) / 25)\n# plt.xscale(\"log\")\nax.set_xlim([0, 130])\nax.set_xticks(np.arange(0, 130, 30, dtype=int))\nax.set_yticks([0, 0.01, 0.02, 0.03])\n# for tick in ax.xaxis.get_major_ticks():\n# tick.label.set_fontsize(12)\n\n# ax.set_yticklabels()\nax.legend()\n\nax.tick_params(axis=\"x\", labelsize=14)\nax.tick_params(axis=\"y\", labelsize=14)\nax.set_xlabel(r\"$\\sigma_{{\\omega + \\rm{GMF}}}$ / degrees\", fontsize=14)\nax.set_ylabel(r\"$P (\\sigma_{{\\omega + \\rm{GMF}}} | \\hat{\\omega}, \\omega_{g})$\", fontsize=16)\n\nfig.tight_layout()\n\nfig.savefig(\"kappa_defl_histogram.png\", dpi=400)\n\n# plt.hist(kappa_gmf_rand_list[ptype_idx][sel_uhecr_idx, :], \n# bins=np.logspace(-2, 2, 30), \n# alpha=0.4, color=colors[i], label=ptype)\n# plt.xscale(\"log\")\n\n# plt.legend()", "_____no_output_____" ], [ "colors = [\"k\"]\n\nfig, ax = plt.subplots(figsize=(6,4))\n# plt.hist(kappa_gmf_list[ptype_idx], bins=np.logspace(-2, 3, 10))\nfor i, ptype in enumerate([\"p\"]):\n\n ptype_idx = np.argwhere([p == ptype for p in ptypes_list])[0][0]\n # print(kappa_gmf_list[ptype_idx])\n\n cos_theta_arr = np.zeros_like(kappa_gmf_rand_list[ptype_idx][sel_uhecr_idx, :])\n for j, kappa_gmf in enumerate(kappa_gmf_rand_list[ptype_idx][sel_uhecr_idx, :]):\n sol = root(fischer_int_eq_P, x0=1, args=(kappa_gmf, 0.683))\n cos_theta = sol.x[0]\n cos_theta_arr[j] = cos_theta\n\n thetas = np.rad2deg(np.arccos(cos_theta_arr))\n\n ax.hist(thetas, bins=np.linspace(0, 30, 20), alpha=0.4, color=colors[i], label=ptype, weights=np.ones_like(thetas) / len(thetas) / 20)\n# plt.xscale(\"log\")\nax.set_xlim([0, 30])\nax.set_xticks(np.arange(0, 35, 5, dtype=int))\nax.set_yticks([0, 0.005, 0.01, 0.015])\nax.tick_params(axis=\"x\", labelsize=14)\nax.tick_params(axis=\"y\", labelsize=14)\n# for tick in ax.xaxis.get_major_ticks():\n# tick.label.set_fontsize(12)\n\n# ax.set_yticklabels()\n# ax.legend()\n\nax.set_xlabel(r\"$\\sigma_{{\\omega + \\rm{GMF}}}$ / degrees\", fontsize=14)\nax.set_ylabel(r\"$P (\\sigma_{{\\omega + \\rm{GMF}}} | \\hat{\\omega}, \\omega_{g})$\", fontsize=16)\n\nfig.tight_layout()\n\nfig.savefig(f\"kappa_defl_{ptype}_histogram.png\", dpi=400)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb677efa7857378db8f835d4e3deb6dcba92e15e
29,434
ipynb
Jupyter Notebook
st_book.ipynb
MarquesThiago/sumarize-text
4e5eece2becce5574ad1bedf50be0b56a43c2caf
[ "MIT" ]
null
null
null
st_book.ipynb
MarquesThiago/sumarize-text
4e5eece2becce5574ad1bedf50be0b56a43c2caf
[ "MIT" ]
null
null
null
st_book.ipynb
MarquesThiago/sumarize-text
4e5eece2becce5574ad1bedf50be0b56a43c2caf
[ "MIT" ]
null
null
null
60.069388
10,011
0.677448
[ [ [ "import PyPDF2\nimport re\nimport os \nimport fitz\nfrom goose3 import Goose\nfrom sumariza import (\n sumarize_per_frequency as sumi1,\n sumarize_by_luhn as sumi2,\n simple_clear)", "[nltk_data] Downloading package punkt to\n[nltk_data] C:\\Users\\thiag\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package punkt is already up-to-date!\n" ], [ "# pdf = open(r'.\\books\\a_moreninha.pdf', 'rb')\n# book = PyPDF2.PdfFileReader(pdf)", "_____no_output_____" ], [ "# total_pages = book.getNumPages()\n# total_pages", "_____no_output_____" ], [ "# book.getPage(9).extractText", "_____no_output_____" ], [ "text = None\nwith fitz.open(r'.\\books\\a_moreninha.pdf') as book:\n \n content = [page.get_text() for page in book]\n text = simple_clear(\"\".join(content))", "_____no_output_____" ], [ "text[:10000]", "_____no_output_____" ], [ "sumi1(text, 5, True, lemma= True)", "_____no_output_____" ], [ "sumi2(text,5, 3, True)", "_____no_output_____" ], [ "others = [\"Do_avatar_ao_sujeito_Transicionalidade_e (1).pdf\" , \"SPINOZA, Baruch. Ética.pdf\"]", "_____no_output_____" ], [ "def process(path, init = 0):\n\n text = fitz.open(path)\n content_list = [text[index].get_text() for index in range(len(text)) if index >= init]\n content = \"\".join(content_list)\n return simple_clear(content)", "_____no_output_____" ], [ "text_article = process(r'.\\books\\{}'.format(others[0]), init = 10)\ntext_baruch = process(r'.\\books\\{}'.format(others[1]), init = 6)\n", "_____no_output_____" ], [ "sum_ = [sumi1(text, 5, True) for text in [text_article, text_baruch]]", "_____no_output_____" ], [ "sum_2 = [sumi2(text, 5, True) for text in [text_article, text_baruch]]", "_____no_output_____" ], [ "sum_[0]", "_____no_output_____" ], [ "sum_[1]", "_____no_output_____" ], [ "sum_2[0]", "_____no_output_____" ], [ "sum_2[1]", "_____no_output_____" ], [ "def article (link):\n search = Goose()\n return search.extract(link)", "_____no_output_____" ], [ "spy_family = article(\"https://animenew.com.br/spy-x-family-anime-ganha-data-de-estreia/\")\nmassacre = article(\"https://canaltech.com.br/quadrinhos/massacre-a-saga-em-que-o-professor-x-se-tornou-supervilao-na-marvel-210763/\")\nfilmes = article(\"https://canaltech.com.br/entretenimento/filmes-acao-aventura-netflix-em-2022/\")", "_____no_output_____" ], [ "sumi1(spy_family.cleaned_text, 5, True)", "_____no_output_____" ], [ "sumi2(spy_family.cleaned_text, 5, True)", "_____no_output_____" ], [ "sumi1(massacre.cleaned_text, 4, True)", "_____no_output_____" ], [ "sumi2(massacre.cleaned_text, 4, True)", "_____no_output_____" ], [ "sumi1(filmes.cleaned_text, 4, True, True)", "_____no_output_____" ], [ "sumi2(filmes.cleaned_text, 4, True, True)", "_____no_output_____" ], [ "sumi2(filmes.cleaned_text, 4, True)", "_____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" ] ]
cb678896f123edd11bf812c682a2671d28e96506
19,801
ipynb
Jupyter Notebook
lesson_1/1_intro.ipynb
mariaisnotsodead/1_python_public
8acd399db2c74928c78e81e28854220ddd5f08b4
[ "MIT" ]
1
2020-11-11T06:31:16.000Z
2020-11-11T06:31:16.000Z
lesson_1/1_intro.ipynb
mariaisnotsodead/1_python_public
8acd399db2c74928c78e81e28854220ddd5f08b4
[ "MIT" ]
null
null
null
lesson_1/1_intro.ipynb
mariaisnotsodead/1_python_public
8acd399db2c74928c78e81e28854220ddd5f08b4
[ "MIT" ]
null
null
null
23.051222
702
0.540579
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb679c7d58d454e258e5d23319523530768d3d62
868,112
ipynb
Jupyter Notebook
Grade prediction-reoder.ipynb
wasit7/grade_analysis
6b352ccbc8bc66901b16ba8c2049a7f3caf26c0a
[ "MIT" ]
null
null
null
Grade prediction-reoder.ipynb
wasit7/grade_analysis
6b352ccbc8bc66901b16ba8c2049a7f3caf26c0a
[ "MIT" ]
null
null
null
Grade prediction-reoder.ipynb
wasit7/grade_analysis
6b352ccbc8bc66901b16ba8c2049a7f3caf26c0a
[ "MIT" ]
null
null
null
36.764155
27,918
0.259411
[ [ [ "#Grae prediction using Parallel Random Forest\n \n Grading is necessary tool for measure outcome of the sudying process. Unsuccessful lerning process may depend on many factors such as student attenction, teacher and background knowledge. In many academic instituetions, the prerequisite subjects are required before registering some particular subjects. In this project, we attempt to investigate the relationship between prerequisite grades on a grade of the paricular subject. We have aquired a anonymous enrolment records of computer science students from the registrar of Thammasat University. The records have been constantly collected for 4 years consisting of over 28,272 records.", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nprint pd.__version__\n%matplotlib inline\npd.set_option('display.max_rows', 100)\npd.set_option('display.max_columns', 500)\ndf_csv = pd.read_csv('CS_table_No2_No4_new.csv',delimiter=\";\",\n skip_blank_lines = True, error_bad_lines=False)\ndf_csv=df_csv.dropna()", "0.18.0\n" ], [ "print df_csv.head() #get first 5 records", " STUDENTID ACADYEAR SEMESTER CAMPUSID COURSEID CAMPUSNAME CURRIC \\\n0 316644 2552 1 2 CS101 RANGSIT 521 \n1 316644 2552 1 2 CS102 RANGSIT 521 \n2 316644 2552 1 2 EL171 RANGSIT 521 \n3 316644 2552 1 2 SC135 RANGSIT 521 \n4 316644 2552 1 2 SC185 RANGSIT 521 \n\n COURSENAME SECTIONGROUP CREDIT GRADE \n0 DISCRETE STRUCTURES 10001 3 C \n1 COMPUTER PROGRAMMING FUNDAMENTALS 20301 4 C \n2 ENGLISH COURSE 2 100003 3 D \n3 GENERAL PHYSICS 80001 3 F \n4 GENERAL PHYSICS LABORATORY 5401 1 C \n" ], [ "print df_csv.tail() #get lat 5 records", " STUDENTID ACADYEAR SEMESTER CAMPUSID COURSEID CAMPUSNAME CURRIC \\\n31332 447243 2557 1 2 EL070 RANGSIT 561 \n31333 447243 2557 1 2 MA211 RANGSIT 561 \n31334 447243 2557 1 2 ST216 RANGSIT 561 \n31335 447243 2557 1 2 TH161 RANGSIT 561 \n31336 447243 2557 1 2 TU154 RANGSIT 561 \n\n COURSENAME SECTIONGROUP CREDIT GRADE \n31332 ENGLISH COURSE 1 650001 3 U# \n31333 CALCULUS 1 650001 3 F \n31334 STATISTICS FOR SOCIAL SCIENCE 1 650001 3 F \n31335 THAI USAGE 650002 3 F \n31336 FOUNDATION OF MATHEMATICS 650001 3 F \n" ] ], [ [ "#Data minning process\nThe normal procedures for data mininng are the following:\n* data cleaning\n* data transformation\n* training\n* evaluation", "_____no_output_____" ], [ "##Drop unnecessary data\n Some column are unnecessary for the prediction. We can drop them by using df.drop()\n```python\n df_csv.drop([\"column_name\"])\n```", "_____no_output_____" ] ], [ [ "column_name=df_csv.columns.values\nprint column_name\nfor i in column_name:\n print \"datatype of column {} is {}.\".format(i,df_csv[i].dtype)", "['STUDENTID' 'ACADYEAR' 'SEMESTER' 'CAMPUSID' 'COURSEID' 'CAMPUSNAME'\n 'CURRIC' 'COURSENAME' 'SECTIONGROUP' 'CREDIT' 'GRADE']\ndatatype of column STUDENTID is int64.\ndatatype of column ACADYEAR is int64.\ndatatype of column SEMESTER is int64.\ndatatype of column CAMPUSID is int64.\ndatatype of column COURSEID is object.\ndatatype of column CAMPUSNAME is object.\ndatatype of column CURRIC is int64.\ndatatype of column COURSENAME is object.\ndatatype of column SECTIONGROUP is int64.\ndatatype of column CREDIT is int64.\ndatatype of column GRADE is object.\n" ], [ "df_csv.drop(['CAMPUSID','CAMPUSNAME','COURSENAME','CURRIC','SECTIONGROUP','CREDIT'],\n axis=1, inplace=True)\ncolumn_name=df_csv.columns.values\nprint column_name\nfor i in column_name:\n print \"datatype of column {} is {}.\".format(i,df_csv[i].dtype)", "['STUDENTID' 'ACADYEAR' 'SEMESTER' 'COURSEID' 'GRADE']\ndatatype of column STUDENTID is int64.\ndatatype of column ACADYEAR is int64.\ndatatype of column SEMESTER is int64.\ndatatype of column COURSEID is object.\ndatatype of column GRADE is object.\n" ] ], [ [ "##Data cleaning\n There are some records having NAN ann invalid data. We need to fix or remove them.", "_____no_output_____" ] ], [ [ "df=df_csv.copy()\nmyhist=df[\"GRADE\"].value_counts()\nprint myhist\nmyhist.plot(kind='bar')", "C 5075\nC+ 4939\nB 4228\nB+ 3411\nA 3187\nD+ 2600\nD 1792\nW 1690\nF 1062\nS# 206\nS 36\nU 27\nU# 19\nName: GRADE, dtype: int64\n" ] ], [ [ "##converting category to numeric data\n", "_____no_output_____" ] ], [ [ "grade_cn={'':0, 'U#':1, 'U':2, 'S#':3, 'S':4, 'W':5, 'F':6, 'D':7, 'D+':8, 'C':9, 'C+':10, 'B':11, 'B+':12, 'A':13}\ngrade_list=['', 'U#', 'U', 'S#', 'S', 'W', 'F', 'D', 'D+', 'C', 'C+', 'B', 'B+', 'A']\n[grade_cn[i] for i in grade_list]", "_____no_output_____" ], [ "df2=df.copy()\ndf2 = df2.fillna(0)\ndf2 = df2.replace(grade_list, [grade_cn[i] for i in grade_list] )\n", "_____no_output_____" ], [ "myhist=df[\"GRADE\"].value_counts()\nprint myhist\nmyhist2=df2[\"GRADE\"].value_counts()\nprint myhist2", "C 5075\nC+ 4939\nB 4228\nB+ 3411\nA 3187\nD+ 2600\nD 1792\nW 1690\nF 1062\nS# 206\nS 36\nU 27\nU# 19\nName: GRADE, dtype: int64\n9 5075\n10 4939\n11 4228\n12 3411\n13 3187\n8 2600\n7 1792\n5 1690\n6 1062\n3 206\n4 36\n2 27\n1 19\nName: GRADE, dtype: int64\n" ], [ "df2[\"TERM\"]=10*df2[\"ACADYEAR\"]+df2[\"SEMESTER\"]\ndf3=df2.copy()\ndf3.drop([\"ACADYEAR\",\"SEMESTER\"],axis=1, inplace=True)", "_____no_output_____" ], [ "print df3.head()\nprint df3.tail()", " STUDENTID COURSEID GRADE TERM\n0 316644 CS101 9 25521\n1 316644 CS102 9 25521\n2 316644 EL171 7 25521\n3 316644 SC135 6 25521\n4 316644 SC185 9 25521\n STUDENTID COURSEID GRADE TERM\n31332 447243 EL070 1 25571\n31333 447243 MA211 6 25571\n31334 447243 ST216 6 25571\n31335 447243 TH161 6 25571\n31336 447243 TU154 6 25571\n" ] ], [ [ "We need to create a new dataframe that has pattern, where pattern is a set of grades from studied subjects.", "_____no_output_____" ] ], [ [ "#df4=df3[0:20].copy()\ndf4=df3", "_____no_output_____" ], [ "#create a new data frame\ndf5=df4.copy()\nfor c in df5.COURSEID.value_counts().index:\n df5[c]=pd.Series(np.zeros(df5.shape[0],dtype=int),index=df5.index)\n#reindex the columns\ncname=df5.columns[0:4].values.tolist() + sorted(df5.columns[4:].values)\ndf5=df5.reindex_axis(cname, axis=1)", "_____no_output_____" ], [ "df5.COURSEID.value_counts().plot(kind='bar')", "_____no_output_____" ], [ "%%timeit -n1\nfor i, ri in df5.iterrows():\n dfx=df4[ (df4[\"STUDENTID\"] == ri[\"STUDENTID\"]) & (df4[\"TERM\"] < ri[\"TERM\"]) ]\n if(dfx.shape[0]):\n for j,rj in dfx.iterrows():\n df5.loc[i,rj[\"COURSEID\"]]=rj[\"GRADE\"]", "1 loops, best of 3: 15min 29s per loop\n" ], [ "df5.to_pickle(\"df5.pkl\")\n#df = pd.read_pickle(\"df5.pkl\")", "_____no_output_____" ], [ "df6 = pd.read_pickle(\"df5.pkl\")", "_____no_output_____" ], [ "df6", "_____no_output_____" ], [ "import pickle\nwith open('grade_cn.pkl', 'wb') as pickleFile:\n pickle.dump(grade_cn, pickleFile, pickle.HIGHEST_PROTOCOL)", "_____no_output_____" ], [ "import pickle\nwith open('grade_cn.pkl', 'rb') as pickleFile:\n _grade_cn = pickle.load(pickleFile)", "_____no_output_____" ], [ "print grade_cn\nprint _grade_cn", "{'': 0, 'A': 13, 'C': 9, 'B': 11, 'D': 7, 'F': 6, 'S': 4, 'U': 2, 'W': 5, 'S#': 3, 'U#': 1, 'C+': 10, 'D+': 8, 'B+': 12}\n{'': 0, 'A': 13, 'C': 9, 'B': 11, 'D': 7, 'F': 6, 'C+': 10, 'S': 4, 'U': 2, 'W': 5, 'S#': 3, 'B+': 12, 'U#': 1, 'D+': 8}\n" ], [ "df6.to_csv(\"df6.csv\")", "_____no_output_____" ], [ "abc=df6[\"COURSEID\"].value_counts() \nlen(abc)", "_____no_output_____" ], [ "m20=abc[abc[:]>=20]\nprint m20\nlen(m20)", "MA211 1068\nCS102 966\nCS101 948\nTU154 946\nTH161 899\nCS111 834\nCS213 765\nEL171 760\nSC135 740\nPY228 705\nEL172 697\nSC185 686\nTU110 666\nCS223 664\nTU120 648\nST216 623\nCS284 616\nEL295 588\nTU130 567\nMA212 539\nMA332 509\nCS314 509\nCS222 490\nCS214 488\nCS261 481\nCS251 471\nCS281 470\nCS341 443\nEL395 442\nCS301 421\nCS311 343\nCS374 339\nCS302 338\nCS401 333\nCS342 332\nCS105 298\nHO201 257\nCS395 256\nCS402 248\nCS365 237\nEL070 229\nAT326 221\nTU100 210\nCS289 182\nCS385 181\nAT316 142\nCS326 141\nTU122 141\nCS288 140\nCS487 138\n ... \nSW212 82\nCS409 81\nSW221 81\nCS215 80\nCS386 79\nCS366 72\nCS295 71\nCS377 69\nLA209 69\nCS456 68\nCS467 67\nCS300 64\nSW478 64\nSW213 63\nMW314 58\nBA291 58\nSW475 57\nCS396 56\nCS427 56\nES356 56\nCS387 54\nCS286 53\nCS297 53\nCS429 51\nCS446 50\nSW335 50\nCS356 49\nHR201 49\nCS459 48\nSO201 44\nNS132 44\nTA395 42\nCJ321 41\nCS397 41\nCS398 40\nCS348 38\nCJ317 37\nMW313 36\nCJ316 36\nMA216 35\nCS407 35\nCS115 34\nCS457 32\nCS388 31\nCS426 30\nCS449 30\nCS408 27\nCJ315 26\nCS285 24\nCS399 24\nName: COURSEID, dtype: int64\n" ], [ "mm=abc[abc[:]<20]\nlen(mm)", "_____no_output_____" ], [ "df6[df6[\"COURSEID\"].isin(mm.index)].shape[0]", "_____no_output_____" ], [ "df6[df6[\"COURSEID\"].isin(m20.index)].shape[0]", "_____no_output_____" ], [ "278+27994", "_____no_output_____" ], [ "df6.shape[0]", "_____no_output_____" ], [ "df7=df6[df6[\"COURSEID\"].isin(m20.index)]\ndf7.to_csv('df7.csv')", "_____no_output_____" ], [ "for m in m20.index:\n dfx=df6[df6[\"COURSEID\"].isin([m])]\n dfx.to_csv(\"df_%s.csv\"%m)", "_____no_output_____" ], [ "df7.COURSEID.value_counts().plot(kind='bar')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb67a1f42842c6f9686fb2c53eea0fb49ad4ba98
8,763
ipynb
Jupyter Notebook
08/8.5.ipynb
XXG-Lab/Dragon
741b36f8836d8a1d7a6912021ac3e54d57784124
[ "MIT" ]
4
2019-09-14T13:46:18.000Z
2022-01-11T22:05:41.000Z
08/8.5.ipynb
XGG-Lab/Dragon
741b36f8836d8a1d7a6912021ac3e54d57784124
[ "MIT" ]
null
null
null
08/8.5.ipynb
XGG-Lab/Dragon
741b36f8836d8a1d7a6912021ac3e54d57784124
[ "MIT" ]
2
2019-09-14T13:46:19.000Z
2022-01-11T22:34:55.000Z
23.683784
181
0.261668
[ [ [ "## 8.5 Optimization of Basic Blocks", "_____no_output_____" ], [ "### 8.5.1\n\n> Construct the DAG for the basic block\n\n> ```\nd = b * c\ne = a + b\nb = b * c\na = e - d\n```", "_____no_output_____" ], [ "```\n +--+--+\n | - | a\n +-+++-+\n | |\n +---+ +---+\n | |\n +--v--+ +--v--+\n e | + | | * | d,b\n +-+++-+ +-+-+-+\n | | | |\n +---+ +--+ +--+ +---+\n | | | |\n v v v v\n a0 b0 c \n```", "_____no_output_____" ], [ "### 8.5.2\n\n> Simplify the three-address code of Exercise 8.5.1, assuming\n\n> a) Only $a$ is live on exit from the block.", "_____no_output_____" ], [ "```\nd = b * c\ne = a + b\na = e - d\n```", "_____no_output_____" ], [ "> b) $a$, $b$, and $c$ are live on exit from the block.", "_____no_output_____" ], [ "```\ne = a + b\nb = b * c\na = e - b\n```", "_____no_output_____" ], [ "### 8.5.3\n\n> Construct the DAG for the code in block $B_6$ of Fig. 8.9. Do not forget to include the comparison $i \\le 10$.", "_____no_output_____" ], [ "```\n +-----+\n | []= | a[t0]\n ++-+-++\n | | |\n+--------+ | +-------+\n| | |\nv +--v--+ v +-----+\na t6 | * | 1.0 | <= |\n +-+-+-+ +-+-+-+\n | | | |\n +------+ +--+ +---+ +---+\n | | | |\n v +-----+ +-----+ v\n 88 t5 | - | i | + | 10\n +-+++-+ +-++-++\n | | | |\n +-----------------+ |\n | | | |\n +-----+ +----+-------+\n v v\n i0 1\n\n```", "_____no_output_____" ], [ "### 8.5.4\n\n> Construct the DAG for the code in block $B_3$ of Fig. 8.9.", "_____no_output_____" ], [ "```\n +-----+\n | []= | a[t4]\n ++-+-++\n | | |\n +--------+ | +--------+\n | | |\n v +--v--+ v\n a0 t4 | - | 0.0\n +-+-+-+\n | |\n +---+ +---+\n | |\n +--v--+ v +-----+\n t3 | * | 88 | <= |\n +-+-+-+ +---+-+\n | | | |\n+-----+ +---+ +---+ +---+\n| | | |\nv +--v--+ +--v--+ v\n8 t2 | + | j | + | 10\n +-+-+-+ +-+-+-+\n | | | |\n +---+ +--------+ +---+\n | || |\n +--v--+ vv v\n t1 | * | j0 1\n +-+-+-+\n | |\n+-----+ +---+\nv v\n10 i\n```", "_____no_output_____" ], [ "### 8.5.5\n\n> Extend Algorithm 8.7 to process three-statements of the form\n\n> a) `a[i] = b`\n\n> b) `a = b[i]`\n\n> c) `a = *b`\n\n> d) `*a = b`", "_____no_output_____" ], [ "1. ...\n2. set $a$ to \"not live\" and \"no next use\".\n3. set $b$ (and $i$) to \"live\" and the next uses of $b$ (and $i$) to statement", "_____no_output_____" ], [ "### 8.5.6\n\n> Construct the DAG for the basic block\n\n> ```\na[i] = b\n*p = c\nd = a[j]\ne = *p\n*p = a[i]\n```\n\n> on the assumption that\n\n> a) `p` can point anywhere.", "_____no_output_____" ], [ "Calculate `a[i]` twice.", "_____no_output_____" ], [ "> b) `p` can point only to `b` or `d`.", "_____no_output_____" ], [ "```\n +-----+ +-----+\n | *= | *p e | =* |\n +--+--+ +--+--+\n | |\n | |\n | |\n +--v--+ +-----+ +--v--+\n a[i] | []= | d | []= | *p0 | *= |\n ++-+-++ ++-+-++ +--+--+\n | | | | | | |\n | | | | | | |\n | | | | | | |\n | | | | | | |\n +------------------------+ | |\n | | | | | | |\n+------------------------------+ | |\n| | | | | | |\n| | | | +------------------------+ |\n| | | | | | |\n| <--+ +------+ +----+ | |\nv v v v v v\nd a i j b c\n```", "_____no_output_____" ], [ "### 8.5.7\n\n> Revise the DAG-construction algorithm to take advantage of such situations, and apply your algorithm to the code of Exercise 8.5.6.", "_____no_output_____" ], [ "```\na[i] = b\nd = a[j]\ne = c\n*p = b\n```", "_____no_output_____" ], [ "### 8.5.8\n\n> Suppose a basic block is formed from the C assignment statements\n\n> ```\nx = a + b + c + d + e + f;\ny = a + c + e;\n```\n\n> a) Give the three-address statements for this block.", "_____no_output_____" ], [ "```\nt1 = a + b\nt2 = t1 + c\nt3 = t2 + d\nt4 = t3 + e\nt5 = t4 + f\nx = t5\nt6 = a + c\nt7 = t6 + e\ny = t7\n```", "_____no_output_____" ], [ "> b) Use the associative and commutative laws to modify the block to use the fewest possible number of instructions, assuming both `x` and `y` are live on exit from the block.", "_____no_output_____" ], [ "```\nt1 = a + c\nt2 = t1 + e\ny = t2\nt3 = t2 + b\nt4 = t3 + d\nt5 = t4 + f\nx = t5\n```", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cb67a82cd4b6c059e2945206e09e5c91d174e35e
26,639
ipynb
Jupyter Notebook
code/model_zoo/pytorch_ipynb/custom-data-loader-mnist.ipynb
tongni1975/deep-learning-book
5e0b831c58a5cfab99b1db4b4bdbb1040bdd95aa
[ "MIT" ]
1
2021-06-19T07:44:47.000Z
2021-06-19T07:44:47.000Z
code/model_zoo/pytorch_ipynb/custom-data-loader-mnist.ipynb
bharat3012/deep-learning-book
839e076c5098084512c947a38878a9a545d9a87d
[ "MIT" ]
null
null
null
code/model_zoo/pytorch_ipynb/custom-data-loader-mnist.ipynb
bharat3012/deep-learning-book
839e076c5098084512c947a38878a9a545d9a87d
[ "MIT" ]
2
2020-09-07T12:43:33.000Z
2021-06-11T12:10:09.000Z
45.150847
10,036
0.664552
[ [ [ "*Accompanying code examples of the book \"Introduction to Artificial Neural Networks and Deep Learning: A Practical Guide with Applications in Python\" by [Sebastian Raschka](https://sebastianraschka.com). All code examples are released under the [MIT license](https://github.com/rasbt/deep-learning-book/blob/master/LICENSE). If you find this content useful, please consider supporting the work by buying a [copy of the book](https://leanpub.com/ann-and-deeplearning).*\n \nOther code examples and content are available on [GitHub](https://github.com/rasbt/deep-learning-book). The PDF and ebook versions of the book are available through [Leanpub](https://leanpub.com/ann-and-deeplearning).", "_____no_output_____" ] ], [ [ "%load_ext watermark\n%watermark -a 'Sebastian Raschka' -v -p torch", "Sebastian Raschka \n\nCPython 3.7.1\nIPython 7.2.0\n\ntorch 1.0.0\n" ] ], [ [ "# Model Zoo -- Using PyTorch Dataset Loading Utilities for Custom Datasets (MNIST)", "_____no_output_____" ], [ "This notebook provides an example for how to load an image dataset, stored as individual PNG files, using PyTorch's data loading utilities. For a more in-depth discussion, please see the official\n\n- [Data Loading and Processing Tutorial](http://pytorch.org/tutorials/beginner/data_loading_tutorial.html)\n- [torch.utils.data](http://pytorch.org/docs/master/data.html) API documentation\n\nIn this example, we are using the cropped version of the **Street View House Numbers (SVHN) Dataset**, which is available at http://ufldl.stanford.edu/housenumbers/. \n\nTo execute the following examples, you need to download the 2 \".mat\" files \n\n- [train_32x32.mat](http://ufldl.stanford.edu/housenumbers/train_32x32.mat) (ca. 182 Mb, 73,257 images)\n- [test_32x32.mat](http://ufldl.stanford.edu/housenumbers/test_32x32.mat) (ca. 65 Mb, 26,032 images)\n\n\n", "_____no_output_____" ], [ "## Imports", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport os\n\nimport torch\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\n\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport scipy.io as sio\nimport imageio", "_____no_output_____" ] ], [ [ "## Dataset", "_____no_output_____" ], [ "The following function will convert the images from \".mat\" into individual \".png\" files. In addition, we will create CSV contained the image paths and associated class labels.", "_____no_output_____" ] ], [ [ "def make_pngs(main_dir, mat_file, label):\n \n if not os.path.exists(main_dir):\n os.mkdir(main_dir)\n \n sub_dir = os.path.join(main_dir, label)\n if not os.path.exists(sub_dir):\n os.mkdir(sub_dir)\n\n data = sio.loadmat(mat_file)\n\n X = np.transpose(data['X'], (3, 0, 1, 2))\n y = data['y'].flatten()\n\n with open(os.path.join(main_dir, '%s_labels.csv' % label), 'w') as out_f:\n for i, img in enumerate(X):\n file_path = os.path.join(sub_dir, str(i) + '.png')\n imageio.imwrite(os.path.join(file_path),\n img)\n\n out_f.write(\"%d.png,%d\\n\" % (i, y[i]))\n\n \nmake_pngs(main_dir='svhn_cropped',\n mat_file='train_32x32.mat',\n label='train')\n \n \nmake_pngs(main_dir='svhn_cropped',\n mat_file='test_32x32.mat',\n label='test')", "_____no_output_____" ], [ "df = pd.read_csv('svhn_cropped/train_labels.csv', header=None, index_col=0)\ndf.head()", "_____no_output_____" ], [ "df = pd.read_csv('svhn_cropped/test_labels.csv', header=None, index_col=0)\ndf.head()", "_____no_output_____" ] ], [ [ "## Implementing a Custom Dataset Class", "_____no_output_____" ], [ "Now, we implement a custom `Dataset` for reading the images. The `__getitem__` method will\n\n1. read a single image from disk based on an `index` (more on batching later)\n2. perform a custom image transformation (if a `transform` argument is provided in the `__init__` construtor)\n3. return a single image and it's corresponding label", "_____no_output_____" ] ], [ [ "class SVHNDataset(Dataset):\n \"\"\"Custom Dataset for loading cropped SVHN images\"\"\"\n \n def __init__(self, csv_path, img_dir, transform=None):\n \n df = pd.read_csv(csv_path, index_col=0, header=None)\n self.img_dir = img_dir\n self.csv_path = csv_path\n self.img_names = df.index.values\n self.y = df[1].values\n self.transform = transform\n\n def __getitem__(self, index):\n img = Image.open(os.path.join(self.img_dir,\n self.img_names[index]))\n \n if self.transform is not None:\n img = self.transform(img)\n \n label = self.y[index]\n return img, label\n\n def __len__(self):\n return self.y.shape[0]", "_____no_output_____" ] ], [ [ "Now that we have created our custom Dataset class, let us add some custom transformations via the `transforms` utilities from `torchvision`, we\n\n1. normalize the images (here: dividing by 255)\n2. converting the image arrays into PyTorch tensors\n\nThen, we initialize a Dataset instance for the training images using the 'quickdraw_png_set1_train.csv' label file (we omit the test set, but the same concepts apply).\n\nFinally, we initialize a `DataLoader` that allows us to read from the dataset.", "_____no_output_____" ] ], [ [ "# Note that transforms.ToTensor()\n# already divides pixels by 255. internally\n\ncustom_transform = transforms.Compose([#transforms.Grayscale(), \n #transforms.Lambda(lambda x: x/255.),\n transforms.ToTensor()])\n\ntrain_dataset = SVHNDataset(csv_path='svhn_cropped/train_labels.csv',\n img_dir='svhn_cropped/train',\n transform=custom_transform)\n\ntest_dataset = SVHNDataset(csv_path='svhn_cropped/test_labels.csv',\n img_dir='svhn_cropped/test',\n transform=custom_transform)\n\nBATCH_SIZE=128\n\n\ntrain_loader = DataLoader(dataset=train_dataset,\n batch_size=BATCH_SIZE,\n shuffle=True,\n num_workers=4)\n\ntest_loader = DataLoader(dataset=test_dataset,\n batch_size=BATCH_SIZE,\n shuffle=False,\n num_workers=4)", "_____no_output_____" ] ], [ [ "That's it, now we can iterate over an epoch using the train_loader as an iterator and use the features and labels from the training dataset for model training:", "_____no_output_____" ], [ "## Iterating Through the Custom Dataset", "_____no_output_____" ] ], [ [ "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\ntorch.manual_seed(0)\n\nnum_epochs = 2\nfor epoch in range(num_epochs):\n\n for batch_idx, (x, y) in enumerate(train_loader):\n \n print('Epoch:', epoch+1, end='')\n print(' | Batch index:', batch_idx, end='')\n print(' | Batch size:', y.size()[0])\n \n x = x.to(device)\n y = y.to(device)\n break", "Epoch: 1 | Batch index: 0 | Batch size: 128\nEpoch: 2 | Batch index: 0 | Batch size: 128\n" ] ], [ [ "Just to make sure that the batches are being loaded correctly, let's print out the dimensions of the last batch:", "_____no_output_____" ] ], [ [ "x.shape", "_____no_output_____" ] ], [ [ "As we can see, each batch consists of 128 images, just as specified. However, one thing to keep in mind though is that\nPyTorch uses a different image layout (which is more efficient when working with CUDA); here, the image axes are \"num_images x channels x height x width\" (NCHW) instead of \"num_images height x width x channels\" (NHWC):", "_____no_output_____" ], [ "To visually check that the images that coming of the data loader are intact, let's swap the axes to NHWC and convert an image from a Torch Tensor to a NumPy array so that we can visualize the image via `imshow`:", "_____no_output_____" ] ], [ [ "one_image = x[99].permute(1, 2, 0)\none_image.shape", "_____no_output_____" ], [ "# note that imshow also works fine with scaled\n# images in [0, 1] range.\nplt.imshow(one_image.to(torch.device('cpu')));", "_____no_output_____" ], [ "%watermark -iv", "pandas 0.23.4\nscipy 1.1.0\nmatplotlib 3.0.2\nimageio 2.4.1\ntorch 1.0.0\nPIL.Image 5.3.0\nnumpy 1.15.4\ntorchvision 0.2.1\n\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
cb67a92d335303c9b6ac1b7344396ea6bf83251a
17,380
ipynb
Jupyter Notebook
Python/10_matplotlib's_imshow.ipynb
seungkyoon/SimpleITK-Notebooks
b8e828d5ae855fb49186cd4adfd2cd12b7b96553
[ "Apache-2.0" ]
null
null
null
Python/10_matplotlib's_imshow.ipynb
seungkyoon/SimpleITK-Notebooks
b8e828d5ae855fb49186cd4adfd2cd12b7b96553
[ "Apache-2.0" ]
null
null
null
Python/10_matplotlib's_imshow.ipynb
seungkyoon/SimpleITK-Notebooks
b8e828d5ae855fb49186cd4adfd2cd12b7b96553
[ "Apache-2.0" ]
2
2018-12-24T06:43:52.000Z
2020-01-13T08:31:19.000Z
29.557823
323
0.573418
[ [ [ "# Using `matplotlib` to display inline images\n\nIn this notebook we will explore using `matplotlib` to display images in our notebooks, and work towards developing a reusable function to display 2D,3D, color, and label overlays for SimpleITK images.\n\nWe will also look at the subtleties of working with image filters that require the input images' to be overlapping. ", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n%matplotlib inline\nimport SimpleITK as sitk\n# Download data to work on\n%run update_path_to_download_script\nfrom downloaddata import fetch_data as fdata", "_____no_output_____" ] ], [ [ "SimpleITK has a built in `Show` method which saves the image to disk and launches a user configurable program ( defaults to ImageJ ), to display the image. ", "_____no_output_____" ] ], [ [ "img1 = sitk.ReadImage(fdata(\"cthead1.png\"))\nsitk.Show(img1, title=\"cthead1\")", "_____no_output_____" ], [ "img2 = sitk.ReadImage(fdata(\"VM1111Shrink-RGB.png\"))\nsitk.Show(img2, title=\"Visible Human Head\")", "_____no_output_____" ], [ "nda = sitk.GetArrayViewFromImage(img1)\nplt.imshow(nda)", "_____no_output_____" ], [ "nda = sitk.GetArrayViewFromImage(img2)\nax = plt.imshow(nda)", "_____no_output_____" ], [ "def myshow(img):\n nda = sitk.GetArrayViewFromImage(img)\n plt.imshow(nda)", "_____no_output_____" ], [ "myshow(img2)", "_____no_output_____" ], [ "myshow(sitk.Expand(img2, [10]*5))", "_____no_output_____" ] ], [ [ "This image does not appear bigger.\n\nThere are numerous improvements that we can make:\n\n - support 3d images\n - include a title\n - use physical pixel size for axis labels\n - show the image as gray values", "_____no_output_____" ] ], [ [ "def myshow(img, title=None, margin=0.05, dpi=80):\n nda = sitk.GetArrayViewFromImage(img)\n spacing = img.GetSpacing()\n \n if nda.ndim == 3:\n # fastest dim, either component or x\n c = nda.shape[-1]\n \n # the the number of components is 3 or 4 consider it an RGB image\n if not c in (3,4):\n nda = nda[nda.shape[0]//2,:,:]\n \n elif nda.ndim == 4:\n c = nda.shape[-1]\n \n if not c in (3,4):\n raise Runtime(\"Unable to show 3D-vector Image\")\n \n # take a z-slice\n nda = nda[nda.shape[0]//2,:,:,:]\n \n ysize = nda.shape[0]\n xsize = nda.shape[1]\n \n # Make a figure big enough to accommodate an axis of xpixels by ypixels\n # as well as the ticklabels, etc...\n figsize = (1 + margin) * ysize / dpi, (1 + margin) * xsize / dpi\n\n fig = plt.figure(figsize=figsize, dpi=dpi)\n # Make the axis the right size...\n ax = fig.add_axes([margin, margin, 1 - 2*margin, 1 - 2*margin])\n \n extent = (0, xsize*spacing[1], ysize*spacing[0], 0)\n \n t = ax.imshow(nda,extent=extent,interpolation=None)\n \n if nda.ndim == 2:\n t.set_cmap(\"gray\")\n \n if(title):\n plt.title(title)", "_____no_output_____" ], [ "myshow(sitk.Expand(img2,[2,2]), title=\"Big Visibile Human Head\")", "_____no_output_____" ] ], [ [ "## Tips and Tricks for Visualizing Segmentations\n\nWe start by loading a segmented image. As the segmentation is just an image with integral data, we can display the labels as we would any other image.", "_____no_output_____" ] ], [ [ "img1_seg = sitk.ReadImage(fdata(\"2th_cthead1.png\"))\nmyshow(img1_seg, \"Label Image as Grayscale\")", "_____no_output_____" ] ], [ [ "We can also map the scalar label image to a color image as shown below.", "_____no_output_____" ] ], [ [ "myshow(sitk.LabelToRGB(img1_seg), title=\"Label Image as RGB\")", "_____no_output_____" ] ], [ [ "Most filters which take multiple images as arguments require that the images occupy the same physical space. That is the pixel you are operating must refer to the same location. Luckily for us our image and labels do occupy the same physical space, allowing us to overlay the segmentation onto the original image.", "_____no_output_____" ] ], [ [ "myshow(sitk.LabelOverlay(img1, img1_seg), title=\"Label Overlayed\")", "_____no_output_____" ] ], [ [ "We can also overlay the labels as contours.", "_____no_output_____" ] ], [ [ "myshow(sitk.LabelOverlay(img1, sitk.LabelContour(img1_seg), 1.0))", "_____no_output_____" ] ], [ [ "## Tips and Tricks for 3D Image Visualization\n\nNow lets move on to visualizing real MRI images with segmentations. The Surgical Planning Laboratory at Brigham and Women's Hospital provides a wonderful Multi-modality MRI-based Atlas of the Brain that we can use.\n\nPlease note, what is done here is for convenience and is not the common way images are displayed for radiological work.", "_____no_output_____" ] ], [ [ "img_T1 = sitk.ReadImage(fdata(\"nac-hncma-atlas2013-Slicer4Version/Data/A1_grayT1.nrrd\"))\nimg_T2 = sitk.ReadImage(fdata(\"nac-hncma-atlas2013-Slicer4Version/Data/A1_grayT2.nrrd\"))\nimg_labels = sitk.ReadImage(fdata(\"nac-hncma-atlas2013-Slicer4Version/Data/hncma-atlas.nrrd\"))", "_____no_output_____" ], [ "myshow(img_T1)\nmyshow(img_T2)\nmyshow(sitk.LabelToRGB(img_labels))", "_____no_output_____" ], [ "size = img_T1.GetSize()\nmyshow(img_T1[:,size[1]//2,:])", "_____no_output_____" ], [ "slices =[img_T1[size[0]//2,:,:], img_T1[:,size[1]//2,:], img_T1[:,:,size[2]//2]]\nmyshow(sitk.Tile(slices, [3,1]), dpi=20)", "_____no_output_____" ], [ "nslices = 5\nslices = [ img_T1[:,:,s] for s in range(0, size[2], size[0]//(nslices+1))]\nmyshow(sitk.Tile(slices, [1,0]))", "_____no_output_____" ] ], [ [ "Let's create a version of the show methods which allows the selection of slices to be displayed.", "_____no_output_____" ] ], [ [ "def myshow3d(img, xslices=[], yslices=[], zslices=[], title=None, margin=0.05, dpi=80):\n size = img.GetSize()\n img_xslices = [img[s,:,:] for s in xslices]\n img_yslices = [img[:,s,:] for s in yslices]\n img_zslices = [img[:,:,s] for s in zslices]\n \n maxlen = max(len(img_xslices), len(img_yslices), len(img_zslices))\n \n \n img_null = sitk.Image([0,0], img.GetPixelID(), img.GetNumberOfComponentsPerPixel())\n \n img_slices = []\n d = 0\n \n if len(img_xslices):\n img_slices += img_xslices + [img_null]*(maxlen-len(img_xslices))\n d += 1\n \n if len(img_yslices):\n img_slices += img_yslices + [img_null]*(maxlen-len(img_yslices))\n d += 1\n \n if len(img_zslices):\n img_slices += img_zslices + [img_null]*(maxlen-len(img_zslices))\n d +=1\n \n if maxlen != 0:\n if img.GetNumberOfComponentsPerPixel() == 1:\n img = sitk.Tile(img_slices, [maxlen,d])\n #TO DO check in code to get Tile Filter working with vector images\n else:\n img_comps = []\n for i in range(0,img.GetNumberOfComponentsPerPixel()):\n img_slices_c = [sitk.VectorIndexSelectionCast(s, i) for s in img_slices]\n img_comps.append(sitk.Tile(img_slices_c, [maxlen,d]))\n img = sitk.Compose(img_comps)\n \n \n myshow(img, title, margin, dpi)\n", "_____no_output_____" ], [ "myshow3d(img_T1,yslices=range(50,size[1]-50,20), zslices=range(50,size[2]-50,20), dpi=30)", "_____no_output_____" ], [ "myshow3d(img_T2,yslices=range(50,size[1]-50,30), zslices=range(50,size[2]-50,20), dpi=30)", "_____no_output_____" ], [ "myshow3d(sitk.LabelToRGB(img_labels),yslices=range(50,size[1]-50,20), zslices=range(50,size[2]-50,20), dpi=30)", "_____no_output_____" ] ], [ [ "We next visualize the T1 image with an overlay of the labels.", "_____no_output_____" ] ], [ [ "# Why doesn't this work? The images do overlap in physical space.\nmyshow3d(sitk.LabelOverlay(img_T1,img_labels),yslices=range(50,size[1]-50,20), zslices=range(50,size[2]-50,20), dpi=30)", "_____no_output_____" ] ], [ [ "Two ways to solve our problem: (1) resample the labels onto the image grid (2) resample the image onto the label grid. The difference between the two from a computation standpoint depends on the grid sizes and on the interpolator used to estimate values at non-grid locations. \n\nNote interpolating a label image with an interpolator that can generate non-label values is problematic as you may end up with an image that has more classes/labels than your original. This is why we only use the nearest neighbor interpolator when working with label images.", "_____no_output_____" ] ], [ [ "# Option 1: Resample the label image using the identity transformation\nresampled_img_labels = sitk.Resample(img_labels, img_T1, sitk.Transform(), sitk.sitkNearestNeighbor,\n 0.0, img_labels.GetPixelID())\n# Overlay onto the T1 image, requires us to rescale the intensity of the T1 image to [0,255] and cast it so that it can \n# be combined with the color overlay (we use an alpha blending of 0.5).\nmyshow3d(sitk.LabelOverlay(sitk.Cast(sitk.RescaleIntensity(img_T1), sitk.sitkUInt8),resampled_img_labels, 0.5),\n yslices=range(50,size[1]-50,20), zslices=range(50,size[2]-50,20), dpi=30)", "_____no_output_____" ], [ "# Option 2: Resample the T1 image using the identity transformation\nresampled_T1 = sitk.Resample(img_T1, img_labels, sitk.Transform(), sitk.sitkLinear,\n 0.0, img_T1.GetPixelID())\n# Overlay onto the T1 image, requires us to rescale the intensity of the T1 image to [0,255] and cast it so that it can \n# be combined with the color overlay (we use an alpha blending of 0.5).\nmyshow3d(sitk.LabelOverlay(sitk.Cast(sitk.RescaleIntensity(resampled_T1), sitk.sitkUInt8),img_labels, 0.5),\n yslices=range(50,size[1]-50,20), zslices=range(50,size[2]-50,20), dpi=30)", "_____no_output_____" ] ], [ [ "Why are the two displays above different? (hint: in the calls to the \"myshow3d\" function the indexes of the y and z slices are the same). ", "_____no_output_____" ], [ "### There and back again\n\nIn some cases you may want to work with the intensity values or labels outside of SimpleITK, for example you implement an algorithm in Python and you don't care about the physical spacing of things (you are actually assuming the volume is isotropic).\n\n\nHow do you get back to the physical space?", "_____no_output_____" ] ], [ [ "def my_algorithm(image_as_numpy_array):\n # res is the image result of your algorithm, has the same grid size as the original image\n res = image_as_numpy_array\n return res\n\n# There (run your algorithm), and back again (convert the result into a SimpleITK image)\nres_image = sitk.GetImageFromArray(my_algorithm(sitk.GetArrayFromImage(img_T1)))\n\n# Now lets add the original image to the processed one, why doesn't this work?\nres_image + img_T1", "_____no_output_____" ] ], [ [ "When we converted the SimpleITK image to a numpy array we lost the spatial information (origin, spacing, direction cosine matrix). Converting the numpy array back to a SimpleITK image simply set the value of these components to reasonable defaults. We can easily restore the original values to deal with this issue. ", "_____no_output_____" ] ], [ [ "res_image.CopyInformation(img_T1)\nres_image + img_T1", "_____no_output_____" ] ], [ [ "The ``myshow`` and ``myshow3d`` functions are really useful. They have been copied into a \"myshow.py\" file so that they can be imported into other notebooks.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cb67ba0cbd682780061dc5b677ed2b2e57e570c4
16,380
ipynb
Jupyter Notebook
2020.07.2400_classification/.ipynb_checkpoints/LR_knn_sqrt-checkpoint.ipynb
danhtaihoang/classification
2c38012c28d50d4727f9242c792c4105a3a15fef
[ "MIT" ]
null
null
null
2020.07.2400_classification/.ipynb_checkpoints/LR_knn_sqrt-checkpoint.ipynb
danhtaihoang/classification
2c38012c28d50d4727f9242c792c4105a3a15fef
[ "MIT" ]
null
null
null
2020.07.2400_classification/.ipynb_checkpoints/LR_knn_sqrt-checkpoint.ipynb
danhtaihoang/classification
2c38012c28d50d4727f9242c792c4105a3a15fef
[ "MIT" ]
null
null
null
41.363636
198
0.593162
[ [ [ "## Logistic Regression", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\n\nfrom sklearn.model_selection import train_test_split,KFold\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import confusion_matrix,accuracy_score,precision_score,\\\nrecall_score,roc_curve,auc\n\nimport expectation_reflection as ER\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import GridSearchCV\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom function import split_train_test,make_data_balance", "_____no_output_____" ], [ "np.random.seed(1)", "_____no_output_____" ] ], [ [ "First of all, the processed data are imported.", "_____no_output_____" ] ], [ [ "#data_list = ['1paradox','2peptide','3stigma']\n#data_list = np.loadtxt('data_list.txt',dtype='str')\ndata_list = np.loadtxt('data_list_30sets.txt',dtype='str')\n#data_list = ['9coag']\n\nprint(data_list)", "['1paradox' '2peptide' '3stigma' '4nki' '5mental' '6smoking' '7anemia'\n '8language' '9coag' '10tazamia' '11hepato' '12heat' '13ef' '14cervix'\n '15heart' '16liver' '17nwosu' '18school' '19ibs' '21survival'\n '29parkinson' '30paradox2' '31renal' '33svr' '35pcos' '36probiotic'\n '101kidney' '102breast_cancer' '103diabetes_niddk'\n '104diabetic_retinopathy']\n" ], [ "def read_data(data_id): \n data_name = data_list[data_id]\n print('data_name:',data_name)\n Xy = np.loadtxt('../classification_data/%s/data_processed_knn_sqrt.dat'%data_name) \n X = Xy[:,:-1]\n y = Xy[:,-1]\n\n #print(np.unique(y,return_counts=True))\n X,y = make_data_balance(X,y)\n print(np.unique(y,return_counts=True))\n\n X, y = shuffle(X, y, random_state=1)\n X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.5,random_state = 1)\n \n sc = MinMaxScaler()\n X_train = sc.fit_transform(X_train)\n X_test = sc.transform(X_test)\n \n return X_train,X_test,y_train,y_test", "_____no_output_____" ], [ "def measure_performance(X_train,X_test,y_train,y_test):\n \n #model = LogisticRegression(max_iter=100)\n model = SGDClassifier(loss='log',max_iter=1000,tol=0.001) # 'log' for logistic regression, 'hinge' for SVM\n\n # regularization penalty space\n #penalty = ['l1','l2']\n penalty = ['elasticnet']\n\n # solver\n #solver=['saga']\n #solver=['liblinear']\n\n # regularization hyperparameter space\n #C = np.logspace(0, 4, 10)\n #C = [0.001,0.1,1.0,10.0,100.0]\n alpha = [0.001,0.01,0.1,1.0,10.,100.]\n\n # l1_ratio\n #l1_ratio = [0.1,0.5,0.9]\n l1_ratio = [0.,0.2,0.4,0.6,0.8,1.0]\n\n # Create hyperparameter options\n #hyperparameters = dict(penalty=penalty,solver=solver,C=C,l1_ratio=l1_ratio)\n #hyper_parameters = dict(penalty=penalty,solver=solver,C=C)\n hyper_parameters = dict(penalty=penalty,alpha=alpha,l1_ratio=l1_ratio)\n \n # Create grid search using cross validation\n clf = GridSearchCV(model, hyper_parameters, cv=4, iid='deprecated')\n \n # Fit grid search\n best_model = clf.fit(X_train, y_train)\n \n # View best hyperparameters\n #print('Best Penalty:', best_model.best_estimator_.get_params()['penalty'])\n #print('Best C:', best_model.best_estimator_.get_params()['C'])\n #print('Best alpha:', best_model.best_estimator_.get_params()['alpha'])\n #print('Best l1_ratio:', best_model.best_estimator_.get_params()['l1_ratio'])\n \n # best hyper parameters\n print('best_hyper_parameters:',best_model.best_params_)\n\n # performance:\n y_test_pred = best_model.best_estimator_.predict(X_test)\n acc = accuracy_score(y_test,y_test_pred)\n #print('Accuracy:', acc)\n\n p_test_pred = best_model.best_estimator_.predict_proba(X_test) # prob of [0,1]\n p_test_pred = p_test_pred[:,1] # prob of 1 \n fp,tp,thresholds = roc_curve(y_test, p_test_pred, drop_intermediate=False)\n roc_auc = auc(fp,tp)\n #print('AUC:', roc_auc)\n\n precision = precision_score(y_test,y_test_pred)\n #print('Precision:',precision)\n\n recall = recall_score(y_test,y_test_pred)\n #print('Recall:',recall)\n \n f1_score = 2*precision*recall/(precision+recall)\n\n return acc,roc_auc,precision,recall,f1_score", "_____no_output_____" ], [ "n_data = len(data_list)\nroc_auc = np.zeros(n_data) ; acc = np.zeros(n_data)\nprecision = np.zeros(n_data) ; recall = np.zeros(n_data)\nf1_score = np.zeros(n_data)\n\n#data_id = 0\nfor data_id in range(n_data):\n X_train,X_test,y_train,y_test = read_data(data_id)\n acc[data_id],roc_auc[data_id],precision[data_id],recall[data_id],f1_score[data_id] =\\\n measure_performance(X_train,X_test,y_train,y_test)\n print(data_id,acc[data_id],roc_auc[data_id],precision[data_id],recall[data_id],f1_score[data_id]) \n ", "data_name: 1paradox\n(array([-1., 1.]), array([60, 60]))\nbest_hyper_parameters: {'alpha': 0.001, 'l1_ratio': 0.8, 'penalty': 'elasticnet'}\n0 0.7833333333333333 0.8760282021151586 0.6666666666666666 0.8695652173913043 0.7547169811320754\ndata_name: 2peptide\n(array([-1., 1.]), array([23, 23]))\nbest_hyper_parameters: {'alpha': 0.001, 'l1_ratio': 0.8, 'penalty': 'elasticnet'}\n1 0.9565217391304348 1.0 1.0 0.9166666666666666 0.9565217391304348\ndata_name: 3stigma\n(array([-1., 1.]), array([2725, 2725]))\nbest_hyper_parameters: {'alpha': 0.001, 'l1_ratio': 0.2, 'penalty': 'elasticnet'}\n2 0.996697247706422 0.9999859864715552 1.0 0.9932330827067669 0.9966050546963411\ndata_name: 4nki\n(array([-1., 1.]), array([77, 77]))\nbest_hyper_parameters: {'alpha': 0.1, 'l1_ratio': 0.2, 'penalty': 'elasticnet'}\n3 0.7142857142857143 0.8418918918918918 0.6829268292682927 0.7567567567567568 0.7179487179487181\ndata_name: 5mental\n(array([-1., 1.]), array([147, 147]))\nbest_hyper_parameters: {'alpha': 1.0, 'l1_ratio': 0.0, 'penalty': 'elasticnet'}\n4 0.6598639455782312 0.6890289103039289 0.6521739130434783 0.6338028169014085 0.6428571428571428\ndata_name: 6smoking\n(array([-1., 1.]), array([722, 722]))\nbest_hyper_parameters: {'alpha': 0.001, 'l1_ratio': 0.2, 'penalty': 'elasticnet'}\n5 1.0 1.0 1.0 1.0 1.0\ndata_name: 7anemia\n(array([-1., 1.]), array([43, 43]))\nbest_hyper_parameters: {'alpha': 0.001, 'l1_ratio': 0.8, 'penalty': 'elasticnet'}\n6 0.8372093023255814 0.9 0.8095238095238095 0.85 0.8292682926829269\ndata_name: 8language\n(array([-1., 1.]), array([267, 267]))\nbest_hyper_parameters: {'alpha': 0.01, 'l1_ratio': 0.4, 'penalty': 'elasticnet'}\n7 0.7378277153558053 0.8552912131073953 0.8478260869565217 0.582089552238806 0.6902654867256638\ndata_name: 9coag\n(array([-1., 1.]), array([504, 504]))\nbest_hyper_parameters: {'alpha': 0.1, 'l1_ratio': 0.0, 'penalty': 'elasticnet'}\n8 0.6170634920634921 0.670047883064516 0.5992779783393501 0.6693548387096774 0.6323809523809524\ndata_name: 10tazamia\n(array([-1., 1.]), array([124, 124]))\nbest_hyper_parameters: {'alpha': 0.001, 'l1_ratio': 0.2, 'penalty': 'elasticnet'}\n9 0.7338709677419355 0.8323337679269883 0.7222222222222222 0.8 0.759124087591241\ndata_name: 11hepato\n(array([-1., 1.]), array([63, 63]))\nbest_hyper_parameters: {'alpha': 0.01, 'l1_ratio': 0.2, 'penalty': 'elasticnet'}\n10 0.6666666666666666 0.7227822580645162 0.631578947368421 0.7741935483870968 0.6956521739130435\ndata_name: 12heat\n(array([-1., 1.]), array([83, 83]))\nbest_hyper_parameters: {'alpha': 0.1, 'l1_ratio': 0.0, 'penalty': 'elasticnet'}\n11 0.7349397590361446 0.7514619883040935 0.7804878048780488 0.7111111111111111 0.7441860465116279\ndata_name: 13ef\n(array([-1., 1.]), array([93, 93]))\nbest_hyper_parameters: {'alpha': 0.001, 'l1_ratio': 0.6, 'penalty': 'elasticnet'}\n12 0.989247311827957 0.999537037037037 1.0 0.9777777777777777 0.9887640449438202\ndata_name: 14cervix\n(array([-1., 1.]), array([24, 24]))\nbest_hyper_parameters: {'alpha': 0.001, 'l1_ratio': 0.0, 'penalty': 'elasticnet'}\n13 0.9583333333333334 1.0 1.0 0.9333333333333333 0.9655172413793104\ndata_name: 15heart\n(array([-1., 1.]), array([138, 138]))\nbest_hyper_parameters: {'alpha': 0.1, 'l1_ratio': 0.8, 'penalty': 'elasticnet'}\n14 0.7681159420289855 0.8691934121621623 0.8620689655172413 0.6756756756756757 0.7575757575757576\ndata_name: 16liver\n(array([-1., 1.]), array([167, 167]))\nbest_hyper_parameters: {'alpha': 0.001, 'l1_ratio': 0.6, 'penalty': 'elasticnet'}\n15 0.6407185628742516 0.6836206896551724 0.5957446808510638 0.9655172413793104 0.7368421052631579\ndata_name: 17nwosu\n(array([-1., 1.]), array([59, 59]))\nbest_hyper_parameters: {'alpha': 0.01, 'l1_ratio': 0.2, 'penalty': 'elasticnet'}\n16 1.0 1.0 1.0 1.0 1.0\ndata_name: 18school\n(array([-1., 1.]), array([68, 68]))\nbest_hyper_parameters: {'alpha': 0.001, 'l1_ratio': 0.2, 'penalty': 'elasticnet'}\n17 0.8088235294117647 0.8576388888888888 0.8275862068965517 0.75 0.7868852459016394\ndata_name: 19ibs\n(array([-1., 1.]), array([33, 33]))\nbest_hyper_parameters: {'alpha': 0.001, 'l1_ratio': 0.2, 'penalty': 'elasticnet'}\n18 0.9090909090909091 0.962962962962963 0.8947368421052632 0.9444444444444444 0.918918918918919\ndata_name: 21survival\n(array([-1., 1.]), array([123, 123]))\nbest_hyper_parameters: {'alpha': 0.01, 'l1_ratio': 1.0, 'penalty': 'elasticnet'}\n19 0.7154471544715447 0.8531746031746031 0.6811594202898551 0.7833333333333333 0.7286821705426356\ndata_name: 29parkinson\n(array([-1., 1.]), array([48, 48]))\nbest_hyper_parameters: {'alpha': 0.001, 'l1_ratio': 0.8, 'penalty': 'elasticnet'}\n20 0.75 0.8536155202821869 0.6666666666666666 0.8571428571428571 0.75\ndata_name: 30paradox2\n(array([-1., 1.]), array([52, 52]))\nbest_hyper_parameters: {'alpha': 0.01, 'l1_ratio': 0.8, 'penalty': 'elasticnet'}\n21 0.9807692307692307 0.9761904761904762 1.0 0.9583333333333334 0.9787234042553191\ndata_name: 31renal\n(array([-1., 1.]), array([47, 47]))\nbest_hyper_parameters: {'alpha': 1.0, 'l1_ratio': 0.0, 'penalty': 'elasticnet'}\n22 0.8723404255319149 0.927536231884058 0.84 0.9130434782608695 0.8749999999999999\ndata_name: 33svr\n(array([-1., 1.]), array([41, 41]))\nbest_hyper_parameters: {'alpha': 0.001, 'l1_ratio': 0.0, 'penalty': 'elasticnet'}\n23 0.975609756097561 0.9856459330143541 1.0 0.9473684210526315 0.972972972972973\ndata_name: 35pcos\n(array([-1., 1.]), array([177, 177]))\nbest_hyper_parameters: {'alpha': 0.01, 'l1_ratio': 0.6, 'penalty': 'elasticnet'}\n24 0.8813559322033898 0.9692288049029623 0.8526315789473684 0.9204545454545454 0.8852459016393441\ndata_name: 36probiotic\n(array([-1., 1.]), array([10, 10]))\n" ], [ "print('acc_mean:',acc.mean())\nprint('roc_mean:',roc_auc.mean())\nprint('precision:',precision.mean())\nprint('recall:',recall.mean())\nprint('f1_score:',f1_score.mean())", "acc_mean: 0.8296819491383333\nroc_mean: 0.8886013486619515\nprecision: 0.8375415495178863\nrecall: 0.8347199127569022\nf1_score: 0.8296999206199118\n" ], [ "np.savetxt('result_knn_sqrt_LR.dat',(roc_auc,acc,precision,recall,f1_score),fmt='%f')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
cb67c4d0ab6887835a476beb85f6a5f3385f6793
163,165
ipynb
Jupyter Notebook
02. Interpolacion/01. Interpolacion.ipynb
ashcat2005/AstrofisicaComputacional2022
67463ec4041eb08c0f326792fed0dcf9e970e9b7
[ "MIT" ]
3
2022-03-08T06:18:56.000Z
2022-03-10T04:55:53.000Z
02. Interpolacion/01. Interpolacion.ipynb
ashcat2005/AstrofisicaComputacional2022
67463ec4041eb08c0f326792fed0dcf9e970e9b7
[ "MIT" ]
null
null
null
02. Interpolacion/01. Interpolacion.ipynb
ashcat2005/AstrofisicaComputacional2022
67463ec4041eb08c0f326792fed0dcf9e970e9b7
[ "MIT" ]
4
2022-03-09T17:47:43.000Z
2022-03-21T02:29:36.000Z
163.165
23,008
0.884007
[ [ [ "![Astrofisica Computacional](../logo.PNG)", "_____no_output_____" ], [ "---\n## 01. Interpolación de Funciones\n\n\nEduard Larrañaga ([email protected])\n\n---", "_____no_output_____" ], [ "## Interpolación \n\n### Resumen\n\nEn este cuaderno se presentan algunas de las técnicas de interpolación de una función.\n\n---", "_____no_output_____" ], [ "## Interpolación\n\nLos datos astrofísicos (experimentales y sintéticos) usualmente consiten de un conjunto de valores discretos con la forma $(x_j, f_j)$ en donde se representa el valor de una función $f(x)$ paa un conjunto finito de argumentos $\\{ x_0, x_1, x_2, ..., x_{n} \\}$. Sin embargo, en muchas ocasiones se necesita conocer el valor de la función en puntos adicionales (que no pertenecen al conjunto dado). La **interpolación** es el método que permite obtener estos valores.\n\nPor **interpolación** entenderemos el definir una función $g(x)$, utilizando la información discreta conocida y de tal forma que $g(x_j) = f(x_j)$ y que se aproxime el valor de la función $f$ en cualquier punto $x \\in [x_{min}, x_{max}]$, done $x_{min} = \\min [x_j]$ y $x_{max} = \\max \\{ x_j \\}$. \n\nPor otro lado, la **extrapolación** correspondería a aproximar el valor de la función $f$ en un punto $x \\notin [x_{min}, x_{max}]$}. Sin embargo, este caso no será analizado aquí.\n \n--- \n## Interpolación Lineal Simple \n\nEl método de interpolación más simple es denominado **Interpolación Polinomial** y consiste en encontrar un polinomio $p_n(x)$ de grado $n$ que pasa por $N = n+1$ puntos $x_j$ tomando los valores $p(x_j) = f(x_j)$, donde $j=0,1,2,...,n$. \n\nEl polinomio se escribe en la forma general\n\n$p_n(x) = a_0 + a_1 x + a_2 x^2 + \\cdots + a_n x^n$\n\ndonde $a_i$ son $n+1$-constantes reales que se determinarán por las condiciones\n\n$\\left( \n\\begin{array}{ccccc}\n1&x_0^1&x_0^2&\\cdots&x_0^n\\\\\n\\vdots&\\vdots&\\vdots&\\vdots&\\vdots\\\\\n\\vdots&\\vdots&\\vdots&\\vdots&\\vdots\\\\\n1&x_n^1&x_n^2&\\cdots&x_n^n\\\\\n\\end{array}\n\\right)\n\\left(\\begin{array}{c}\na_0\\\\\n\\vdots\\\\\n\\vdots\\\\\na_n\n\\end{array}\\right)\n=\n\\left(\\begin{array}{c}\nf(x_0)\\\\\n\\vdots\\\\\n\\vdots\\\\\nf(x_n)\n\\end{array}\\right)$\n\nLa solución de este sistema es fácil de obtener en los casos de interpolación lineal ($n=1$) y cuadrática ($n=2$), pero puede ser dificil de encontrar para un valor grande de $n$. ", "_____no_output_____" ], [ "---\n### Interpolación Lineal\n\nLa interpolación lineal ($n=1$) de una función $f(x)$ en un intervalo\n$[x_i,x_{i+1}]$ requiere conocer solamente dos puntos.\n\nResolviendo el sistema lineal resultante se obtiene el polinomio interpolado\n\n\\begin{equation}\np_1(x) = f(x_i) + \\frac{f(x_{i+1}) - f(x_i)}{x_{i+1} - x_i} (x-x_i) + \\mathcal{O}(\\Delta x^2)\n\\end{equation}\n\ndonde $\\Delta x = x_{i+1} - x_i$.\n\nEl método de interpolación lineal provee un polinomio con una precisión de segundo orden que puede ser derivado una vez, pero esta derivada no es continua en los puntos extremos del intervalo de interpolación, $x_i$ y $x_{i+1}$.", "_____no_output_____" ], [ "#### Ejemplo. Interpolación Lineal por intervalos\n\nA continuación se leerá un conjunto de datos desde un archivo .txt y se interpolará linealmente entre cada par de puntos (*piecewise interpolation*)", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# Reading the data\ndata = np.loadtxt('data_points.txt', comments='#', delimiter=',')\nx = data[:,0]\nf = data[:,1]\n\nplt.figure()\nplt.scatter(x,f)\nplt.xlabel(r'$x$')\nplt.ylabel(r'$f(x)$')\nplt.show()", "_____no_output_____" ], [ "data.shape", "_____no_output_____" ], [ "def linearInterpolation(x1, x2, f1, f2, x):\n p1 = f1 + ((f2-f1)/(x2-x1))*(x-x1)\n return p1\n \nN = len(x)\n\nplt.figure(figsize=(7,5))\nplt.scatter(x, f, color='black')\n\nfor i in range(N-1):\n x_interval = np.linspace(x[i],x[i+1],3) \n # Note that the number 3 in thie above line indeicates the number of \n # points interpolated in each interval !\n # (including the extreme points of the interval)\n y_interval = linearInterpolation(x[i], x[i+1], f[i], f[i+1], x_interval)\n plt.plot(x_interval, y_interval,'r')\n \nplt.title(r'Linear Piecewise Interpolation')\nplt.xlabel(r'$x$')\nplt.ylabel(r'$p_1(x)$')\nplt.show()", "_____no_output_____" ] ], [ [ "---\n### Interpolación Cuadrática\n\nLa interpolación cuadrática ($n=2$) requiere información de tres puntos.\n\nPor ejemplo, se pueden tomar los tres puntos $x_i$ , $x_{i+1}$ y $x_{i+2}$ para interpolar la función $f(x)$ en el rango$[x_{i},x_{i+1}]$. Al solucionar el sistema de ecuaciones lineales correspondiente se obtiene el polinomio\n\n$p_2(x) = \\frac{(x-x_{i+1})(x-x_{i+2})}{(x_i - x_{i+1})(x_i - x_{i+2})} f(x_i)\n+ \\frac{(x-x_{i})(x-x_{i+2})}{(x_{i+1} - x_{i})(x_{i+1} - x_{i+2})} f(x_{i+1}) \n+ \\frac{(x-x_i)(x-x_{i+1})}{(x_{i+2} - x_i)(x_{i+2} - x_{i+1})} f(x_{i+2}) + \\mathcal{O}(\\Delta x^3)$,\n\ndonde $\\Delta x = \\max \\{ x_{i+2}-x_{i+1},x_{i+1}-x_i \\}$. \n\nEn este caso, el polinomio interpolado se puede derivar dos veces pero, aunque su primera derivada es continua, la segunda derivada no es continua en los puntos extremos del intervalo.", "_____no_output_____" ], [ "#### Ejemplo. Interpolación Cuadrática por Intervalos\n\nA continuación se leerá un conjunto de datos desde un archivo .txt y se interpolará cuadráticamente en sub-intervalos (*quadratic piecewise interpolation*)", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Reading the data\ndata = np.loadtxt('data_points.txt', comments='#', delimiter=',')\nx = data[:,0]\nf = data[:,1]\n\ndef quadraticInterpolation(x1, x2, x3, f1, f2, f3, x):\n p2 = (((x-x2)*(x-x3))/((x1-x2)*(x1-x3)))*f1 +\\\n (((x-x1)*(x-x3))/((x2-x1)*(x2-x3)))*f2 +\\\n (((x-x1)*(x-x2))/((x3-x1)*(x3-x2)))*f3\n return p2\n \nN = len(x)\n\nplt.figure(figsize=(7,5))\nplt.scatter(x, f, color='black')\n\nfor i in range(N-2):\n x_interval = np.linspace(x[i],x[i+1],6) # 6 interpolate points in each interval\n y_interval = quadraticInterpolation(x[i], x[i+1], x[i+2], f[i], f[i+1], f[i+2], x_interval)\n plt.plot(x_interval, y_interval,'r')\n\nplt.title(r' Quadratic Polynomial Piecewise Interpolation')\nplt.xlabel(r'$x$')\nplt.ylabel(r'$p_2(x)$')\nplt.show()", "_____no_output_____" ] ], [ [ "**Nota:** Por la forma de realizar la interpolación cuadrática, el último intervalo queda sin información. En esta región se puede extender la interpolación del penúltimo intervalo o también se puede interpolar un polinomio lineal. ", "_____no_output_____" ], [ "---\n## Interpolación de Lagrange \n\nLa **Interpolación de Lagrange Interpolation** también busca un polinomio de grado $n$ utilizando $n+1$ puntos, pero utiliza un método alternativo de encontrar los coeficientes. Para comprender esta idea, re-escribimos el polinomio lineal encontrado antes en la forma\n\n\\begin{equation} \np_1(x) = \\frac{x-x_{i+1}}{x_i - x_{i+1}} f(x_i) + \\frac{x-x_i}{x_{i+1}-x_i} f(x_{i+1}) + \\mathcal{O}(\\Delta x^2),\n\\end{equation} \n\no así,\n\n\\begin{equation} \np_1(x) = \\sum_{j=i}^{i+1} f(x_j) L_{1j}(x) + \\mathcal{O}(\\Delta x^2) \n\\end{equation}\n\ndonde se han introducido los *coeficientes de Lagrange*\n\n\\begin{equation} \nL_{1j}(x) = \\frac{x-x_k}{x_j-x_k}\\bigg|_{k\\ne j}.\n\\end{equation} \n\nNótese que estos coeficientes aseguran que el polinomio pasa por los puntos conocidos, i.e. $p_1(x_i) = f(x_i)$ y $p_1(x_{i+1}) = f(x_{i+1})$\n\nLa **interpolación de Lagrange** generaliza estas expresiones para un polinomio de grado $n$ que pasa por los $n+1$ puntos conocidos,\n\n\\begin{equation}\np_n (x) = \\sum_{j=0}^{n} f(x_j) L_{nj}(x) + \\mathcal{O}(\\Delta x^{n+1})\\,, \\label{eq:LagrangeInterpolation}\n\\end{equation}\n\ndonde los coeficientes de Lagrange se generalizan a \n\n\\begin{equation}\nL_{nj}(x) = \\prod_{k\\ne j}^{n} \\frac{x-x_k}{x_j - x_k}\\,.\n\\end{equation}\n\nDe nuevo, es posible notar que estos coeficientes aseguran que el polinomio pasa por los puntos concidos $p(x_j) = f(x_j)$.", "_____no_output_____" ] ], [ [ "# %load lagrangeInterpolation\n'''\nEduard Larrañaga\nComputational Astrophysics \n2020\n\nLagrange Interpolation Method\n'''\n\nimport numpy as np\n\n#Lagrange Coefficients\ndef L(x, xi, j):\n\t'''\n\t------------------------------------------\n\tL(x, xi, j)\n\t------------------------------------------\n Returns the Lagrange coefficient for the \n interpolation evaluated at points x\n Receives as arguments:\n x : array of points where the interpolated\n polynomial will be evaluated\n xi : array of N data points \n j : index of the coefficient to be \n calculated\n\t------------------------------------------\n\t'''\n\t# Number of points\n\tN = len(xi) \n\n\tprod = 1\n\tfor k in range(N):\n\t\tif (k != j):\n\t\t\tprod = prod * (x - xi[k])/(xi[j] - xi[k])\n\treturn prod\n\n\n\n\n\n# Interpolated Polynomial\ndef p(x, xi, fi):\n\t'''\n\t------------------------------------------\n p(x, xi, fi)\n ------------------------------------------\n Returns the values of the Lagrange \n interpolated polynomial in a set of points\n defined by x\n x : array of points where the interpolated\n polynomial will be evaluated\n xi : array of N data points points\n fi : values of the function to be \n interpolated\n ------------------------------------------\n\t'''\n\t# Number of points\n\tN = len(xi)\n\n\tsumm = 0\n\tfor j in range(N):\n\t\tsumm = summ + fi[j]*L(x, xi, j)\n\treturn summ\n", "_____no_output_____" ], [ "import numpy as np\nimport matplotlib.pyplot as plt\n#import lagrangeInterpolation as lagi\nimport sys\n\n# Reading the data\ndata = np.loadtxt('data_points.txt', comments='#', delimiter=',')\nx = data[:,0]\nf = data[:,1]\n \nN = len(x)\n\n# Degree of the polynomial to be interpolated piecewise\nn = 3\n\n# Check if the number of point is enough to interpolate such a polynomial\nif n>=N:\n print('\\nThere are not enough points to interpolate this polynomial.')\n print(f'Using {N:.0f} points it is possible to interpolate polynomials up to order n={N-1:.0f}')\n sys.exit()\n\n \nplt.figure(figsize=(7,5))\nplt.title(f'Lagrange Polynomial Piecewise Interpolation n={n:.0f}')\nplt.scatter(x, f, color='black')\n\n# Piecewise Interpolation Loop\nfor i in range(N-n):\n xi = x[i:i+n+1]\n fi = f[i:i+n+1]\n x_interval = np.linspace(x[i],x[i+1],3*n)\n y_interval = p(x_interval,xi,fi)\n plt.plot(x_interval, y_interval,'r')\n\nplt.xlabel(r'$x$')\nplt.ylabel(r'$p_n(x)$')\nplt.show()", "_____no_output_____" ] ], [ [ "Nótese que los últimos $n$ puntos no estan interpolados. Qué se puede hacer?", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\n#import lagrangeInterpolation as lagi\nimport sys\n\n# Reading the data\ndata = np.loadtxt('data_points.txt', comments='#', delimiter=',')\nx = data[:,0]\nf = data[:,1]\n \nN = len(x)\n\n# Degree of the polynomial to be interpolated piecewise\nn = 6\n\n# Check if the number of point is enough to interpolate such a polynomial\nif n>=N:\n print('\\nThere are not enough points to interpolate this polynomial.')\n print(f'Using {N:.0f} points it is possible to interpolate polynomials up to order n={N-1:.0f}')\n sys.exit()\n\n \nplt.figure(figsize=(7,5))\nplt.title(f'Lagrange Polynomial Piecewise Interpolation n={n:.0f}')\nplt.scatter(x, f, color='black')\n\n# Piecewise Interpolation Loop\nfor i in range(N-n):\n xi = x[i:i+n+1]\n fi = f[i:i+n+1]\n x_interval = np.linspace(x[i],x[i+1],3*n)\n y_interval = p(x_interval,xi,fi)\n plt.plot(x_interval, y_interval,'r')\n\n# Piecewise Interpolation for the final N-n points, \n# using a lower degree polynomial\nwhile n>1:\n m = n-1\n for i in range(N-n,N-m):\n xi = x[i:i+m+1]\n fi = f[i:i+m+1]\n x_interval = np.linspace(x[i],x[i+1],3*m)\n y_interval = p(x_interval,xi,fi)\n plt.plot(x_interval, y_interval,'r')\n n=n-1\n\n\nplt.xlabel(r'$x$')\nplt.ylabel(r'$p_n(x)$')\nplt.show()", "_____no_output_____" ] ], [ [ "### Fenómeno de Runge\n\nPor qué se se interpola por sub-intervalos? Cuando se tiene una gran cantidad de puntos conocidos, es posible interpolar un polinomio de grado alto. Sin embargo, el comportamiento del polinomio interpolado puede no ser el esperado (especialmente en los extremos del intervalo de interpolación) debido a la existencia de oscilaciones no controladas. A este comportamiento se le denomina el fenómeno de Runge.\n\nPor ejemplo, para un conjunto de datos con $20$ puntos es posible interpolar un polinomio de orden $n=19$,", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport lagrangeInterpolation as lagi\nimport sys\n\n# Reading the data\ndata = np.loadtxt('data_points.txt', comments='#', delimiter=',')\nx = data[:,0]\nf = data[:,1]\n \nN = len(x)\n\n# Higher Degree polynomial to be interpolated \nn = N-1\n\nplt.figure(figsize=(7,5))\nplt.title(f'Lagrange Polynomial Piecewise Interpolation n={n:.0f}')\nplt.scatter(x, f, color='black')\n\n#Interpolation of the higher degree polynomial\nx_int = np.linspace(x[0],x[N-1],3*n)\ny_int = lagi.p(x_int,x,f)\nplt.plot(x_int, y_int,'r')\n\nplt.xlabel(r'$x$')\nplt.ylabel(r'$p_n(x)$')\nplt.show()", "_____no_output_____" ] ], [ [ "Sin embargo, es claro que el comportamiento del polinomio interpolado no es bueno en los extremos del intervalo considerado. Por esta razón, es muy aconsejable utilizar una interpolación de polinomios de grado pequeño por sub-intervalos.", "_____no_output_____" ], [ "---\n## Interpolación Cúbica de Hermite por Intervalos\n\nLa interpolación de Hermite es unc aso particular de interpolación polinomica que utiliza un conjunto de puntos conocidos en donde se conoce el valor de la función $f(x_j)$ y su derivada $f'(x_j)$. Al incorporar la primera derivada se pueden interpolar polinomios de un grado alto controlando las osiclaciones no deseadas. Adicionalmente, al conocer la primera derivada, se necesitan menos puntos para realizar la interpolación.\n\nDentro de este tipo de interpolación, la más utilizada es la de polinomios de tercer orden. DE esta forma, en un intervalo $[x_i , x_{i+1}]$, se requiere conocer (o evaluar) los valores de $f(x_i)$, $f(x_{i+1})$, $f'(x_i)$ y $f'(x_{i+1})$ para obtener el polinomio interpolado de Hermite cúbico,\n\n\\begin{equation}\nH_3(x) = f(x_i)\\psi_0(z) + f(x_{i+1})\\psi_0(1-z)+ f'(x_i)(x_{i+1} - x_{i})\\psi_1(z) - f'(x_{i+1})(x_{i+1}-x_i)\\psi_1 (1-z),\n\\end{equation}\n\ndonde \n\n\\begin{equation}\nz = \\frac{x-x_i}{x_{i+1}-x_i}\n\\end{equation}\n\ny\n\n\\begin{align}\n\\psi_0(z) =&2z^3 - 3z^2 + 1 \\\\\n\\psi_1(z) =&z^3-2z^2+z\\,\\,.\n\\end{align}\n\nNótese que con esta formulación, es posible interpolar un polinomio de tercer orden en un intervalo con solo dos puntos. De esta forma, al trabajar con un conjunto de muhos puntos, se podría interpolar un polinomio cúbico entre cada par de datos, incluso en el último sub-intervalo!", "_____no_output_____" ] ], [ [ "# %load HermiteInterpolation\n'''\nEduard Larrañaga\nComputational Astrophysics \n2020\n\nHermite Interpolation Method\n'''\n\nimport numpy as np\n\n#Hermite Coefficients\ndef psi0(z):\n\t'''\n\t------------------------------------------\n\tpsi0(z)\n\t------------------------------------------\n\tReturns the Hermite coefficients Psi_0\n\tfor the interpolation\n\tReceives as arguments: z\n\t------------------------------------------\n\t'''\n\tpsi_0 = 2*z**3 - 3*z**2 + 1\n\treturn psi_0\n\ndef psi1(z):\n\t'''\n\t------------------------------------------\n\tpsi1(z)\n\t------------------------------------------\n\tReturns the Hermite coefficients Psi_1 for \n\tthe interpolation\n\tReceives as arguments: z\n\t------------------------------------------\n\t'''\n\tpsi_1 = z**3 - 2*z**2 + z\n\treturn psi_1\n\n\n# Interpolated Polynomial\ndef H3(x, xi, fi, dfidx):\n\t'''\n\t------------------------------------------\n H3(x, xi, fi, dfidx)\n ------------------------------------------\n Returns the values of the Cubic Hermite \n interpolated polynomial in a set of points\n defined by x\n x : array of points where the interpolated\n polynomial will be evaluated\n xi : array of 2 data points \n fi : array of values of the function at xi\n dfidx : array of values of the derivative \n of the function at xi\n ------------------------------------------\n\t'''\n\t# variable z in the interpolation\n\tz = (x - xi[0])/(xi[1] - x[0])\n\t\n\th1 = psi0(z) * fi[0]\n\th2 = psi0(1-z)*fi[1]\n\th3 = psi1(z)*(xi[1] - xi[0])*dfidx[0]\n\th4 = psi1(1-z)*(xi[1] - xi[0])*dfidx[1]\n\tH = h1 + h2 + h3 - h4\n\treturn H\n", "_____no_output_____" ], [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport HermiteInterpolation as heri\n\ndef Derivative(x, f):\n '''\n ------------------------------------------\n Derivative(x, f)\n ------------------------------------------\n This function returns the numerical \n derivative of a discretely-sample function \n using one-side derivatives in the extreme \n points of the interval and second order \n accurate derivative in the middle points.\n The data points may be evenly or unevenly\n spaced.\n ------------------------------------------\n '''\n # Number of points\n N = len(x)\n dfdx = np.zeros([N, 2])\n dfdx[:,0] = x\n \n # Derivative at the extreme points\n dfdx[0,1] = (f[1] - f[0])/(x[1] - x[0])\n dfdx[N-1,1] = (f[N-1] - f[N-2])/(x[N-1] - x[N-2])\n \n #Derivative at the middle points\n for i in range(1,N-1):\n h1 = x[i] - x[i-1]\n h2 = x[i+1] - x[i]\n dfdx[i,1] = h1*f[i+1]/(h2*(h1+h2)) - (h1-h2)*f[i]/(h1*h2) -\\\n h2*f[i-1]/(h1*(h1+h2))\n \n return dfdx\n\n# Loading the data\ndata = np.loadtxt('data_points.txt', comments='#', delimiter=',')\nx = data[:,0]\nf = data[:,1]\nN = len(x)\n\n# Calling the derivative function and chosing only the second column\ndfdx = Derivative(x,f)[:,1]\n\nplt.figure(figsize=(7,5))\nplt.title(f'Cubic Hermite Polynomial Piecewise Interpolation')\nplt.scatter(x, f, color='black')\n\n# Piecewise Hermite Interpolation Loop\nfor i in range(N-1):\n xi = x[i:i+2]\n fi = f[i:i+2]\n dfidx = dfdx[i:i+2]\n x_interval = np.linspace(x[i],x[i+1],4)\n y_interval = heri.H3(x_interval, xi, fi, dfidx)\n plt.plot(x_interval, y_interval,'r')\n\nplt.xlabel(r'$x$')\nplt.ylabel(r'$H_3(x)$')\nplt.show()\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
cb67c520dd2ccb586e25e8a000a56a63cb576826
100,289
ipynb
Jupyter Notebook
Time Series.ipynb
dattscience/Analysis-of-Data
fc9ee6c369f05fe964b7f676db9598149ccda27f
[ "MIT" ]
null
null
null
Time Series.ipynb
dattscience/Analysis-of-Data
fc9ee6c369f05fe964b7f676db9598149ccda27f
[ "MIT" ]
null
null
null
Time Series.ipynb
dattscience/Analysis-of-Data
fc9ee6c369f05fe964b7f676db9598149ccda27f
[ "MIT" ]
null
null
null
100,289
100,289
0.838586
[ [ [ "# Time series on the stock market", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\ndf = pd.read_csv(\"datosdebolsa.csv\")", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df.dtypes", "_____no_output_____" ], [ "df.Date = pd.to_datetime(df.Date)\ndf.index = df.Date", "_____no_output_____" ], [ "df.head(10)", "_____no_output_____" ], [ "df = df.set_index('Date').asfreq('d')\ndf.head(10)", "_____no_output_____" ], [ "df = df.fillna(method=\"ffill\")\ndf.head(10)", "_____no_output_____" ], [ "df = df[\"2016-06\":\"2018-06\"]", "_____no_output_____" ], [ "\nplt.figure(figsize=(9,5))\nplt.plot(df.Close);", "_____no_output_____" ] ], [ [ "# Making future predictions\n\n\n\n\n", "_____no_output_____" ] ], [ [ "import seaborn as sns\nimport numpy as np\ntest_size = 60\nwindow_size = 3", "_____no_output_____" ], [ "df_shift = df.Close.shift(1)\ndf_mean_roll = df_shift.rolling(window_size).mean()\ndf_std_roll = df_shift.rolling(window_size).std()\ndf_mean_roll.name = \"mean_roll\"\ndf_std_roll.name = \"std_roll\"\ndf_mean_roll.index = df.index\ndf_std_roll.index = df.index", "_____no_output_____" ], [ "df_shift.head(),df_mean_roll.head(),df_std_roll.head()", "_____no_output_____" ], [ "df_w = pd.concat([df.Close,df_mean_roll,df_std_roll],axis=1)\ndf_w.head(10)", "_____no_output_____" ], [ "df_w = df_w[window_size:]\ndf_w.head()", "_____no_output_____" ], [ "test = df_w[-test_size:]\ntrain = df_w[:-test_size]\nX_test = test.drop(\"Close\",axis = 1)\ny_test = test[\"Close\"]\nX_train = train.drop(\"Close\",axis = 1)\ny_train = train[\"Close\"]", "_____no_output_____" ], [ "from sklearn.svm import SVR\nclf = SVR(gamma=\"scale\")\nclf.fit(X_train, y_train)\ny_train_hat = pd.Series(clf.predict(X_train),index=y_train.index)\ny_test_hat = pd.Series(clf.predict(X_test),index=y_test.index)", "_____no_output_____" ], [ "plt.figure(figsize=(9,5))\nplt.plot(y_train ,label='Training')\nplt.plot(y_test_hat,label='Test_Prediction')\nplt.plot(y_test , label='Test_Real')\nplt.legend(loc='best')\nplt.title('Rolling Mean & Standard Deviation');", "_____no_output_____" ], [ "from sklearn.metrics import mean_squared_error\nmse = mean_squared_error(y_test, y_test_hat)\nprint('MSE: {}'.format(mse))", "MSE: 0.025163154752358315\n" ], [ "clf.predict(X_train[0:1])", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "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" ] ]
cb67d193353bae49ad2e91a6e080e26833b3c186
31,918
ipynb
Jupyter Notebook
Feature_Engineering/6] Target Encoding/target-encoding.ipynb
nan645/Kaggle_ML_Course
e4b3f6f04a62c123de035c86c59718e58d4eb7ca
[ "Apache-2.0" ]
null
null
null
Feature_Engineering/6] Target Encoding/target-encoding.ipynb
nan645/Kaggle_ML_Course
e4b3f6f04a62c123de035c86c59718e58d4eb7ca
[ "Apache-2.0" ]
null
null
null
Feature_Engineering/6] Target Encoding/target-encoding.ipynb
nan645/Kaggle_ML_Course
e4b3f6f04a62c123de035c86c59718e58d4eb7ca
[ "Apache-2.0" ]
null
null
null
31,918
31,918
0.861833
[ [ [ "# Introduction #\n\nMost of the techniques we've seen in this course have been for numerical features. The technique we'll look at in this lesson, *target encoding*, is instead meant for categorical features. It's a method of encoding categories as numbers, like one-hot or label encoding, with the difference that it also uses the *target* to create the encoding. This makes it what we call a **supervised** feature engineering technique.", "_____no_output_____" ] ], [ [ "\nimport pandas as pd\n\nautos = pd.read_csv(\"../input/fe-course-data/autos.csv\")", "_____no_output_____" ] ], [ [ "# Target Encoding #\n\nA **target encoding** is any kind of encoding that replaces a feature's categories with some number derived from the target.\n\nA simple and effective version is to apply a group aggregation from Lesson 3, like the mean. Using the *Automobiles* dataset, this computes the average price of each vehicle's make:", "_____no_output_____" ] ], [ [ "autos[\"make_encoded\"] = autos.groupby(\"make\")[\"price\"].transform(\"mean\")\n\nautos[[\"make\", \"price\", \"make_encoded\"]].head(10)", "_____no_output_____" ] ], [ [ "This kind of target encoding is sometimes called a **mean encoding**. Applied to a binary target, it's also called **bin counting**. (Other names you might come across include: likelihood encoding, impact encoding, and leave-one-out encoding.)\n\n# Smoothing #\n\nAn encoding like this presents a couple of problems, however. First are *unknown categories*. Target encodings create a special risk of overfitting, which means they need to be trained on an independent \"encoding\" split. When you join the encoding to future splits, Pandas will fill in missing values for any categories not present in the encoding split. These missing values you would have to impute somehow.\n\nSecond are *rare categories*. When a category only occurs a few times in the dataset, any statistics calculated on its group are unlikely to be very accurate. In the *Automobiles* dataset, the `mercurcy` make only occurs once. The \"mean\" price we calculated is just the price of that one vehicle, which might not be very representative of any Mercuries we might see in the future. Target encoding rare categories can make overfitting more likely.\n\nA solution to these problems is to add **smoothing**. The idea is to blend the *in-category* average with the *overall* average. Rare categories get less weight on their category average, while missing categories just get the overall average.\n\nIn pseudocode:\n```\nencoding = weight * in_category + (1 - weight) * overall\n```\nwhere `weight` is a value between 0 and 1 calculated from the category frequency.\n\nAn easy way to determine the value for `weight` is to compute an **m-estimate**:\n```\nweight = n / (n + m)\n```\nwhere `n` is the total number of times that category occurs in the data. The parameter `m` determines the \"smoothing factor\". Larger values of `m` put more weight on the overall estimate.\n\n<figure style=\"padding: 1em;\">\n<img src=\"https://i.imgur.com/1uVtQEz.png\" width=500, alt=\"\">\n<figcaption style=\"textalign: center; font-style: italic\"><center>\n</center></figcaption>\n</figure>\n\nIn the *Automobiles* dataset there are three cars with the make `chevrolet`. If you chose `m=2.0`, then the `chevrolet` category would be encoded with 60% of the average Chevrolet price plus 40% of the overall average price.\n```\nchevrolet = 0.6 * 6000.00 + 0.4 * 13285.03\n```\n\nWhen choosing a value for `m`, consider how noisy you expect the categories to be. Does the price of a vehicle vary a great deal within each make? Would you need a lot of data to get good estimates? If so, it could be better to choose a larger value for `m`; if the average price for each make were relatively stable, a smaller value could be okay.\n\n<blockquote style=\"margin-right:auto; margin-left:auto; background-color: #ebf9ff; padding: 1em; margin:24px;\">\n<strong>Use Cases for Target Encoding</strong><br>\nTarget encoding is great for:\n<ul>\n<li><strong>High-cardinality features</strong>: A feature with a large number of categories can be troublesome to encode: a one-hot encoding would generate too many features and alternatives, like a label encoding, might not be appropriate for that feature. A target encoding derives numbers for the categories using the feature's most important property: its relationship with the target.\n<li><strong>Domain-motivated features</strong>: From prior experience, you might suspect that a categorical feature should be important even if it scored poorly with a feature metric. A target encoding can help reveal a feature's true informativeness.\n</ul>\n</blockquote>\n\n# Example - MovieLens1M #\n\nThe [*MovieLens1M*](https://www.kaggle.com/grouplens/movielens-20m-dataset) dataset contains one-million movie ratings by users of the MovieLens website, with features describing each user and movie. This hidden cell sets everything up:", "_____no_output_____" ] ], [ [ "\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport warnings\n\nplt.style.use(\"seaborn-whitegrid\")\nplt.rc(\"figure\", autolayout=True)\nplt.rc(\n \"axes\",\n labelweight=\"bold\",\n labelsize=\"large\",\n titleweight=\"bold\",\n titlesize=14,\n titlepad=10,\n)\nwarnings.filterwarnings('ignore')\n\n\ndf = pd.read_csv(\"../input/fe-course-data/movielens1m.csv\")\ndf = df.astype(np.uint8, errors='ignore') # reduce memory footprint\nprint(\"Number of Unique Zipcodes: {}\".format(df[\"Zipcode\"].nunique()))", "Number of Unique Zipcodes: 3439\n" ] ], [ [ "With over 3000 categories, the `Zipcode` feature makes a good candidate for target encoding, and the size of this dataset (over one-million rows) means we can spare some data to create the encoding.\n\nWe'll start by creating a 25% split to train the target encoder.", "_____no_output_____" ] ], [ [ "X = df.copy()\ny = X.pop('Rating')\n\nX_encode = X.sample(frac=0.25)\ny_encode = y[X_encode.index]\nX_pretrain = X.drop(X_encode.index)\ny_train = y[X_pretrain.index]", "_____no_output_____" ] ], [ [ "The `category_encoders` package in `scikit-learn-contrib` implements an m-estimate encoder, which we'll use to encode our `Zipcode` feature.", "_____no_output_____" ] ], [ [ "from category_encoders import MEstimateEncoder\n\n# Create the encoder instance. Choose m to control noise.\nencoder = MEstimateEncoder(cols=[\"Zipcode\"], m=5.0)\n\n# Fit the encoder on the encoding split.\nencoder.fit(X_encode, y_encode)\n\n# Encode the Zipcode column to create the final training data\nX_train = encoder.transform(X_pretrain)", "_____no_output_____" ] ], [ [ "Let's compare the encoded values to the target to see how informative our encoding might be.", "_____no_output_____" ] ], [ [ "plt.figure(dpi=90)\nax = sns.distplot(y, kde=False, norm_hist=True)\nax = sns.kdeplot(X_train.Zipcode, color='r', ax=ax)\nax.set_xlabel(\"Rating\")\nax.legend(labels=['Zipcode', 'Rating']);", "_____no_output_____" ] ], [ [ "The distribution of the encoded `Zipcode` feature roughly follows the distribution of the actual ratings, meaning that movie-watchers differed enough in their ratings from zipcode to zipcode that our target encoding was able to capture useful information.\n\n# Your Turn #\n\n[**Apply target encoding**](https://www.kaggle.com/kernels/fork/14393917) to features in *Ames* and investigate a surprising way that target encoding can lead to overfitting.", "_____no_output_____" ], [ "---\n\n\n\n\n*Have questions or comments? Visit the [Learn Discussion forum](https://www.kaggle.com/learn-forum/221677) to chat with other Learners.*", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cb67d4241276946f93c49e669c37108988ad258f
24,480
ipynb
Jupyter Notebook
AzureML-OpenVINO/AML-BYOC-ONNXRUNTIME-OpenVINO.ipynb
xlegend1024/onnxruntime-iot-edge
9fc76b7dabf70ad4144e6f1d567689a2965adb30
[ "MIT" ]
59
2019-08-15T01:31:16.000Z
2021-12-16T22:27:27.000Z
AzureML-OpenVINO/AML-BYOC-ONNXRUNTIME-OpenVINO.ipynb
xlegend1024/onnxruntime-iot-edge
9fc76b7dabf70ad4144e6f1d567689a2965adb30
[ "MIT" ]
10
2019-08-22T18:46:31.000Z
2022-02-01T04:45:01.000Z
AzureML-OpenVINO/AML-BYOC-ONNXRUNTIME-OpenVINO.ipynb
wmpauli/onnxruntime-iot-edge
4d0ec8d6728eaa69d45cfa68442badd0a90dedd0
[ "MIT" ]
28
2019-08-15T00:49:13.000Z
2021-08-02T15:44:00.000Z
32.295515
259
0.558415
[ [ [ "## Deploy an ONNX model to an IoT Edge device using ONNX Runtime and the Azure Machine Learning ", "_____no_output_____" ], [ "![End-to-end pipeline with ONNX Runtime](https://github.com/manashgoswami/byoc/raw/master/ONNXRuntime-AML.png)", "_____no_output_____" ] ], [ [ "!python -m pip install --upgrade pip", "_____no_output_____" ], [ "!pip install azureml-core azureml-contrib-iot azure-mgmt-containerregistry azure-cli\n!az extension add --name azure-cli-iot-ext", "_____no_output_____" ], [ "import os\nprint(os.__file__)", "_____no_output_____" ], [ "# Check core SDK version number\nimport azureml.core as azcore\n\nprint(\"SDK version:\", azcore.VERSION)", "_____no_output_____" ] ], [ [ "## 1. Setup the Azure Machine Learning Environment", "_____no_output_____" ], [ "### 1a AML Workspace : using existing config", "_____no_output_____" ] ], [ [ "#Initialize Workspace \nfrom azureml.core import Workspace\n\nws = Workspace.from_config()", "_____no_output_____" ] ], [ [ "### 1.2 AML Workspace : create a new workspace", "_____no_output_____" ] ], [ [ "#Initialize Workspace \nfrom azureml.core import Workspace\n\n### Change this cell from markdown to code and run this if you need to create a workspace \n### Update the values for your workspace below\nws=Workspace.create(subscription_id=\"<subscription-id goes here>\",\n resource_group=\"<resource group goes here>\",\n name=\"<name of the AML workspace>\",\n location=\"<location>\")\n \nws.write_config()", "_____no_output_____" ] ], [ [ "### 1.3 AML Workspace : initialize an existing workspace\nDownload the `config.json` file for your AML Workspace from the Azure portal", "_____no_output_____" ] ], [ [ "#Initialize Workspace \nfrom azureml.core import Workspace\n\n## existing AML Workspace in config.json\nws = Workspace.from_config('config.json')", "_____no_output_____" ], [ "print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')", "_____no_output_____" ] ], [ [ "## 2. Setup the trained model to use in this example", "_____no_output_____" ], [ "### 2.1 Register the trained model in workspace from the ONNX Model Zoo", "_____no_output_____" ] ], [ [ "import urllib.request\nonnx_model_url = \"https://onnxzoo.blob.core.windows.net/models/opset_8/tiny_yolov2/tiny_yolov2.tar.gz\"\nurllib.request.urlretrieve(onnx_model_url, filename=\"tiny_yolov2.tar.gz\")\n!tar xvzf tiny_yolov2.tar.gz", "_____no_output_____" ], [ "from azureml.core.model import Model\n\nmodel = Model.register(workspace = ws, \n model_path = \"./tiny_yolov2/Model.onnx\",\n model_name = \"Model.onnx\",\n tags = {\"data\": \"Imagenet\", \"model\": \"object_detection\", \"type\": \"TinyYolo\"},\n description = \"real-time object detection model from ONNX model zoo\")", "_____no_output_____" ] ], [ [ "### 2.2 Load the model from your workspace model registry\nFor e.g. this could be the ONNX model exported from your training experiment", "_____no_output_____" ] ], [ [ "from azureml.core.model import Model\nmodel = Model(name='Model.onnx', workspace=ws)", "_____no_output_____" ] ], [ [ "## 3. Create the application container image\nThis container is the IoT Edge module that will be deployed on the UP<sup>2</sup> device. \n 1. This container is using a pre-build base image for ONNX Runtime.\n 2. Includes a `score.py` script, Must include a `run()` and `init()` function. The `init()` is entrypoint that reads the camera frames from /device/video0. The `run()` function is a dummy module to satisfy AML-sdk checks.\n 3. `amlpackage_inference.py` script which is used to process the input frame and run the inference session and\n 4. the ONNX model, label file used by the ONNX Runtime", "_____no_output_____" ] ], [ [ "%%writefile score.py\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for\n# full license information.\n\n\nimport sys\nimport time\nimport io\nimport csv\n\n\n# Imports for inferencing\nimport onnxruntime as rt\nfrom amlpackage_inference import run_onnx\nimport numpy as np\nimport cv2\n\n# Imports for communication w/IOT Hub\nfrom iothub_client import IoTHubModuleClient, IoTHubClientError, IoTHubTransportProvider\nfrom iothub_client import IoTHubMessage, IoTHubMessageDispositionResult, IoTHubError\nfrom azureml.core.model import Model\n\n# Imports for the http server\nfrom flask import Flask, request\nimport json\n\n# Imports for storage\nimport os\n# from azure.storage.blob import BlockBlobService, PublicAccess, AppendBlobService\nimport random\nimport string\nimport csv\nfrom datetime import datetime\nfrom pytz import timezone \nimport time\nimport json\n\nclass HubManager(object):\n def __init__(\n self,\n protocol=IoTHubTransportProvider.MQTT):\n self.client_protocol = protocol\n self.client = IoTHubModuleClient()\n self.client.create_from_environment(protocol)\n\n # set the time until a message times out\n self.client.set_option(\"messageTimeout\", MESSAGE_TIMEOUT)\n\n # Forwards the message received onto the next stage in the process.\n def forward_event_to_output(self, outputQueueName, event, send_context):\n self.client.send_event_async(\n outputQueueName, event, send_confirmation_callback, send_context)\n\n\n\ndef send_confirmation_callback(message, result, user_context):\n \"\"\"\n Callback received when the message that we're forwarding is processed.\n \"\"\"\n print(\"Confirmation[%d] received for message with result = %s\" % (user_context, result))\n\n\ndef get_tinyyolo_frame_from_encode(msg):\n \"\"\"\n Formats jpeg encoded msg to frame that can be processed by tiny_yolov2\n \"\"\"\n #inp = np.array(msg).reshape((len(msg),1))\n #frame = cv2.imdecode(inp.astype(np.uint8), 1)\n frame = cv2.cvtColor(msg, cv2.COLOR_BGR2RGB)\n \n # resize and pad to keep input frame aspect ratio\n h, w = frame.shape[:2]\n tw = 416 if w > h else int(np.round(416.0 * w / h))\n th = 416 if h > w else int(np.round(416.0 * h / w))\n frame = cv2.resize(frame, (tw, th))\n pad_value=114\n top = int(max(0, np.round((416.0 - th) / 2)))\n left = int(max(0, np.round((416.0 - tw) / 2)))\n bottom = 416 - top - th\n right = 416 - left - tw\n frame = cv2.copyMakeBorder(frame, top, bottom, left, right,\n cv2.BORDER_CONSTANT, value=[pad_value, pad_value, pad_value])\n \n frame = np.ascontiguousarray(np.array(frame, dtype=np.float32).transpose(2, 0, 1)) # HWC -> CHW\n frame = np.expand_dims(frame, axis=0)\n return frame\n\ndef run(msg):\n # this is a dummy function required to satisfy AML-SDK requirements.\n return msg\n\ndef init():\n # Choose HTTP, AMQP or MQTT as transport protocol. Currently only MQTT is supported.\n PROTOCOL = IoTHubTransportProvider.MQTT\n DEVICE = 0 # when device is /dev/video0\n LABEL_FILE = \"labels.txt\"\n MODEL_FILE = \"Model.onnx\"\n global MESSAGE_TIMEOUT # setting for IoT Hub Manager\n MESSAGE_TIMEOUT = 1000\n LOCAL_DISPLAY = \"OFF\" # flag for local display on/off, default OFF\n\n \n # Create the IoT Hub Manager to send message to IoT Hub\n print(\"trying to make IOT Hub manager\")\n \n hub_manager = HubManager(PROTOCOL)\n\n if not hub_manager:\n print(\"Took too long to make hub_manager, exiting program.\")\n print(\"Try restarting IotEdge or this module.\")\n sys.exit(1)\n\n # Get Labels from labels file \n labels_file = open(LABEL_FILE)\n labels_string = labels_file.read()\n labels = labels_string.split(\",\")\n labels_file.close()\n label_lookup = {}\n for i, val in enumerate(labels):\n label_lookup[val] = i\n\n # get model path from within the container image\n model_path=Model.get_model_path(MODEL_FILE)\n \n # Loading ONNX model\n\n print(\"loading model to ONNX Runtime...\")\n start_time = time.time()\n ort_session = rt.InferenceSession(model_path)\n print(\"loaded after\", time.time()-start_time,\"s\")\n\n # start reading frames from video endpoint\n \n cap = cv2.VideoCapture(DEVICE)\n\n while cap.isOpened():\n _, _ = cap.read()\n ret, img_frame = cap.read() \n if not ret:\n print('no video RESETTING FRAMES TO 0 TO RUN IN LOOP')\n cap.set(cv2.CAP_PROP_POS_FRAMES, 0)\n continue\n \n \"\"\" \n Handles incoming inference calls for each fames. Gets frame from request and calls inferencing function on frame.\n Sends result to IOT Hub.\n \"\"\"\n try:\n \n draw_frame = img_frame\n start_time = time.time()\n # pre-process the frame to flatten, scale for tiny-yolo\n \n frame = get_tinyyolo_frame_from_encode(img_frame)\n \n # run the inference session for the given input frame\n objects = run_onnx(frame, ort_session, draw_frame, labels, LOCAL_DISPLAY)\n \n # LOOK AT OBJECTS AND CHECK PREVIOUS STATUS TO APPEND\n num_objects = len(objects) \n print(\"NUMBER OBJECTS DETECTED:\", num_objects) \n print(\"PROCESSED IN:\",time.time()-start_time,\"s\") \n if num_objects > 0:\n output_IOT = IoTHubMessage(json.dumps(objects))\n hub_manager.forward_event_to_output(\"inferenceoutput\", output_IOT, 0)\n continue\n except Exception as e:\n print('EXCEPTION:', str(e))\n continue", "_____no_output_____" ] ], [ [ "### 3.1 Include the dependent packages required by the application scripts", "_____no_output_____" ] ], [ [ "from azureml.core.conda_dependencies import CondaDependencies\n\nmyenv = CondaDependencies()\nmyenv.add_pip_package(\"azure-iothub-device-client\")\nmyenv.add_pip_package(\"numpy\")\nmyenv.add_pip_package(\"opencv-python\")\nmyenv.add_pip_package(\"requests\")\nmyenv.add_pip_package(\"pytz\")\nmyenv.add_pip_package(\"onnx\")\n\nwith open(\"myenv.yml\", \"w\") as f:\n f.write(myenv.serialize_to_string())", "_____no_output_____" ] ], [ [ "### 3.2 Build the custom container image with the ONNX Runtime + OpenVINO base image\nThis step uses pre-built container images with ONNX Runtime and the different HW execution providers. A complete list of base images are located [here](https://github.com/microsoft/onnxruntime/tree/master/dockerfiles#docker-containers-for-onnx-runtime).", "_____no_output_____" ] ], [ [ "from azureml.core.image import ContainerImage\nfrom azureml.core.model import Model\n\nopenvino_image_config = ContainerImage.image_configuration(execution_script = \"score.py\",\n runtime = \"python\",\n dependencies=[\"labels.txt\", \"amlpackage_inference.py\"],\n conda_file = \"myenv.yml\",\n description = \"TinyYolo ONNX Runtime inference container\",\n tags = {\"demo\": \"onnx\"})\n\n# Use the ONNX Runtime + OpenVINO base image for Intel MovidiusTM USB sticks\nopenvino_image_config.base_image = \"mcr.microsoft.com/azureml/onnxruntime:latest-openvino-myriad\" \n\n# For the Intel Movidius VAD-M PCIe card use this:\n# openvino_image_config.base_image = \"mcr.microsoft.com/azureml/onnxruntime:latest-openvino-vadm\"\n\nopenvino_image = ContainerImage.create(name = \"name-of-image\",\n # this is the model object\n models = [model],\n image_config = openvino_image_config,\n workspace = ws)\n\n# Alternative: Re-use an image that you have already built from the workspace image registry\n# openvino_image = ContainerImage(name = \"<name-of-image>\", workspace = ws)\n\nopenvino_image.wait_for_creation(show_output = True)\nif openvino_image.creation_state == 'Failed':\n print(\"Image build log at: \" + openvino_image.image_build_log_uri)", "_____no_output_____" ], [ "if openvino_image.creation_state != 'Failed':\n print(\"Image URI at: \" +openvino_image.image_location)", "_____no_output_____" ] ], [ [ "## 4. Deploy to the UP<sup>2</sup> device using Azure IoT Edge", "_____no_output_____" ], [ "### 4.1 Login with the Azure subscription to provision the IoT Hub and the IoT Edge device", "_____no_output_____" ] ], [ [ "!az login \n!az account set --subscription $ws.subscription_id \n", "_____no_output_____" ], [ "# confirm the account\n!az account show", "_____no_output_____" ] ], [ [ "### 4.2 Specify the IoT Edge device details", "_____no_output_____" ] ], [ [ "# Parameter list to configure the IoT Hub and the IoT Edge device\n\n# Pick a name for what you want to call the module you deploy to the camera\nmodule_name = \"module-name-here\"\n\n# Resource group in Azure \nresource_group_name= ws.resource_group\niot_rg=resource_group_name\n\n# Azure region where your services will be provisioned\niot_location=\"location-here\"\n\n# Azure IoT Hub name\niot_hub_name=\"name-of-IoT-Hub\"\n\n# Pick a name for your camera\niot_device_id=\"name-of-IoT-Edge-device\"\n\n# Pick a name for the deployment configuration\niot_deployment_id=\"Infernce Module from AML\"", "_____no_output_____" ] ], [ [ "### 4.2a Optional: Provision the IoT Hub, create the IoT Edge device and Setup the Intel UP<sup>2</sup> AI Vision Developer Kit", "_____no_output_____" ] ], [ [ "!az iot hub create --resource-group $resource_group_name --name $iot_hub_name --sku S1", "_____no_output_____" ], [ "# Register an IoT Edge device (create a new entry in the Iot Hub)\n!az iot hub device-identity create --hub-name $iot_hub_name --device-id $iot_device_id --edge-enabled", "_____no_output_____" ], [ "!az iot hub device-identity show-connection-string --hub-name $iot_hub_name --device-id $iot_device_id ", "_____no_output_____" ] ], [ [ "The following steps need to be executed in the device terminal\n\n1. Open the IoT edge configuration file in UP<sup>2</sup> device to update the IoT Edge device *connection string*\n \n `sudo nano /etc/iotedge/config.yaml`\n \n provisioning:\n source: \"manual\"\n device_connection_string: \"<ADD DEVICE CONNECTION STRING HERE>\"\n\n2. To update the DPS TPM provisioning configuration:\n\n provisioning:\n source: \"dps\"\n global_endpoint: \"https://global.azure-devices-provisioning.net\"\n scope_id: \"{scope_id}\"\n attestation:\n method: \"tpm\"\n registration_id: \"{registration_id}\"\n\n3. Save and close the file. `CTRL + X, Y, Enter\n\n \n4. After entering the privisioning information in the configuration file, restart the *iotedge* daemon\n \n `sudo systemctl restart iotedge`\n \n \n5. We will show the object detection results from the camera connected (`/dev/video0`) to the UP<sup>2</sup> on the display. Update your .profile file:\n \n `nano ~/.profile`\n \n add the following line to the end of file\n\n __xhost +__", "_____no_output_____" ], [ "### 4.3 Construct the deployment file", "_____no_output_____" ] ], [ [ "# create the registry uri\ncontainer_reg = ws.get_details()[\"containerRegistry\"]\nreg_name=container_reg.split(\"/\")[-1]\ncontainer_url = \"\\\"\" + openvino_image.image_location + \"\\\",\"\nsubscription_id = ws.subscription_id\nprint('{}'.format(openvino_image.image_location), \"<-- this is the URI configured in the IoT Hub for the device\")\nprint('{}'.format(reg_name))\nprint('{}'.format(subscription_id))", "_____no_output_____" ], [ "from azure.mgmt.containerregistry import ContainerRegistryManagementClient\nfrom azure.mgmt import containerregistry\nclient = ContainerRegistryManagementClient(ws._auth,subscription_id)\nresult= client.registries.list_credentials(resource_group_name, reg_name, custom_headers=None, raw=False)\nusername = result.username\npassword = result.passwords[0].value", "_____no_output_____" ] ], [ [ "#### Create the `deplpyment.json` with the AML image registry details\nWe have provided here a sample deployment template this reference implementation.", "_____no_output_____" ] ], [ [ "file = open('./AML-deployment.template.json')\ncontents = file.read()\ncontents = contents.replace('__AML_MODULE_NAME', module_name)\ncontents = contents.replace('__AML_REGISTRY_NAME', reg_name)\ncontents = contents.replace('__AML_REGISTRY_USER_NAME', username)\ncontents = contents.replace('__AML_REGISTRY_PASSWORD', password)\ncontents = contents.replace('__AML_REGISTRY_IMAGE_LOCATION', openvino_image.image_location)\nwith open('./deployment.json', 'wt', encoding='utf-8') as output_file:\n output_file.write(contents)", "_____no_output_____" ] ], [ [ "### 4.4 Push the *deployment* to the IoT Edge device", "_____no_output_____" ] ], [ [ "print(\"Pushing deployment to IoT Edge device\")", "_____no_output_____" ], [ "print (\"Set the deployement\") \n!az iot edge set-modules --device-id $iot_device_id --hub-name $iot_hub_name --content deployment.json", "_____no_output_____" ] ], [ [ "### 4.5 Monitor IoT Hub Messages", "_____no_output_____" ] ], [ [ "!az iot hub monitor-events --hub-name $iot_hub_name -y", "_____no_output_____" ] ], [ [ "## 5. CLEANUP", "_____no_output_____" ] ], [ [ "!rm score.py deployment.json myenv.yml", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb67d74a3a07a1a11f552e924e43ff58b9e5dabc
212,466
ipynb
Jupyter Notebook
notebooks/Dublin_ED_maps.ipynb
stephenrigney/CIG_2016
eacb1a10752d2679cd97713bbf10d52a035f7fbf
[ "MIT" ]
null
null
null
notebooks/Dublin_ED_maps.ipynb
stephenrigney/CIG_2016
eacb1a10752d2679cd97713bbf10d52a035f7fbf
[ "MIT" ]
null
null
null
notebooks/Dublin_ED_maps.ipynb
stephenrigney/CIG_2016
eacb1a10752d2679cd97713bbf10d52a035f7fbf
[ "MIT" ]
null
null
null
196.182825
72,034
0.861286
[ [ [ "% matplotlib inline\n\nimport json, re\nimport fiona\nfrom shapely.geometry import MultiPolygon, shape\n\nimport pandas as pd\nimport geopandas as gp\nimport numpy as np\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom matplotlib.collections import PatchCollection\nfrom matplotlib.colors import Normalize\n\nfrom mpl_toolkits.basemap import Basemap\n\nfrom descartes import PolygonPatch\n\nfrom datetime import datetime\nfrom dateutil.parser import parse\n\nfrom pysal.esda.mapclassify import Natural_Breaks as nb\nfrom itertools import chain", "_____no_output_____" ], [ "matplotlib.style.use('ggplot')", "_____no_output_____" ] ], [ [ "#### Create Dublin Electoral Division basemap from CSO boundary files (already converted to geojson)", "_____no_output_____" ] ], [ [ "with open(\"../data/raw/dublin_ed.geojson\", \"r\") as f:\n dub = json.load(f)", "_____no_output_____" ], [ "# Creating new geojson for geometries and basic id info\n# Including Ward names to incorporate 1961 data\ndub2 = {'type':dub['type'], 'crs': dub['crs'], 'features': []}\nfor feat in dub['features']:\n prop = feat\n prop['properties'] = {\"ed\": feat['properties']['EDNAME'],\n \"geogid\": feat['properties']['GEOGID'],\n \"osied\": feat['properties']['OSIED'],\n \"ward\": re.sub(\"\\s[A-Z]$\", \"\", feat['properties']['EDNAME'])}\n dub2['features'].append(prop)\n\nwith open(\"../data/processed/dublin_ed_base.geojson\", \"w\") as f:\n json.dump(dub2, f, indent=2, sort_keys=True)", "_____no_output_____" ], [ "#Create Geopandas data frame from dublin data\ndub_gp = gp.GeoDataFrame.from_file(\"../data/processed/dublin_ed_base.geojson\")\ndub_gp.set_index(\"geogid\")\ndub_gp.geometry.total_bounds", "_____no_output_____" ], [ "dub_gp.plot(legend=True)", "_____no_output_____" ], [ "#Import census tenure data into dataframe\nwith open(\"../data/interim/ten_71_81_91_02_11.json\", \"r\") as f:\n tenure = json.load(f)\nten_df = pd.DataFrame.from_dict(data)", "_____no_output_____" ], [ "ten_df[ten_df['year']==1971].describe()", "_____no_output_____" ], [ "for t in tenure:\n t['year'] = str(t['year'])\n\ndub_df = pd.DataFrame.from_dict(sorted(({k:t[k] for k in t if k in ['area', 'geogid', \"year\"] or k.endswith(\"units\")}\n for t in tenure if t['geogid'] == \"C02\"), key=lambda x: x['year']))\n\ndub_df.set_index(\"year\")\ndub_df.loc[dub_df['owner_occ_units'].isnull(), 'owner_occ_units'] = dub_df['owner_mortg_units']+dub_df['owner_no_mortg_units']\ndub_df.loc[dub_df['private_rent_units'].isnull(), 'private_rent_units'] = dub_df['rent_furn_units']+dub_df['rent_unfurn_units']\n", "_____no_output_____" ], [ "ax = plt.figure(figsize=(7,4), dpi=300).add_subplot(111)\ndub_df.plot(ax=ax, x=\"year\", y=['rent_furn_units', 'rent_unfurn_units', \"private_rent_units\"])", "_____no_output_____" ], [ "#bx = plt.figure(figsize=(7,4), dpi=300).add_subplot(111)\ndub_df.plot(x=\"year\", y=['owner_occ_units', 'owner_mortg_units', \"owner_no_mortg_units\", \"private_rent_units\"])", "_____no_output_____" ], [ "dub71 = pd.DataFrame.from_dict({k:t[k] for k in t if k in ['area', 'geogid', \"year\"] or k.endswith(\"units\")}\n for t in tenure if t['geogid'] and t['geogid'].startswith(\"E\") and t['year'] == \"2002\")\ndub71.set_index(\"geogid\")\ndub71.describe()", "_____no_output_____" ], [ "bds = dub_gp.total_bounds\nextra = 0.01\nll = (bds[0], bds[1])\nur = (bds[2], bds[3])\ncoords = list(chain(ll, ur))\nw, h = coords[2] - coords[0], coords[3] - coords[1]\nw, h = coords[2] - coords[0], coords[3] - coords[1]\nextra = 0.01", "_____no_output_____" ], [ "?Basemap.readshapefile", "_____no_output_____" ], [ "m = Basemap(\n projection='tmerc',\n lon_0=-2.,\n lat_0=49.,\n ellps = 'WGS84',\n llcrnrlon=coords[0] - extra * w,\n llcrnrlat=coords[1] - extra + 0.01 * h,\n urcrnrlon=coords[2] + extra * w,\n urcrnrlat=coords[3] + extra + 0.01 * h,\n lat_ts=0,\n resolution='i',\n suppress_ticks=True)\nm.readshapefile(\n '../data/external/census2011DED/Census2011_Electoral_Divisions_generalised20m',\n 'Dublin City',\n color='none',\n zorder=2)", "_____no_output_____" ], [ "# Calculate Jenks natural breaks for density\nbreaks = nb(\n dub71[dub71['rent_furn_units'].notnull()].rent_unfurn_units.values,\n initial=300,\n k=5)\n# the notnull method lets us match indices when joining\njb = pd.DataFrame({'jenks_bins': breaks.yb}, index=dub71[dub71['rent_furn_units'].notnull()].index)\ndub71 = dub71.join(jb)\ndub71.jenks_bins.fillna(-1, inplace=True)\n\njenks_labels = [\"<= %0.f units (%s EDs)\" % (b, c) for b, c in zip(\n breaks.bins, breaks.counts)]\n#jenks_labels.insert(0, 'No plaques (%s wards)' % len(df_map[df_map['density_km'].isnull()]))\njenks_labels", "_____no_output_____" ], [ "#fig = plt.figure(figsize=(20,15), dpi=300)#.add_subplot(111)\nplt.clf()\nfig = plt.figure()\n\nax = fig.add_subplot(111, axisbg='w', frame_on=False)\n\n# use a blue colour ramp - we'll be converting it to a map using cmap()\ncmap = plt.get_cmap('Blues')\n# draw wards with grey outlines\npatches = []\n\nd71 = pd.merge(dub_gp,dub71)\nd71['patches'] = d71.geometry.map(lambda x: PolygonPatch(x, ec='#555555', lw=.2, alpha=1., zorder=4))\npc = PatchCollection(d71['patches'], match_original=True)\n# impose our colour map onto the patch collection\nnorm = Normalize()\npc.set_facecolor(cmap(norm(d71['jenks_bins'].values)))\nax.add_collection(pc)\n\nd71.plot(column=\"jenks_bins\", colormap=\"Blues\", \n categorical=True, \n alpha=1.0, \n \n )\n# Add a colour bar\ncb = colorbar_index(ncolors=len(jenks_labels), cmap=cmap, shrink=0.5, labels=jenks_labels)\ncb.ax.tick_params(labelsize=10)\n\n# this will set the image width to 722px at 100dpi\nplt.tight_layout()\nfig.set_size_inches(12,8)\n#plt.savefig('data/london_plaques.png', dpi=100, alpha=True)\nplt.show()", "_____no_output_____" ], [ "# Convenience functions for working with colour ramps and bars\ndef colorbar_index(ncolors, cmap, labels=None, **kwargs):\n \"\"\"\n This is a convenience function to stop you making off-by-one errors\n Takes a standard colour ramp, and discretizes it,\n then draws a colour bar with correctly aligned labels\n \"\"\"\n cmap = cmap_discretize(cmap, ncolors)\n mappable = cm.ScalarMappable(cmap=cmap)\n mappable.set_array([])\n mappable.set_clim(-0.5, ncolors+0.5)\n colorbar = plt.colorbar(mappable, **kwargs)\n colorbar.set_ticks(np.linspace(0, ncolors, ncolors))\n colorbar.set_ticklabels(range(ncolors))\n if labels:\n colorbar.set_ticklabels(labels)\n return colorbar\n\ndef cmap_discretize(cmap, N):\n \"\"\"\n Return a discrete colormap from the continuous colormap cmap.\n\n cmap: colormap instance, eg. cm.jet. \n N: number of colors.\n\n Example\n x = resize(arange(100), (5,100))\n djet = cmap_discretize(cm.jet, 5)\n imshow(x, cmap=djet)\n\n \"\"\"\n if type(cmap) == str:\n cmap = get_cmap(cmap)\n colors_i = np.concatenate((np.linspace(0, 1., N), (0., 0., 0., 0.)))\n colors_rgba = cmap(colors_i)\n indices = np.linspace(0, 1., N + 1)\n cdict = {}\n for ki, key in enumerate(('red', 'green', 'blue')):\n cdict[key] = [(indices[i], colors_rgba[i - 1, ki], colors_rgba[i, ki]) for i in range(N + 1)]\n return matplotlib.colors.LinearSegmentedColormap(cmap.name + \"_%d\" % N, cdict, 1024)", "_____no_output_____" ], [ "[(t['geogid'], t['area'], t['year']) for t in tenure if t['geogid'] == \"E02146\"]", "_____no_output_____" ], [ "dub_gp['geometry'].iloc[6:8].values", "_____no_output_____" ], [ "ax.collections", "_____no_output_____" ] ] ]
[ "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" ] ]
cb67e38fe498094f590ce69fba65068dd090dbe8
9,317
ipynb
Jupyter Notebook
lesson4.ipynb
TigranShirinyan/econometrics2022
1ac106a2604b21cb365144bd7ba3ed8b1668a089
[ "MIT" ]
null
null
null
lesson4.ipynb
TigranShirinyan/econometrics2022
1ac106a2604b21cb365144bd7ba3ed8b1668a089
[ "MIT" ]
null
null
null
lesson4.ipynb
TigranShirinyan/econometrics2022
1ac106a2604b21cb365144bd7ba3ed8b1668a089
[ "MIT" ]
null
null
null
16.848101
79
0.41816
[ [ [ "import numpy as np\n", "_____no_output_____" ], [ "arr1= np.array([[1,3,4]])", "_____no_output_____" ], [ "arr1.shape", "_____no_output_____" ], [ "arr1.dtype", "_____no_output_____" ], [ "arr1.ndim", "_____no_output_____" ], [ "arr2 = np.arange(1,10)\narr2", "_____no_output_____" ], [ "arr2 *2", "_____no_output_____" ], [ "arr2.mean()", "_____no_output_____" ], [ "arr2.sum()", "_____no_output_____" ], [ "arr2.std()", "_____no_output_____" ], [ "arr2 > 5", "_____no_output_____" ], [ "arr3 = np.arange(1,15)\narr3", "_____no_output_____" ], [ "arr3.ndim", "_____no_output_____" ], [ "arr3.shape", "_____no_output_____" ], [ "arr3.std()", "_____no_output_____" ], [ "arr3_sqrt = np.sqrt(arr3.std())\narr3_sqrt", "_____no_output_____" ], [ "arr3[(arr3 > 6)]", "_____no_output_____" ], [ "matrix1 = np.array([(1,2),(3,4),(5,6),(7,8),(9,10),(11,12)])\nmatrix2 = np.array([(1,2,3,4),(5,6,7,8),(9,10,11,12)])\nmatrix1\n", "_____no_output_____" ], [ "matrix2", "_____no_output_____" ], [ "matrix1[(matrix1 > 5)]", "_____no_output_____" ], [ "matrix2[(matrix2>5)]", "_____no_output_____" ], [ "matrix1[:,1]", "_____no_output_____" ], [ "matrix1[1,1]", "_____no_output_____" ], [ "matrix2[0,:]", "_____no_output_____" ], [ "matrix2[2,3]", "_____no_output_____" ], [ "np.insert(matrix1, 2 , (5,4) , axis = 0)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb67e7c13c275042eb2a293e33435a09597bb9be
37,247
ipynb
Jupyter Notebook
notebook/curricularface-efficientnet-b3-margin-0.9.ipynb
jingxuanyang/Shopee-Product-Matching
703087a6bbb87340766bee5ccd38a7ffbdab0b06
[ "MIT" ]
13
2021-05-28T12:49:03.000Z
2022-03-15T19:38:03.000Z
notebook/curricularface-efficientnet-b3-margin-0.9.ipynb
jingxuanyang/Shopee-Product-Matching
703087a6bbb87340766bee5ccd38a7ffbdab0b06
[ "MIT" ]
2
2021-12-20T08:36:08.000Z
2021-12-21T12:44:56.000Z
notebook/curricularface-efficientnet-b3-margin-0.9.ipynb
jingxuanyang/Shopee-Product-Matching
703087a6bbb87340766bee5ccd38a7ffbdab0b06
[ "MIT" ]
4
2021-07-31T14:54:48.000Z
2021-12-16T14:27:18.000Z
37,247
37,247
0.658415
[ [ [ "# About this kernel \n\n+ efficientnet_b3\n+ CurricularFace\n+ Mish() activation\n+ Ranger (RAdam + Lookahead) optimizer\n+ margin = 0.9", "_____no_output_____" ], [ "## Imports", "_____no_output_____" ] ], [ [ "import sys\n\nsys.path.append('../input/shopee-competition-utils')\nsys.path.insert(0,'../input/pytorch-image-models')", "_____no_output_____" ], [ "import numpy as np \nimport pandas as pd \n\nimport torch \nfrom torch import nn \nfrom torch.utils.data import Dataset, DataLoader \n\nimport albumentations\nfrom albumentations.pytorch.transforms import ToTensorV2\n\nfrom custom_scheduler import ShopeeScheduler\nfrom custom_activation import replace_activations, Mish\nfrom custom_optimizer import Ranger\n\nimport math \nimport cv2\nimport timm \nimport os\nimport random\nimport gc\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import GroupKFold\nfrom sklearn.neighbors import NearestNeighbors\nfrom tqdm.notebook import tqdm ", "_____no_output_____" ] ], [ [ "## Config", "_____no_output_____" ] ], [ [ "class CFG: \n \n DATA_DIR = '../input/shopee-product-matching/train_images'\n TRAIN_CSV = '../input/shopee-product-matching/train.csv'\n\n # data augmentation\n IMG_SIZE = 512\n MEAN = [0.485, 0.456, 0.406]\n STD = [0.229, 0.224, 0.225]\n\n SEED = 2021\n\n # data split\n N_SPLITS = 5\n TEST_FOLD = 0\n VALID_FOLD = 1\n\n EPOCHS = 8\n BATCH_SIZE = 8\n\n NUM_WORKERS = 4\n DEVICE = 'cuda:0'\n\n CLASSES = 6609 \n SCALE = 30\n MARGIN = 0.9\n\n MODEL_NAME = 'efficientnet_b3'\n MODEL_PATH = f'{MODEL_NAME}_curricular_face_epoch_{EPOCHS}_bs_{BATCH_SIZE}_margin_{MARGIN}.pt'\n FC_DIM = 512\n SCHEDULER_PARAMS = {\n \"lr_start\": 1e-5,\n \"lr_max\": 1e-5 * 32,\n \"lr_min\": 1e-6,\n \"lr_ramp_ep\": 5,\n \"lr_sus_ep\": 0,\n \"lr_decay\": 0.8,\n }", "_____no_output_____" ] ], [ [ "## Augmentations", "_____no_output_____" ] ], [ [ "def get_train_transforms():\n return albumentations.Compose(\n [ \n albumentations.Resize(CFG.IMG_SIZE,CFG.IMG_SIZE,always_apply=True),\n albumentations.HorizontalFlip(p=0.5),\n albumentations.VerticalFlip(p=0.5),\n albumentations.Rotate(limit=120, p=0.8),\n albumentations.RandomBrightness(limit=(0.09, 0.6), p=0.5),\n albumentations.Normalize(mean=CFG.MEAN, std=CFG.STD),\n ToTensorV2(p=1.0),\n ]\n )\n\ndef get_valid_transforms():\n\n return albumentations.Compose(\n [\n albumentations.Resize(CFG.IMG_SIZE,CFG.IMG_SIZE,always_apply=True),\n albumentations.Normalize(mean=CFG.MEAN, std=CFG.STD),\n ToTensorV2(p=1.0)\n ]\n )\n\ndef get_test_transforms():\n\n return albumentations.Compose(\n [\n albumentations.Resize(CFG.IMG_SIZE,CFG.IMG_SIZE,always_apply=True),\n albumentations.Normalize(mean=CFG.MEAN, std=CFG.STD),\n ToTensorV2(p=1.0)\n ]\n )", "_____no_output_____" ] ], [ [ "## Reproducibility", "_____no_output_____" ] ], [ [ "def seed_everything(seed):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = True # set True to be faster\n\nseed_everything(CFG.SEED)", "_____no_output_____" ] ], [ [ "## Dataset ", "_____no_output_____" ] ], [ [ "class ShopeeDataset(torch.utils.data.Dataset):\n \"\"\"for training\n \"\"\"\n def __init__(self,df, transform = None):\n self.df = df \n self.root_dir = CFG.DATA_DIR\n self.transform = transform\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self,idx):\n\n row = self.df.iloc[idx]\n\n img_path = os.path.join(self.root_dir,row.image)\n image = cv2.imread(img_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n label = row.label_group\n\n if self.transform:\n augmented = self.transform(image=image)\n image = augmented['image']\n\n return {\n 'image' : image,\n 'label' : torch.tensor(label).long()\n }", "_____no_output_____" ], [ "class ShopeeImageDataset(torch.utils.data.Dataset):\n \"\"\"for validating and test\n \"\"\"\n def __init__(self,df, transform = None):\n self.df = df \n self.root_dir = CFG.DATA_DIR\n self.transform = transform\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self,idx):\n\n row = self.df.iloc[idx]\n\n img_path = os.path.join(self.root_dir,row.image)\n image = cv2.imread(img_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n label = row.label_group\n\n if self.transform:\n augmented = self.transform(image=image)\n image = augmented['image'] \n \n return image,torch.tensor(1)", "_____no_output_____" ] ], [ [ "## Curricular Face + NFNet-L0", "_____no_output_____" ] ], [ [ "'''\ncredit : https://github.com/HuangYG123/CurricularFace/blob/8b2f47318117995aa05490c05b455b113489917e/head/metrics.py#L70\n'''\n\ndef l2_norm(input, axis = 1):\n norm = torch.norm(input, 2, axis, True)\n output = torch.div(input, norm)\n\n return output\n\nclass CurricularFace(nn.Module):\n def __init__(self, in_features, out_features, s = 30, m = 0.50):\n super(CurricularFace, self).__init__()\n\n print('Using Curricular Face')\n\n self.in_features = in_features\n self.out_features = out_features\n self.m = m\n self.s = s\n self.cos_m = math.cos(m)\n self.sin_m = math.sin(m)\n self.threshold = math.cos(math.pi - m)\n self.mm = math.sin(math.pi - m) * m\n self.kernel = nn.Parameter(torch.Tensor(in_features, out_features))\n self.register_buffer('t', torch.zeros(1))\n nn.init.normal_(self.kernel, std=0.01)\n\n def forward(self, embbedings, label):\n embbedings = l2_norm(embbedings, axis = 1)\n kernel_norm = l2_norm(self.kernel, axis = 0)\n cos_theta = torch.mm(embbedings, kernel_norm)\n cos_theta = cos_theta.clamp(-1, 1) # for numerical stability\n with torch.no_grad():\n origin_cos = cos_theta.clone()\n target_logit = cos_theta[torch.arange(0, embbedings.size(0)), label].view(-1, 1)\n\n sin_theta = torch.sqrt(1.0 - torch.pow(target_logit, 2))\n cos_theta_m = target_logit * self.cos_m - sin_theta * self.sin_m #cos(target+margin)\n mask = cos_theta > cos_theta_m\n final_target_logit = torch.where(target_logit > self.threshold, cos_theta_m, target_logit - self.mm)\n\n hard_example = cos_theta[mask]\n with torch.no_grad():\n self.t = target_logit.mean() * 0.01 + (1 - 0.01) * self.t\n cos_theta[mask] = hard_example * (self.t + hard_example)\n cos_theta.scatter_(1, label.view(-1, 1).long(), final_target_logit)\n output = cos_theta * self.s\n return output, nn.CrossEntropyLoss()(output,label)", "_____no_output_____" ], [ "class ShopeeModel(nn.Module):\n\n def __init__(\n self,\n n_classes = CFG.CLASSES,\n model_name = CFG.MODEL_NAME,\n fc_dim = CFG.FC_DIM,\n margin = CFG.MARGIN,\n scale = CFG.SCALE,\n use_fc = True,\n pretrained = True):\n\n\n super(ShopeeModel,self).__init__()\n print('Building Model Backbone for {} model'.format(model_name))\n\n self.backbone = timm.create_model(model_name, pretrained=pretrained)\n\n if 'efficientnet' in model_name:\n final_in_features = self.backbone.classifier.in_features\n self.backbone.classifier = nn.Identity()\n self.backbone.global_pool = nn.Identity()\n \n elif 'resnet' in model_name:\n final_in_features = self.backbone.fc.in_features\n self.backbone.fc = nn.Identity()\n self.backbone.global_pool = nn.Identity()\n\n elif 'resnext' in model_name:\n final_in_features = self.backbone.fc.in_features\n self.backbone.fc = nn.Identity()\n self.backbone.global_pool = nn.Identity()\n\n elif 'nfnet' in model_name:\n final_in_features = self.backbone.head.fc.in_features\n self.backbone.head.fc = nn.Identity()\n self.backbone.head.global_pool = nn.Identity()\n\n self.pooling = nn.AdaptiveAvgPool2d(1)\n\n self.use_fc = use_fc\n\n if use_fc:\n self.dropout = nn.Dropout(p=0.0)\n self.fc = nn.Linear(final_in_features, fc_dim)\n self.bn = nn.BatchNorm1d(fc_dim)\n self._init_params()\n final_in_features = fc_dim\n\n self.final = CurricularFace(final_in_features, \n n_classes, \n s=scale, \n m=margin)\n\n def _init_params(self):\n nn.init.xavier_normal_(self.fc.weight)\n nn.init.constant_(self.fc.bias, 0)\n nn.init.constant_(self.bn.weight, 1)\n nn.init.constant_(self.bn.bias, 0)\n\n def forward(self, image, label):\n feature = self.extract_feat(image)\n logits = self.final(feature,label)\n return logits\n\n def extract_feat(self, x):\n batch_size = x.shape[0]\n x = self.backbone(x)\n x = self.pooling(x).view(batch_size, -1)\n\n if self.use_fc:\n x = self.dropout(x)\n x = self.fc(x)\n x = self.bn(x)\n return x\n", "_____no_output_____" ] ], [ [ "## Engine", "_____no_output_____" ] ], [ [ "def train_fn(model, data_loader, optimizer, scheduler, i):\n model.train()\n fin_loss = 0.0\n tk = tqdm(data_loader, desc = \"Epoch\" + \" [TRAIN] \" + str(i+1))\n\n for t,data in enumerate(tk):\n for k,v in data.items():\n data[k] = v.to(CFG.DEVICE)\n optimizer.zero_grad()\n _, loss = model(**data)\n loss.backward()\n optimizer.step() \n fin_loss += loss.item() \n\n tk.set_postfix({'loss' : '%.6f' %float(fin_loss/(t+1)), 'LR' : optimizer.param_groups[0]['lr']})\n\n scheduler.step()\n\n return fin_loss / len(data_loader)\n\ndef eval_fn(model, data_loader, i):\n model.eval()\n fin_loss = 0.0\n tk = tqdm(data_loader, desc = \"Epoch\" + \" [VALID] \" + str(i+1))\n\n with torch.no_grad():\n for t,data in enumerate(tk):\n for k,v in data.items():\n data[k] = v.to(CFG.DEVICE)\n _, loss = model(**data)\n fin_loss += loss.item() \n\n tk.set_postfix({'loss' : '%.6f' %float(fin_loss/(t+1))})\n return fin_loss / len(data_loader)", "_____no_output_____" ], [ "def read_dataset():\n df = pd.read_csv(CFG.TRAIN_CSV)\n df['matches'] = df.label_group.map(df.groupby('label_group').posting_id.agg('unique').to_dict())\n df['matches'] = df['matches'].apply(lambda x: ' '.join(x))\n\n gkf = GroupKFold(n_splits=CFG.N_SPLITS)\n df['fold'] = -1\n for i, (train_idx, valid_idx) in enumerate(gkf.split(X=df, groups=df['label_group'])):\n df.loc[valid_idx, 'fold'] = i\n\n labelencoder= LabelEncoder()\n df['label_group'] = labelencoder.fit_transform(df['label_group'])\n\n train_df = df[df['fold']!=CFG.TEST_FOLD].reset_index(drop=True)\n train_df = train_df[train_df['fold']!=CFG.VALID_FOLD].reset_index(drop=True)\n valid_df = df[df['fold']==CFG.VALID_FOLD].reset_index(drop=True)\n test_df = df[df['fold']==CFG.TEST_FOLD].reset_index(drop=True)\n\n train_df['label_group'] = labelencoder.fit_transform(train_df['label_group'])\n\n return train_df, valid_df, test_df", "_____no_output_____" ], [ "def precision_score(y_true, y_pred):\n y_true = y_true.apply(lambda x: set(x.split()))\n y_pred = y_pred.apply(lambda x: set(x.split()))\n intersection = np.array([len(x[0] & x[1]) for x in zip(y_true, y_pred)])\n len_y_pred = y_pred.apply(lambda x: len(x)).values\n precision = intersection / len_y_pred\n return precision\n\ndef recall_score(y_true, y_pred):\n y_true = y_true.apply(lambda x: set(x.split()))\n y_pred = y_pred.apply(lambda x: set(x.split()))\n intersection = np.array([len(x[0] & x[1]) for x in zip(y_true, y_pred)])\n len_y_true = y_true.apply(lambda x: len(x)).values\n recall = intersection / len_y_true\n return recall\n\ndef f1_score(y_true, y_pred):\n y_true = y_true.apply(lambda x: set(x.split()))\n y_pred = y_pred.apply(lambda x: set(x.split()))\n intersection = np.array([len(x[0] & x[1]) for x in zip(y_true, y_pred)])\n len_y_pred = y_pred.apply(lambda x: len(x)).values\n len_y_true = y_true.apply(lambda x: len(x)).values\n f1 = 2 * intersection / (len_y_pred + len_y_true)\n return f1", "_____no_output_____" ], [ "def get_valid_embeddings(df, model):\n\n model.eval()\n\n image_dataset = ShopeeImageDataset(df,transform=get_valid_transforms())\n image_loader = torch.utils.data.DataLoader(\n image_dataset,\n batch_size=CFG.BATCH_SIZE,\n pin_memory=True,\n num_workers = CFG.NUM_WORKERS,\n drop_last=False\n )\n\n embeds = []\n with torch.no_grad():\n for img,label in tqdm(image_loader): \n img = img.to(CFG.DEVICE)\n label = label.to(CFG.DEVICE)\n feat,_ = model(img,label)\n image_embeddings = feat.detach().cpu().numpy()\n embeds.append(image_embeddings)\n \n del model\n image_embeddings = np.concatenate(embeds)\n print(f'Our image embeddings shape is {image_embeddings.shape}')\n del embeds\n gc.collect()\n return image_embeddings", "_____no_output_____" ], [ "def get_valid_neighbors(df, embeddings, KNN = 50, threshold = 0.36):\n\n model = NearestNeighbors(n_neighbors = KNN, metric = 'cosine')\n model.fit(embeddings)\n distances, indices = model.kneighbors(embeddings)\n\n predictions = []\n for k in range(embeddings.shape[0]):\n idx = np.where(distances[k,] < threshold)[0]\n ids = indices[k,idx]\n posting_ids = ' '.join(df['posting_id'].iloc[ids].values)\n predictions.append(posting_ids)\n \n df['pred_matches'] = predictions\n df['f1'] = f1_score(df['matches'], df['pred_matches'])\n df['recall'] = recall_score(df['matches'], df['pred_matches'])\n df['precision'] = precision_score(df['matches'], df['pred_matches'])\n \n del model, distances, indices\n gc.collect()\n return df, predictions", "_____no_output_____" ] ], [ [ "# Training ", "_____no_output_____" ] ], [ [ "def run_training():\n train_df, valid_df, test_df = read_dataset()\n train_dataset = ShopeeDataset(train_df, transform = get_train_transforms())\n\n train_dataloader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size = CFG.BATCH_SIZE,\n pin_memory = True,\n num_workers = CFG.NUM_WORKERS,\n shuffle = True,\n drop_last = True\n )\n\n print(train_df['label_group'].nunique())\n\n model = ShopeeModel()\n model = replace_activations(model, torch.nn.SiLU, Mish())\n model.to(CFG.DEVICE)\n\n optimizer = Ranger(model.parameters(), lr = CFG.SCHEDULER_PARAMS['lr_start'])\n #optimizer = torch.optim.Adam(model.parameters(), lr = config.SCHEDULER_PARAMS['lr_start'])\n scheduler = ShopeeScheduler(optimizer,**CFG.SCHEDULER_PARAMS)\n\n best_valid_f1 = 0.\n for i in range(CFG.EPOCHS):\n avg_loss_train = train_fn(model, train_dataloader, optimizer, scheduler, i)\n\n valid_embeddings = get_valid_embeddings(valid_df, model)\n valid_df, valid_predictions = get_valid_neighbors(valid_df, valid_embeddings)\n\n valid_f1 = valid_df.f1.mean()\n valid_recall = valid_df.recall.mean()\n valid_precision = valid_df.precision.mean()\n print(f'Valid f1 score = {valid_f1}, recall = {valid_recall}, precision = {valid_precision}')\n\n if valid_f1 > best_valid_f1:\n best_valid_f1 = valid_f1\n print('Valid f1 score improved, model saved')\n torch.save(model.state_dict(),CFG.MODEL_PATH)\n \nrun_training()", "6609\nBuilding Model Backbone for efficientnet_b3 model\nUsing Curricular Face\nRanger optimizer loaded. \nGradient Centralization usage = True\nGC applied to both conv and fc layers\n" ] ], [ [ "## Best threshold Search", "_____no_output_____" ] ], [ [ "train_df, valid_df, test_df = read_dataset()\n\nprint(\"Searching best threshold...\")\nsearch_space = np.arange(10, 50, 1)\n\nmodel = ShopeeModel()\nmodel.eval()\nmodel = replace_activations(model, torch.nn.SiLU, Mish())\nmodel.load_state_dict(torch.load(CFG.MODEL_PATH))\nmodel = model.to(CFG.DEVICE)\n\nvalid_embeddings = get_valid_embeddings(valid_df, model)\n\nbest_f1_valid = 0.\nbest_threshold = 0.\n\nfor i in search_space:\n threshold = i / 100\n valid_df, valid_predictions = get_valid_neighbors(valid_df, valid_embeddings, threshold=threshold)\n\n valid_f1 = valid_df.f1.mean()\n valid_recall = valid_df.recall.mean()\n valid_precision = valid_df.precision.mean()\n\n print(f\"threshold = {threshold} -> f1 score = {valid_f1}, recall = {valid_recall}, precision = {valid_precision}\")\n\n if (valid_f1 > best_f1_valid):\n best_f1_valid = valid_f1\n best_threshold = threshold\n\nprint(\"Best threshold =\", best_threshold)\nprint(\"Best f1 score =\", best_f1_valid)\nBEST_THRESHOLD = best_threshold", "Searching best threshold...\nBuilding Model Backbone for efficientnet_b3 model\nUsing Curricular Face\n" ], [ "print(\"Searching best knn...\")\n\nsearch_space = np.arange(40, 80, 2)\n\nbest_f1_valid = 0.\nbest_knn = 0\n\nfor knn in search_space:\n\n valid_df, valid_predictions = get_valid_neighbors(valid_df, valid_embeddings, KNN=knn, threshold=BEST_THRESHOLD)\n\n valid_f1 = valid_df.f1.mean()\n valid_recall = valid_df.recall.mean()\n valid_precision = valid_df.precision.mean()\n\n print(f\"knn = {knn} -> f1 score = {valid_f1}, recall = {valid_recall}, precision = {valid_precision}\")\n\n if (valid_f1 > best_f1_valid):\n best_f1_valid = valid_f1\n best_knn = knn\n\nprint(\"Best knn =\", best_knn)\nprint(\"Best f1 score =\", best_f1_valid)\nBEST_KNN = best_knn", "Searching best knn...\nknn = 40 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 42 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 44 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 46 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 48 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 50 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 52 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 54 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 56 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 58 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 60 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 62 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 64 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 66 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 68 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 70 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 72 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 74 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 76 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nknn = 78 -> f1 score = 0.777758209672296, recall = 0.7531682743571495, precision = 0.9166499975976827\nBest knn = 40\nBest f1 score = 0.777758209672296\n" ], [ "test_embeddings = get_valid_embeddings(test_df,model)\ntest_df, test_predictions = get_valid_neighbors(test_df, test_embeddings, KNN = BEST_KNN, threshold = BEST_THRESHOLD)\n\ntest_f1 = test_df.f1.mean()\ntest_recall = test_df.recall.mean()\ntest_precision = test_df.precision.mean()\nprint(f'Test f1 score = {test_f1}, recall = {test_recall}, precision = {test_precision}')", "_____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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cb67e991821a1ca04a195980bd9f499230692cb2
13,962
ipynb
Jupyter Notebook
model.ipynb
SadiJr/INE5644-Projeto
316a5ed06daab1ff11e99615533ac4c46e52fa2f
[ "MIT" ]
null
null
null
model.ipynb
SadiJr/INE5644-Projeto
316a5ed06daab1ff11e99615533ac4c46e52fa2f
[ "MIT" ]
null
null
null
model.ipynb
SadiJr/INE5644-Projeto
316a5ed06daab1ff11e99615533ac4c46e52fa2f
[ "MIT" ]
null
null
null
30.618421
133
0.51146
[ [ [ "import pandas as pd\nimport numpy as np\nimport datetime\nimport matplotlib.pyplot as plt\n\nimport math\nimport seaborn as sns\nimport multiprocessing\nfrom multiprocessing import Process\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn import metrics\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.neighbors import KNeighborsRegressor", "_____no_output_____" ], [ "class Result:\n def __init__(self, dataset_type, random_state, test_size, algorithm_name, fit_time,\n figure, r_square, mea, mse, rmse, k):\n self.dataset_type = dataset_type\n self.random_state = random_state\n self.test_size = test_size\n self.algorithm_name = algorithm_name\n self.fit_time = fit_time\n self.figure = figure\n self.r_square = r_square\n self.mea = mea\n self.mse = mse\n self.rmse = rmse\n self.k = k\n \n def print_object(self):\n print(f\"\"\"\n Algorithm: {self.algorithm_name}\n Dataset: {self.dataset_type}\n Test Size: {self.test_size}\n Random State: {self.random_state}\n Fit Time: {self.fit_time}\n Figure Path: {self.figure}\n R Square: {self.r_square}\n MEA: {self.mea}\n MSE: {self.mse}\n RMSE: {self.rmse}\n K: {self.k}\\n\\n\n \"\"\")", "_____no_output_____" ], [ "results1 = multiprocessing.Manager().list()\nresults2 = multiprocessing.Manager().list()\nresults3 = multiprocessing.Manager().list()", "_____no_output_____" ], [ "def runInParallel(*fns):\n proc = []\n for fn in fns:\n p = Process(target=fn)\n p.start()\n proc.append(p)\n for p in proc:\n p.join()", "_____no_output_____" ], [ "def standard_scaler(dataset):\n columns = dataset.columns.to_list()\n scaler = StandardScaler() \n scaled = scaler.fit_transform(dataset.to_numpy())\n return pd.DataFrame(scaled, columns=columns)", "_____no_output_____" ], [ "def min_max_scaler(dataset):\n columns = dataset.columns.to_list()\n scaler = MinMaxScaler() \n scaled = scaler.fit_transform(dataset.to_numpy())\n return pd.DataFrame(scaled, columns=columns)", "_____no_output_____" ], [ "data1 = pd.read_csv('process.csv')\ndata2 = standard_scaler(data1)\ndata3 = min_max_scaler(data1)", "_____no_output_____" ], [ "def plotGraph(y_test, y_pred, regressorName, figName):\n plt.figure(figsize=(10,10))\n plt.scatter(y_test,y_pred, c='crimson')\n plt.yscale('log')\n plt.xscale('log')\n\n p1 = max(max(y_pred), max(y_test))\n p2 = min(min(y_pred), min(y_test))\n plt.plot([p1, p2], [p1, p2], 'b-')\n plt.xlabel('True Values', fontsize=15)\n plt.ylabel('Predictions', fontsize=15)\n plt.axis('equal')\n plt.savefig(figName, format=\"svg\")\n plt.close()", "_____no_output_____" ], [ "def split_test(rand, size, dataset):\n y = dataset['new_cases'].values\n x = dataset.drop(['new_cases'], axis=1).values\n return train_test_split(x, y, random_state=rand, test_size=size)", "_____no_output_____" ], [ "def liner_test(name, rand, size, X_train, X_test, y_train, y_test):\n start = datetime.datetime.now()\n \n regressor = LinearRegression()\n regressor.fit(X_train, y_train)\n y_pred = regressor.predict(X_test)\n \n end = datetime.datetime.now()\n \n figureName = f\"LN-{name}-{rand}-{size}\"\n plotGraph(y_test, y_pred, 'Linear Regression', figureName)\n\n r_square = (1 - ((1 - metrics.r2_score(y_test, y_pred)) * (len(y_test) - 1)) / (len(y_test) - X_train.shape[1] - 1))\n mea = metrics.mean_absolute_error(y_test, y_pred)\n mse = metrics.mean_squared_error(y_test, y_pred)\n rmse = np.sqrt(metrics.mean_squared_error(y_test, y_pred))\n \n res = Result(name, rand, size, \"LinearRegression\", (end-start), figureName, r_square, mea, mse, rmse, 0)\n results1.append(res)", "_____no_output_____" ], [ "def rand_forest(name, rand, size, X_train, X_test, y_train, y_test):\n start = datetime.datetime.now()\n \n rf = RandomForestRegressor(n_estimators = 1000 - rand, random_state = rand + 10)\n rf.fit(X_train, y_train);\n y_pred = rf.predict(X_test)\n \n end = datetime.datetime.now()\n \n figureName = f\"RF-{name}-{rand}-{size}\"\n plotGraph(y_test, y_pred, 'Random Forest', figureName)\n r_square = (1 - ((1 - metrics.r2_score(y_test, y_pred)) * (len(y_test) - 1)) / (len(y_test) - X_train.shape[1] - 1))\n mea = metrics.mean_absolute_error(y_test, y_pred)\n mse = metrics.mean_squared_error(y_test, y_pred)\n rmse = np.sqrt(metrics.mean_squared_error(y_test, y_pred))\n \n res = Result(name, rand, size, \"RandomForest\", (end-start), figureName, r_square, mea, mse, rmse, 0)\n results2.append(res)", "_____no_output_____" ], [ "def knn_regression(name, rand, size, X_train, X_test, y_train, y_test):\n start = datetime.datetime.now()\n for K in range(20):\n K = K+1\n \n clf = KNeighborsRegressor(n_neighbors = K)\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n \n end = datetime.datetime.now()\n \n figureName = f\"RF-{name}-{rand}-{size}-{K}\"\n plotGraph(y_test, y_pred, f\"KNN with K {K}\", figureName)\n \n r_square = (1 - ((1 - metrics.r2_score(y_test, y_pred)) * (len(y_test) - 1)) / (len(y_test) - X_train.shape[1] - 1))\n mea = metrics.mean_absolute_error(y_test, y_pred)\n mse = metrics.mean_squared_error(y_test, y_pred)\n rmse = np.sqrt(metrics.mean_squared_error(y_test, y_pred))\n \n res = Result(name, rand, size, \"KNN\", (end-start), figureName, r_square, mea, mse, rmse, K)\n results3.append(res)", "_____no_output_____" ], [ "def test1():\n start = datetime.datetime.now()\n first_time = True\n for i in range(0, 11): \n if first_time:\n rand = 0\n size = 0.05\n first_time = False\n else:\n rand = i * 5\n size = i * 0.05\n \n X_train, X_test, y_train, y_test = split_test(rand, size, data1)\n liner_test('Original', rand, size, X_train, X_test, y_train, y_test)\n rand_forest('Original', rand, size, X_train, X_test, y_train, y_test)\n knn_regression('Original', rand, size, X_train, X_test, y_train, y_test)\n \n end = datetime.datetime.now()\n print(f\"\\nTest1 Time: \", end-start)", "_____no_output_____" ], [ "def test2():\n start = datetime.datetime.now()\n first_time = True\n for i in range(0, 11):\n if first_time:\n rand = 0\n size = 0.05\n first_time = False\n else:\n rand = i * 5\n size = i * 0.05\n \n X_train, X_test, y_train, y_test = split_test(rand, size, data2)\n liner_test('Standard Scaler', rand, size, X_train, X_test, y_train, y_test)\n rand_forest('Standard Scaler', rand, size, X_train, X_test, y_train, y_test)\n knn_regression('Standard Scaler', rand, size, X_train, X_test, y_train, y_test)\n \n end = datetime.datetime.now()\n print(f\"\\nTest2 Time: \", end-start)", "_____no_output_____" ], [ "def test3():\n start = datetime.datetime.now()\n first_time = True\n \n for i in range(0, 11): \n if first_time:\n rand = 0\n size = 0.05\n first_time = False\n else:\n rand = i * 5\n size = i * 0.05\n \n rand = int(rand)\n X_train, X_test, y_train, y_test = split_test(rand, size, data3)\n liner_test('MinMax Scaler', rand, size, X_train, X_test, y_train, y_test)\n rand_forest('MinMax Scaler', rand, size, X_train, X_test, y_train, y_test)\n knn_regression('MinMax Scaler', rand, size, X_train, X_test, y_train, y_test)\n \n end = datetime.datetime.now()\n print(f\"\\nTest3 Time: \", end-start)", "_____no_output_____" ], [ "start = datetime.datetime.now()\nprint(f\"Parallel start at {start}\")\nrunInParallel(test1, test2, test3)\nend = datetime.datetime.now()\nprint(f\"\\n\\nParallel time: \", end-start)", "_____no_output_____" ], [ "for item in results2:\n results3.append(item)\nfor item in results1:\n results3.append(item)", "_____no_output_____" ], [ "results = list(results3)", "_____no_output_____" ], [ "results.sort(key=lambda x: x.r_square, reverse=True)\nfor i in range(0, 11):\n print(f\"Position {i}:\")\n results[i].print_object()", "_____no_output_____" ], [ "results.sort(key=lambda x: x.mea, reverse=False)\nfor i in range(0, 11):\n print(f\"Position {i}:\")\n results[i].print_object()", "_____no_output_____" ], [ "results.sort(key=lambda x: x.mse, reverse=False)\nfor i in range(0, 11):\n print(f\"Position {i}:\")\n results[i].print_object()", "_____no_output_____" ], [ "results.sort(key=lambda x: x.rmse, reverse=False)\nfor i in range(0, 11):\n print(f\"Position {i}:\")\n results[i].print_object()", "_____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" ] ]
cb67ea24a34a29c6ffad79290b588cf8c3cfe5d3
5,140
ipynb
Jupyter Notebook
soft_trigo_generator.ipynb
arthurlm/atari-creative-playground
f44c56bd63535f1c526cb3be60b8a221609b8e5b
[ "MIT" ]
null
null
null
soft_trigo_generator.ipynb
arthurlm/atari-creative-playground
f44c56bd63535f1c526cb3be60b8a221609b8e5b
[ "MIT" ]
null
null
null
soft_trigo_generator.ipynb
arthurlm/atari-creative-playground
f44c56bd63535f1c526cb3be60b8a221609b8e5b
[ "MIT" ]
null
null
null
22.643172
104
0.47393
[ [ [ "import math\nimport numpy as np", "_____no_output_____" ] ], [ [ "# Small studdy on approximation", "_____no_output_____" ] ], [ [ "size = 1000\ncos_table = [int(math.cos(x / size) * size) for x in range(0, math.floor(math.pi * 2 * size))]\n\nprint(f\"{min(cos_table)=}, {max(cos_table)=}\")\n# cos_table", "min(cos_table)=-999, max(cos_table)=1000\n" ], [ "\ndef sotf_cos(x):\n return cos_table[math.floor(x) % len(cos_table)]\n\ndef diff_soft_cos(x):\n value = sotf_cos(x * size) / size\n return value - round(math.cos(x), 5)\n\ndef print_diff(x):\n print(f\"{float(x):<10.5}: {diff_soft_cos(x)}\")\n\n\nprint_diff(0)\nprint_diff(math.pi / 2)\nprint_diff(math.pi)\nprint_diff(math.pi * 3)\n\n\"mean diff: \", np.mean([diff_soft_cos(x) for x in np.arange(0, math.pi * 2 * 4, 0.01)])", "0.0 : 0.0\n1.5708 : 0.0\n3.1416 : 0.0010000000000000009\n9.4248 : 0.0010000000000000009\n" ] ], [ [ "# Code generator", "_____no_output_____" ] ], [ [ "import math\n\nsize = 2000\ncos_table = [int(math.cos(x / size) * size) for x in range(0, math.floor(math.pi * 2 * size))]\nsin_table = [int(math.sin(x / size) * size) for x in range(0, math.floor(math.pi * 2 * size))]", "_____no_output_____" ], [ "from pathlib import Path\n\nh_src = Path(\"./src/includes/trigo.h\")\nc_src = Path(\"./src/trigo.c\")\n\nh_content = \"\"\"\n#ifndef _TRIGO_H_\n#define _TRIGO_H_\n\n#include <stdint.h>\n\ntypedef int16_t softfloat_t;\n\nsoftfloat_t float_scale();\nint16_t sizeof_tables();\n\nsoftfloat_t soft_cos(uint16_t value);\nsoftfloat_t soft_sin(uint16_t value);\n\n#endif // _TRIGO_H_\n\"\"\".strip()\n\nc_content = \"\"\"\n#include \"trigo.h\"\n\"\"\".strip()\n\ndef append_table(name, values):\n global c_content\n c_content += f\"\"\"\n\nstatic softfloat_t _{name}_table[] = {{\n\"\"\".rstrip()\n\n for idx, value in enumerate(values):\n if idx > 0:\n c_content += \", \"\n if idx % 15 == 0:\n c_content += \"\\n \"\n c_content += f\"{value}\"\n\n c_content += \"};\"\n\nappend_table(\"cos\", cos_table)\nappend_table(\"sin\", sin_table)\n\nc_content += f\"\"\"\n\nsoftfloat_t float_scale()\n{{\n return {size};\n}}\n\"\"\"\n\nc_content += f\"\"\"\nint16_t sizeof_tables()\n{{\n return {len(cos_table)};\n}}\n\nsoftfloat_t soft_cos(uint16_t value)\n{{\n return _cos_table[value % {len(cos_table)}];\n}}\n\nsoftfloat_t soft_sin(uint16_t value)\n{{\n return _sin_table[value % {len(sin_table)}];\n}}\n\"\"\"\n\n\nh_src.write_text(h_content)\nc_src.write_text(c_content)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cb67f5b919fe529ab55921b3f6d0f3684757b938
250,328
ipynb
Jupyter Notebook
USGS_StreamFlow.ipynb
roy-shuvashish/JupyterUSGS
50bf9ddc707c6973ab2c84c11855e6b77221e6e1
[ "MIT" ]
null
null
null
USGS_StreamFlow.ipynb
roy-shuvashish/JupyterUSGS
50bf9ddc707c6973ab2c84c11855e6b77221e6e1
[ "MIT" ]
null
null
null
USGS_StreamFlow.ipynb
roy-shuvashish/JupyterUSGS
50bf9ddc707c6973ab2c84c11855e6b77221e6e1
[ "MIT" ]
null
null
null
200.583333
47,512
0.877768
[ [ [ "# North and South Chickamauga Creek USGS Stations Streamflow Data for HSPF Model\n\n## Shuvashish Roy", "_____no_output_____" ], [ "### *We will use hydrofunctions package for flow data retrieval*", "_____no_output_____" ] ], [ [ "pip show hydrofunctions", "_____no_output_____" ], [ "import hydrofunctions as hf\nimport pandas as pd\n%matplotlib inline\nimport hydrofunctions as hf\nimport pandas as pd\n%matplotlib inline\nhf.__version__\npd.__version__\npd.__version__", "_____no_output_____" ], [ "sites = ['03566535', '03567500'] # USGS gage ids \nstart = '2017-01-01'\nend = '2021-01-01'\nservice = 'dv'\n# Request our data.\ndata = hf.NWIS(sites, service, start, end, file='graphing-1.parquet') # you can also do it in csv\ndata # Verify that the data request went fine.", "Reading data from graphing-1.parquet\n" ] ], [ [ " ### *See the precipitation and discharge columns of these two USGS gages from the dataset*\n", "_____no_output_____" ] ], [ [ "import pandas as pd\nQ1=pd.read_parquet('graphing-1.parquet')\nQ1.head()", "_____no_output_____" ] ], [ [ "### *Extract only the Discharge data*", "_____no_output_____" ] ], [ [ "Q = data.df('00060') # q or 00060 for discharge data", "_____no_output_____" ], [ "Q.head(5)", "_____no_output_____" ], [ "Q.columns=[\"NORTH CHICKAMAUGA\",\"SOUTH CHICKAMAUGA\" ]\nQ.index.names = ['Date']\nQ.head()", "_____no_output_____" ] ], [ [ "### *Plot the daily discharge data* ", "_____no_output_____" ] ], [ [ "Q.plot() # or data.df('discharge').plot() or data.df('00060').plot()\n", "_____no_output_____" ], [ "data.df('00045').plot() # precipitation plot ", "_____no_output_____" ] ], [ [ "### *Let's plot weekly monthly or quarterly data*", "_____no_output_____" ] ], [ [ "ax=Q.resample('W').sum().plot(); # use 'M or 'Q' for mothly and quarterly data plot \nax.set_ylabel('Discharge (cfs)')\nax.set_xlabel(' Date (UTC)')\nax.set_title(' Weekly Flow')", "_____no_output_____" ] ], [ [ "### Let's check the annual trend ", "_____no_output_____" ] ], [ [ "ax=Q.resample('D').sum().rolling(365).sum().plot() # yearly rolling mean \nax.set_ylim(0,None);", "_____no_output_____" ] ], [ [ "#### In North Chickamauga stream, discharge increased until early 2019 and decreased after that. Every point indicates sum of discharge of previous 365 days\n\n\n", "_____no_output_____" ], [ "### *Get the total discharge of North and South Chick streams which can later be used as upstream boundry conditon for TN River EFDC model*", "_____no_output_____" ] ], [ [ "Q.loc[:,'Total']=Q.loc[:,'NORTH CHICKAMAUGA']+Q.loc[:,'SOUTH CHICKAMAUGA']", "C:\\Users\\clhal\\anaconda3\\lib\\site-packages\\pandas\\core\\indexing.py:1745: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n isetter(ilocs[0], value)\n" ], [ "Q # check the Total flow ", "_____no_output_____" ], [ "ax=Q.resample('m').sum().plot(); \nax.set_ylabel('Discharge (cfs)')\nax.set_xlabel(' Date (UTC)')\nax.set_title(' monthly Flow')", "_____no_output_____" ], [ "Q.groupby(Q.index.month).mean().plot();", "_____no_output_____" ], [ "df=Q\ndf.loc[:,'Month'] = df.index.month", "C:\\Users\\clhal\\anaconda3\\lib\\site-packages\\pandas\\core\\indexing.py:1596: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n self.obj[key] = _infer_fill_value(value)\nC:\\Users\\clhal\\anaconda3\\lib\\site-packages\\pandas\\core\\indexing.py:1783: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n self.obj[item_labels[indexer[info_axis]]] = value\n" ], [ "df\n", "_____no_output_____" ], [ "Q", "_____no_output_____" ] ], [ [ "# Let's draw some box plots ", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nax = df.boxplot(column=['NORTH CHICKAMAUGA'], by='Month',showfliers=False)\nplt.suptitle(\"North Chickamauga\")\nax.set_title('')\nax = df.boxplot(column=['SOUTH CHICKAMAUGA'], by='Month',showfliers=False)\nplt.suptitle(\"\")\nax.set_title('South Chickamauga')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
cb67f608cc77ec00f3d8bcf24442a9f38330b576
1,774
ipynb
Jupyter Notebook
nb/hw.ipynb
fuzzyklein/hw-4.2.0
76a7fcae40c60f18b067d0f51ee70d7a578ffea0
[ "Apache-2.0" ]
null
null
null
nb/hw.ipynb
fuzzyklein/hw-4.2.0
76a7fcae40c60f18b067d0f51ee70d7a578ffea0
[ "Apache-2.0" ]
null
null
null
nb/hw.ipynb
fuzzyklein/hw-4.2.0
76a7fcae40c60f18b067d0f51ee70d7a578ffea0
[ "Apache-2.0" ]
null
null
null
19.282609
105
0.533258
[ [ [ "# Hello, World!", "_____no_output_____" ], [ "Version: `4.2.0`", "_____no_output_____" ], [ "Skeleton project for Python software development.", "_____no_output_____" ], [ "## Usage", "_____no_output_____" ], [ "To run this particular Hello, World! program, navigate to the project directory `hw-4.2.0` and use:", "_____no_output_____" ], [ "```\nhw-4.2.0$ ./run\nHello, World!\n\n```", "_____no_output_____" ], [ "## Description", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cb6805fcfa7ca1a264171ffbe735d48b5fc02610
52,200
ipynb
Jupyter Notebook
Code/Machine Learning Prediction_Part_5.ipynb
huongquynh1611/SPACEX_PRESENTATION
5191f1a6930e7f64f965f71ca5ad12b214b09f8b
[ "Apache-2.0" ]
null
null
null
Code/Machine Learning Prediction_Part_5.ipynb
huongquynh1611/SPACEX_PRESENTATION
5191f1a6930e7f64f965f71ca5ad12b214b09f8b
[ "Apache-2.0" ]
null
null
null
Code/Machine Learning Prediction_Part_5.ipynb
huongquynh1611/SPACEX_PRESENTATION
5191f1a6930e7f64f965f71ca5ad12b214b09f8b
[ "Apache-2.0" ]
null
null
null
52,200
52,200
0.680096
[ [ [ "<center>\n <img src=\"https://gitlab.com/ibm/skills-network/courses/placeholder101/-/raw/master/labs/module%201/images/IDSNlogo.png\" width=\"300\" alt=\"cognitiveclass.ai logo\" />\n</center>\n", "_____no_output_____" ], [ "# **Space X Falcon 9 First Stage Landing Prediction**\n", "_____no_output_____" ], [ "## Assignment: Machine Learning Prediction\n", "_____no_output_____" ], [ "Estimated time needed: **60** minutes\n", "_____no_output_____" ], [ "Space X advertises Falcon 9 rocket launches on its website with a cost of 62 million dollars; other providers cost upward of 165 million dollars each, much of the savings is because Space X can reuse the first stage. Therefore if we can determine if the first stage will land, we can determine the cost of a launch. This information can be used if an alternate company wants to bid against space X for a rocket launch. In this lab, you will create a machine learning pipeline to predict if the first stage will land given the data from the preceding labs.\n", "_____no_output_____" ], [ "![](https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DS0701EN-SkillsNetwork/api/Images/landing\\_1.gif)\n", "_____no_output_____" ], [ "Several examples of an unsuccessful landing are shown here:\n", "_____no_output_____" ], [ "![](https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DS0701EN-SkillsNetwork/api/Images/crash.gif)\n", "_____no_output_____" ], [ "Most unsuccessful landings are planed. Space X; performs a controlled landing in the oceans.\n", "_____no_output_____" ], [ "## Objectives\n", "_____no_output_____" ], [ "Perform exploratory Data Analysis and determine Training Labels\n\n* create a column for the class\n* Standardize the data\n* Split into training data and test data\n\n\\-Find best Hyperparameter for SVM, Classification Trees and Logistic Regression\n\n* Find the method performs best using test data\n", "_____no_output_____" ], [ "***\n", "_____no_output_____" ], [ "## Import Libraries and Define Auxiliary Functions\n", "_____no_output_____" ], [ "We will import the following libraries for the lab\n", "_____no_output_____" ] ], [ [ "# Pandas is a software library written for the Python programming language for data manipulation and analysis.\nimport pandas as pd\n# NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays\nimport numpy as np\n# Matplotlib is a plotting library for python and pyplot gives us a MatLab like plotting framework. We will use this in our plotter function to plot data.\nimport matplotlib.pyplot as plt\n#Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics\nimport seaborn as sns\n# Preprocessing allows us to standarsize our data\nfrom sklearn import preprocessing\n# Allows us to split our data into training and testing data\nfrom sklearn.model_selection import train_test_split\n# Allows us to test parameters of classification algorithms and find the best one\nfrom sklearn.model_selection import GridSearchCV\n# Logistic Regression classification algorithm\nfrom sklearn.linear_model import LogisticRegression\n# Support Vector Machine classification algorithm\nfrom sklearn.svm import SVC\n# Decision Tree classification algorithm\nfrom sklearn.tree import DecisionTreeClassifier\n# K Nearest Neighbors classification algorithm\nfrom sklearn.neighbors import KNeighborsClassifier", "_____no_output_____" ] ], [ [ "This function is to plot the confusion matrix.\n", "_____no_output_____" ] ], [ [ "def plot_confusion_matrix(y,y_predict):\n \"this function plots the confusion matrix\"\n from sklearn.metrics import confusion_matrix\n\n cm = confusion_matrix(y, y_predict)\n ax= plt.subplot()\n sns.heatmap(cm, annot=True, ax = ax); #annot=True to annotate cells\n ax.set_xlabel('Predicted labels')\n ax.set_ylabel('True labels')\n ax.set_title('Confusion Matrix'); \n ax.xaxis.set_ticklabels(['did not land', 'land']); ax.yaxis.set_ticklabels(['did not land', 'landed'])", "_____no_output_____" ] ], [ [ "## Load the dataframe\n", "_____no_output_____" ], [ "Load the data\n", "_____no_output_____" ] ], [ [ "data = pd.read_csv(\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/dataset_part_2.csv\")\n\n# If you were unable to complete the previous lab correctly you can uncomment and load this csv\n\n# data = pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DS0701EN-SkillsNetwork/api/dataset_part_2.csv')\n\ndata.head()", "_____no_output_____" ], [ "X = pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/dataset_part_3.csv')\n\n# If you were unable to complete the previous lab correctly you can uncomment and load this csv\n\n# X = pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DS0701EN-SkillsNetwork/api/dataset_part_3.csv')\n\nX.head(100)", "_____no_output_____" ] ], [ [ "## TASK 1\n", "_____no_output_____" ], [ "Create a NumPy array from the column <code>Class</code> in <code>data</code>, by applying the method <code>to_numpy()</code> then\nassign it to the variable <code>Y</code>,make sure the output is a Pandas series (only one bracket df\\['name of column']).\n", "_____no_output_____" ] ], [ [ "Y = data['Class'].to_numpy()", "_____no_output_____" ], [ "Y", "_____no_output_____" ] ], [ [ "## TASK 2\n", "_____no_output_____" ], [ "Standardize the data in <code>X</code> then reassign it to the variable <code>X</code> using the transform provided below.\n", "_____no_output_____" ] ], [ [ "# students get this \ntransform = preprocessing.StandardScaler()", "_____no_output_____" ] ], [ [ "We split the data into training and testing data using the function <code>train_test_split</code>. The training data is divided into validation data, a second set used for training data; then the models are trained and hyperparameters are selected using the function <code>GridSearchCV</code>.\n", "_____no_output_____" ], [ "## TASK 3\n", "_____no_output_____" ], [ "Use the function train_test_split to split the data X and Y into training and test data. Set the parameter test_size to 0.2 and random_state to 2. The training data and test data should be assigned to the following labels.\n", "_____no_output_____" ], [ "<code>X_train, X_test, Y_train, Y_test</code>\n", "_____no_output_____" ] ], [ [ "X_train,X_test,y_train,y_test = train_test_split(X,Y,test_size=0.2,random_state=2)", "_____no_output_____" ] ], [ [ "we can see we only have 18 test samples.\n", "_____no_output_____" ] ], [ [ "y_test.shape", "_____no_output_____" ] ], [ [ "## TASK 4\n", "_____no_output_____" ], [ "Create a logistic regression object then create a GridSearchCV object <code>logreg_cv</code> with cv = 10. Fit the object to find the best parameters from the dictionary <code>parameters</code>.\n", "_____no_output_____" ] ], [ [ "parameters ={\"C\":[0.01,0.1,1],'penalty':['l2'], 'solver':['lbfgs']}# l1 lasso l2 ridge\nlr=LogisticRegression()\nlogreg_cv = GridSearchCV(lr, parameters, cv=10, refit=True)\nlogreg_cv.fit(X_train, y_train)", "/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n" ] ], [ [ "We output the <code>GridSearchCV</code> object for logistic regression. We display the best parameters using the data attribute <code>best_params\\_</code> and the accuracy on the validation data using the data attribute <code>best_score\\_</code>.\n", "_____no_output_____" ] ], [ [ "print(\"tuned hpyerparameters :(best parameters) \",logreg_cv.best_params_)\nprint(\"accuracy :\",logreg_cv.best_score_)", "tuned hpyerparameters :(best parameters) {'C': 0.1, 'penalty': 'l2', 'solver': 'lbfgs'}\naccuracy : 0.8196428571428571\n" ] ], [ [ "## TASK 5\n", "_____no_output_____" ], [ "Calculate the accuracy on the test data using the method <code>score</code>:\n", "_____no_output_____" ] ], [ [ "from sklearn.metrics import classification_report, confusion_matrix, f1_score, precision_score, recall_score, roc_auc_score", "_____no_output_____" ], [ "\nglm_acc=logreg_cv.score(X_test, y_test)\nprint(\"Test set accuracy: {:.1%}\".format(glm_acc))\nglm_probs = logreg_cv.predict_proba(X_test)[:,1]\nglm_auc=roc_auc_score(y_test, glm_probs) \nprint(\"Test set AUC: {:.3}\".format(glm_auc))", "Test set accuracy: 83.3%\nTest set AUC: 0.917\n" ] ], [ [ "Lets look at the confusion matrix:\n", "_____no_output_____" ] ], [ [ "yhat=logreg_cv.predict(X_test)\nplot_confusion_matrix(y_test,yhat)", "_____no_output_____" ] ], [ [ "Examining the confusion matrix, we see that logistic regression can distinguish between the different classes. We see that the major problem is false positives.\n", "_____no_output_____" ], [ "## TASK 6\n", "_____no_output_____" ], [ "Create a support vector machine object then create a <code>GridSearchCV</code> object <code>svm_cv</code> with cv - 10. Fit the object to find the best parameters from the dictionary <code>parameters</code>.\n", "_____no_output_____" ] ], [ [ "parameters = {'kernel':('linear', 'rbf','poly','rbf', 'sigmoid'),\n 'C': np.logspace(-3, 3, 5),\n 'gamma':np.logspace(-3, 3, 5)}\nsvm = SVC(probability=True, random_state=1)", "_____no_output_____" ], [ "svm_cv = GridSearchCV(svm,parameters,cv=10)\nsvm_cv.fit(X_train, y_train)", "_____no_output_____" ], [ "print(\"tuned hpyerparameters :(best parameters) \",svm_cv.best_params_)\nprint(\"accuracy :\",svm_cv.best_score_)", "_____no_output_____" ] ], [ [ "## TASK 7\n", "_____no_output_____" ], [ "Calculate the accuracy on the test data using the method <code>score</code>:\n", "_____no_output_____" ], [ "We can plot the confusion matrix\n", "_____no_output_____" ] ], [ [ "yhat=svm_cv.predict(X_test)\nplot_confusion_matrix(Y_test,yhat)", "_____no_output_____" ] ], [ [ "## TASK 8\n", "_____no_output_____" ], [ "Create a decision tree classifier object then create a <code>GridSearchCV</code> object <code>tree_cv</code> with cv = 10. Fit the object to find the best parameters from the dictionary <code>parameters</code>.\n", "_____no_output_____" ] ], [ [ "parameters = {'criterion': ['gini', 'entropy'],\n 'splitter': ['best', 'random'],\n 'max_depth': [2*n for n in range(1,10)],\n 'max_features': ['auto', 'sqrt'],\n 'min_samples_leaf': [1, 2, 4],\n 'min_samples_split': [2, 5, 10]}\n\ntree = DecisionTreeClassifier()", "_____no_output_____" ], [ "print(\"tuned hpyerparameters :(best parameters) \",tree_cv.best_params_)\nprint(\"accuracy :\",tree_cv.best_score_)", "_____no_output_____" ] ], [ [ "## TASK 9\n", "_____no_output_____" ], [ "Calculate the accuracy of tree_cv on the test data using the method <code>score</code>:\n", "_____no_output_____" ], [ "We can plot the confusion matrix\n", "_____no_output_____" ] ], [ [ "yhat = svm_cv.predict(X_test)\nplot_confusion_matrix(Y_test,yhat)", "_____no_output_____" ] ], [ [ "## TASK 10\n", "_____no_output_____" ], [ "Create a k nearest neighbors object then create a <code>GridSearchCV</code> object <code>knn_cv</code> with cv = 10. Fit the object to find the best parameters from the dictionary <code>parameters</code>.\n", "_____no_output_____" ] ], [ [ "parameters = {'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n 'algorithm': ['auto', 'ball_tree', 'kd_tree', 'brute'],\n 'p': [1,2]}\n\nKNN = KNeighborsClassifier()", "_____no_output_____" ], [ "\n", "_____no_output_____" ], [ "print(\"tuned hpyerparameters :(best parameters) \",knn_cv.best_params_)\nprint(\"accuracy :\",knn_cv.best_score_)", "_____no_output_____" ] ], [ [ "## TASK 11\n", "_____no_output_____" ], [ "Calculate the accuracy of tree_cv on the test data using the method <code>score</code>:\n", "_____no_output_____" ], [ "We can plot the confusion matrix\n", "_____no_output_____" ] ], [ [ "yhat = knn_cv.predict(X_test)\nplot_confusion_matrix(Y_test,yhat)", "_____no_output_____" ] ], [ [ "## TASK 12\n", "_____no_output_____" ], [ "Find the method performs best:\n", "_____no_output_____" ], [ "## Authors\n", "_____no_output_____" ], [ "<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDS0321ENSkillsNetwork26802033-2021-01-01\">Joseph Santarcangelo</a> has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.\n", "_____no_output_____" ], [ "## Change Log\n", "_____no_output_____" ], [ "| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n| ----------------- | ------- | ------------- | ----------------------- |\n| 2021-08-31 | 1.1 | Lakshmi Holla | Modified markdown |\n| 2020-09-20 | 1.0 | Joseph | Modified Multiple Areas |\n", "_____no_output_____" ], [ "Copyright © 2020 IBM Corporation. All rights reserved.\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cb6818fec297f4ae590d405eb319d2ea1778bd57
371,627
ipynb
Jupyter Notebook
notebooks/nitrate_drawdown_C-version.ipynb
ClaraCDouglas/net_community_production
0b1370f00abc99cb4c08c9f84abe12faf781643d
[ "MIT" ]
1
2021-06-03T11:05:00.000Z
2021-06-03T11:05:00.000Z
notebooks/nitrate_drawdown_C-version.ipynb
ClaraCDouglas/net_community_production
0b1370f00abc99cb4c08c9f84abe12faf781643d
[ "MIT" ]
null
null
null
notebooks/nitrate_drawdown_C-version.ipynb
ClaraCDouglas/net_community_production
0b1370f00abc99cb4c08c9f84abe12faf781643d
[ "MIT" ]
1
2022-01-17T21:50:48.000Z
2022-01-17T21:50:48.000Z
80.230354
51,204
0.560764
[ [ [ "# While in argo environment: Import necessary packages for this notebook \nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport xarray as xr\nimport pandas as pd\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\n%matplotlib inline \nimport glob", "_____no_output_____" ] ], [ [ "!python -m pip install \"dask[complete]\" ", "_____no_output_____" ] ], [ [ "float_id = '9094' # '9094' '9099' '7652' '9125'\nrootdir = '../data/raw/LowRes/'\nfd = xr.open_mfdataset(rootdir + float_id + 'SOOCNQC.nc')\nJULD = pd.to_datetime(fd.JULD.values)", "_____no_output_____" ] ], [ [ "#reads float data\nfile_folder = \"../data/raw/WGfloats/\"\n#file_folder = \"../../data/raw/LowRes\"\nfloat_number = \"5904468\" #7900918 #9094\n\nfiles = sorted(glob.glob(file_folder+\"/*\"+float_number+\"*.nc\"))\nprint(files)\n#files = sorted(glob.glob(file_folder+\"/*.nc\"))", "_____no_output_____" ], [ "fd = xr.open_mfdataset(file_folder+\"/*\"+float_number+\"*.nc\")\nJULD = pd.to_datetime(fd.JULD.values)", "_____no_output_____" ] ], [ [ "fd", "_____no_output_____" ] ], [ [ "#help(xr.open_mfdataset)", "_____no_output_____" ], [ "rootdir + float_id + 'SOOCNQC.nc'\n\n#Data/LowRes/9099SOOCNQC.nc\n#fd", "_____no_output_____" ] ], [ [ "# HELPER FUNCTIONS\n\n#define a function that smooths using a boxcar filter (running mean)\n # not sure this function is actually used in the notebook??\ndef smooth(y, box_pts):\n box = np.ones(box_pts)/box_pts\n y_smooth = np.convolve(y, box, mode='same')\n return y_smooth\n\n#interpolate the data onto the standard depth grid given by x_int\ndef interpolate(x_int, xvals, yvals):\n yvals_int = []\n for n in range(0, len(yvals)): # len(yvals) = profile number\n yvals_int.append(np.interp(x_int, xvals[n, :], yvals[n, :]))\n #convert the interpolated data from a list to numpy array\n return np.asarray(yvals_int)\n\n# calculate the vertically integrated data column inventory using the composite trapezoidal rule\ndef integrate(zi, data, depth_range):\n n_profs = len(data)\n zi_start = abs(zi - depth_range[0]).argmin() # find location of start depth\n zi_end = abs(zi - depth_range[1]).argmin() # find location of end depth\n zi_struct = np.ones((n_profs, 1)) * zi[zi_start : zi_end] # add +1 to get the 200m value\n data = data[:, zi_start : zi_end] # add +1 to get the 200m value\n col_inv = []\n for n in range(0, len(data)):\n col_inv.append(np.trapz(data[n,:][~np.isnan(data[n,:])], zi_struct[n,:][~np.isnan(data[n,:])]))\n return col_inv", "_____no_output_____" ], [ "#fd #(float data)\n#fd.Pressure.isel(N_PROF=0).values", "_____no_output_____" ], [ "# Interpolate nitrate and poc\nzi = np.arange(0, 1600, 5) # 5 = 320 depth intervals between 0m to 1595m\nnitr_int = interpolate(zi, fd.Pressure[:, ::-1], fd.Nitrate[:, ::-1]) # interpolate nitrate values across zi depth intervals for all 188 profiles\n\n# Integrate nitrate and poc - total nitrate in upper 200m\nupperlim=25\nlowerlim=200\nnitr = np.array(integrate(zi, nitr_int, [upperlim, lowerlim])) # integrate interpolated nitrate values between 25m-200m ", "_____no_output_____" ], [ "print(nitr)\n#nitr.shape", "[5884.64622024 5721.65531726 5602.44399794 5520.27985333 5455.41719828\n 5391.9213858 5479.44401897 5508.25543581 5592.36579726 5589.91995657\n 5557.15823478 5559.35747554 5553.88891863 5575.22391296 5561.47180647\n 5528.53021754 5534.32938019 5497.93982039 5488.17178344 5549.90723605\n 5464.00293491 5404.94977774 5527.54824269 5416.21150375 5529.66591214\n 5558.91960685 5474.42990105 5537.65119602 5534.67307126 5569.2220892\n 5516.7619716 5511.37846565 5513.71016107 5501.12454389 5467.60101741\n 5465.33025542 5436.56417746 5370.07432146 5238.53917671 5302.87225069\n 5239.2864977 5250.21991778 5265.71230901 5345.67360823 5319.75429365\n 5326.98531255 5318.43915998 5293.05723929 5195.24048007 5226.44801753\n 5289.00537447 5327.1222224 5379.64755525 5327.30269362 5305.07060682\n 5415.50493909 5390.57434367 5391.58920871 5402.12147937 5496.90248844\n 5419.26668804 5495.08139418 5499.54392718 5494.04501234 5520.36893652\n 5522.46969949 5486.51579861 5499.69411884 5496.50225029 5490.56445157\n 5450.5350186 5403.80812816 5397.67138424 5372.28582702 5416.76417797\n 5228.21692988 5309.00901729 5288.87076852 5237.23510452 5285.91852588\n 5299.50788633 5261.53100262 5266.14680241 5216.70184009 5181.58251485\n 5334.28782377 5347.15384086 5361.00259993 5393.66720317 5389.43995199\n 5288.8806318 5324.66609346 5286.15350072 5138.86530625 5273.36357645\n 5285.04046882 5325.17146409 5382.84910019 5559.5287796 5539.47325292\n 0. 5574.09759165 5438.57449382 5370.7904752 5291.11996822\n 5306.94249216 5242.3979153 5233.21552461 5171.8047102 5105.32167325\n 5294.95469162 5287.78455173 4418.33332106 5249.56454999 5168.44572281\n 5030.59423395 5159.79323056 5447.23672383 5285.21748106 5388.20109472\n 5359.89778705 5341.83866237 5345.90923026 5247.43138203 5178.60891393\n 5121.6583127 4985.15529788 5163.0678275 5377.43266981 5254.57392032\n 4995.99199937 5114.71980999 5362.12895256 5264.63592382 5460.73226511\n 5449.38844765 5493.17691868 5495.0628934 5496.37173833 5579.75953913\n 5443.43164643 5407.47549091 5350.65417282 5323.6876134 5392.94409235\n 5380.42110158 5397.97646083 5382.02913132 5456.13093822 5418.54398868\n 5411.40218138 5498.0421019 5481.78492349 5492.86939815 5545.7191291\n 5499.86132845 5584.20624978 5472.83536013 5401.72806936]\n" ], [ "# Find winter maximum and summer minimum upper ocean nitrate levels \ndef find_extrema(data, date_range, find_func):\n # Find indices of float profiles in the date range\n date_mask = (JULD > date_range[0]) & (JULD < date_range[1])\n \n # Get the index where the data is closest to the find_func\n index = np.where(data[date_mask] == find_func(data[date_mask]))[0][0]\n \n # Get the average data for the month of the extrema\n month_start = JULD[date_mask][index].replace(day = 1) # .replace just changes the day of max/min to 1\n month_dates = (JULD > month_start) & (JULD < month_start + pd.Timedelta(days = 30)) \n # ^ not sure why this is needed? or what it does? - it is not used later on...\n #month_avg = np.mean(data[date_mask]) #average whole winter or summer values\n # ^ but it should be just the month of max/min nitrate, \n # not the average for the whole season?... \n \n month_mask = (JULD.month[date_mask] == month_start.month)\n month_avg = np.mean(data[date_mask][month_mask])\n \n return month_avg, JULD[date_mask][index], data[date_mask][index]\n\nyears = [2015, 2016, 2017, 2018]\nnitr_extrema = []\nnitr_ancp = []\nfor y in years:\n winter_range = [pd.datetime(y, 8, 1), pd.datetime(y, 12, 1)] #4 months\n summer_range = [pd.datetime(y, 12, 1), pd.datetime(y + 1, 4, 1)] #4 months\n\n # Find maximum winter and minimum summer nitrate\n avg_max_nitr, max_nitr_date, max_nitr = find_extrema(nitr, winter_range, np.max)\n avg_min_nitr, min_nitr_date, min_nitr = find_extrema(nitr, summer_range, np.min)\n \n \n # Convert to annual nitrate drawdown\n redfield_ratio = 106.0/16.0 #106C:16NO3-\n \n # Nitrate units: umol/kg --> divide by 1000 to convert to mol/kg\n \n nitr_drawdown = (avg_max_nitr - avg_min_nitr)/1000.0 * redfield_ratio\n \n nitr_ancp.append(nitr_drawdown)\n \n nitr_extrema.append(((max_nitr, max_nitr_date), (min_nitr, min_nitr_date)))\n \n print(y, max_nitr_date, max_nitr, avg_max_nitr)\n print(y, min_nitr_date, min_nitr, avg_min_nitr)", "2015 2015-10-15 13:41:00.000000768 5569.222089200839 5540.2190440218765\n2015 2016-01-15 17:37:59.999998208 5238.539176706666 5303.828582949857\n2016 2016-10-21 12:14:00.000000256 5522.469699491864 5505.849861740028\n2016 2017-02-01 12:36:00.000002048 5228.216929876666 5275.365571896017\n2017 2017-10-27 20:15:59.999996416 5574.097591645161 3704.523614854718\n2017 2018-02-18 10:49:59.999998976 4418.333321058395 4985.227474260124\n2018 2018-11-23 11:54:59.999997696 5579.75953913173 5523.731390288997\n2018 2019-01-04 00:59:00.000000256 5323.687613398696 5365.684269109664\n" ], [ "# plot ANCP for chosen float over specified time period\nfig, ax = plt.subplots(figsize = (10, 5))\nax.plot(years, nitr_ancp)\nax.set_ylabel('ANCP [mol/m$^2$]', size = 12) \nax.set_xticks(years)\nax.set_xticklabels(['2015', '2016', '2017', '2018'])\nax.set_title('ANCP for Float ' + float_id)", "_____no_output_____" ], [ "# Find winter maximum and summer minimum upper ocean nitrate levels \ndef find_extrema(data, date_range, find_func):\n # Find indices of float profiles in the date range\n date_mask = (JULD > date_range[0]) & (JULD < date_range[1])\n \n # Get the index where the data is closest to the find_func\n index = np.where(data[date_mask] == find_func(data[date_mask]))[0][0]\n \n # Get the average data for the month of the extrema\n month_start = JULD[date_mask][index].replace(day = 1) # .replace just changes the day of max/min to 1\n month_dates = (JULD > month_start) & (JULD < month_start + pd.Timedelta(days = 30)) \n # ^ not sure why this is needed? or what it does? - it is not used later on...\n month_avg = np.mean(data[date_mask]) #average whole winter or summer values\n # ^ but it should be just the month of max/min nitrate, \n # not the average for the whole season?... \n \n # month_mask = (JULD.month[date_mask] == month_start.month)\n # month_avg = np.mean(data[date_mask][month_mask])\n \n return month_avg, JULD[date_mask][index], data[date_mask][index]\n\nyears = [2015, 2016, 2017, 2018]\nnitr_extrema = []\nnitr_ancp = []\nfor y in years:\n winter_range = [pd.datetime(y, 8, 1), pd.datetime(y, 12, 1)]\n summer_range = [pd.datetime(y, 12, 1), pd.datetime(y + 1, 4, 1)]\n\n # Find maximum winter and minimum summer nitrate\n avg_max_nitr, max_nitr_date, max_nitr = find_extrema(nitr, winter_range, np.max)\n avg_min_nitr, min_nitr_date, min_nitr = find_extrema(nitr, summer_range, np.min)\n \n \n # Convert to annual nitrate drawdown\n redfield_ratio = 106.0/16.0 #106C:16NO3-\n \n # Nitrate units: umol/kg --> divide by 1000 to convert to mol/kg\n \n nitr_drawdown = (avg_max_nitr - avg_min_nitr)/1000.0 * redfield_ratio\n \n nitr_ancp.append(nitr_drawdown)\n \n nitr_extrema.append(((max_nitr, max_nitr_date), (min_nitr, min_nitr_date)))\n \n print(y, max_nitr_date, max_nitr, avg_max_nitr)\n print(y, min_nitr_date, min_nitr, avg_min_nitr)", "2015 2015-10-15 13:41:00.000000768 5569.222089200839 5515.941388764965\n2015 2016-01-15 17:37:59.999998208 5238.539176706666 5335.717761504481\n2016 2016-10-21 12:14:00.000000256 5522.469699491864 5484.77379939102\n2016 2017-02-01 12:36:00.000002048 5228.216929876666 5348.365601665027\n2017 2017-10-27 20:15:59.999996416 5574.097591645161 4931.572873100042\n2017 2018-02-18 10:49:59.999998976 4418.333321058395 5139.096051436783\n2018 2018-11-23 11:54:59.999997696 5579.75953913173 5361.997923182396\n2018 2019-01-04 00:59:00.000000256 5323.687613398696 5405.228243318643\n" ], [ "# plot ANCP for chosen float over specified time period\nfig, ax = plt.subplots(figsize = (10, 5))\nax.plot(years, nitr_ancp)\nax.set_ylabel('ANCP [mol/m$^2$]', size = 12) \nax.set_xticks(years)\nax.set_xticklabels(['2015', '2016', '2017', '2018'])\nax.set_title('ANCP for Float ' + float_id)", "_____no_output_____" ], [ "# Plot values of integrated nitrate (mol/m2) \n\nfig, ax = plt.subplots(figsize = (20, 5))\n\n# Integrate nitrate and poc between given depth range\nzi_range = [25, 200]\nnitr_v = np.array(integrate(zi, nitr_int, zi_range))/1000.0\n\n# Function to mark the maximum/minimum values of the data for summer and winter\ndef add_extrema(ax, ydata, extrema):\n for i in range(len(years)):\n y = years[i]\n winter_range = [pd.datetime(y, 8, 1), pd.datetime(y, 12, 1)]\n summer_range = [pd.datetime(y, 12, 1), pd.datetime(y + 1, 4, 1)]\n plt.axvspan(winter_range[0], winter_range[1], color='grey', alpha=0.1)\n plt.axvspan(summer_range[0], summer_range[1], color='y', alpha=0.1)\n\n (nmax, dmax), (nmin, dmin) = extrema[i]\n nitr_vmax = ydata[JULD == dmax]\n nitr_vmin = ydata[JULD == dmin]\n ax.plot([dmax], nitr_vmax, color = 'g', marker='o', markersize=8)\n ax.plot([dmin], nitr_vmin, color = 'r', marker='o', markersize=8)\n return ax \n\n#ax = plt.subplot(2, 1, 1)\nax.plot(JULD, nitr_v)\nadd_extrema(ax, nitr_v, nitr_extrema)\nax.set_ylabel('Nitrate [mol/$m^2$]')\nax.set_title('Integrated Nitrate (' + str(zi_range[0]) + '-' + str(zi_range[1]) + 'm)')\nax.set_ylim([4.5, ax.get_ylim()[1]])", "<ipython-input-13-9dc2ba3e9a54>:13: FutureWarning: The pandas.datetime class is deprecated and will be removed from pandas in a future version. Import from datetime module instead.\n winter_range = [pd.datetime(y, 8, 1), pd.datetime(y, 12, 1)]\n<ipython-input-13-9dc2ba3e9a54>:14: FutureWarning: The pandas.datetime class is deprecated and will be removed from pandas in a future version. Import from datetime module instead.\n summer_range = [pd.datetime(y, 12, 1), pd.datetime(y + 1, 4, 1)]\n<ipython-input-13-9dc2ba3e9a54>:13: FutureWarning: The pandas.datetime class is deprecated and will be removed from pandas in a future version. Import from datetime module instead.\n winter_range = [pd.datetime(y, 8, 1), pd.datetime(y, 12, 1)]\n<ipython-input-13-9dc2ba3e9a54>:14: FutureWarning: The pandas.datetime class is deprecated and will be removed from pandas in a future version. Import from datetime module instead.\n summer_range = [pd.datetime(y, 12, 1), pd.datetime(y + 1, 4, 1)]\n<ipython-input-13-9dc2ba3e9a54>:13: FutureWarning: The pandas.datetime class is deprecated and will be removed from pandas in a future version. Import from datetime module instead.\n winter_range = [pd.datetime(y, 8, 1), pd.datetime(y, 12, 1)]\n<ipython-input-13-9dc2ba3e9a54>:14: FutureWarning: The pandas.datetime class is deprecated and will be removed from pandas in a future version. Import from datetime module instead.\n summer_range = [pd.datetime(y, 12, 1), pd.datetime(y + 1, 4, 1)]\n<ipython-input-13-9dc2ba3e9a54>:13: FutureWarning: The pandas.datetime class is deprecated and will be removed from pandas in a future version. Import from datetime module instead.\n winter_range = [pd.datetime(y, 8, 1), pd.datetime(y, 12, 1)]\n<ipython-input-13-9dc2ba3e9a54>:14: FutureWarning: The pandas.datetime class is deprecated and will be removed from pandas in a future version. Import from datetime module instead.\n summer_range = [pd.datetime(y, 12, 1), pd.datetime(y + 1, 4, 1)]\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb681c724f36ec4fa24f49505f4eac3f9e4467b3
7,721
ipynb
Jupyter Notebook
paper/figures/gaussians.ipynb
tagordon/exoplanet
bc7aa74408daac43732ca2d80588fad2b94753ed
[ "MIT" ]
null
null
null
paper/figures/gaussians.ipynb
tagordon/exoplanet
bc7aa74408daac43732ca2d80588fad2b94753ed
[ "MIT" ]
null
null
null
paper/figures/gaussians.ipynb
tagordon/exoplanet
bc7aa74408daac43732ca2d80588fad2b94753ed
[ "MIT" ]
null
null
null
27.379433
75
0.498381
[ [ [ "%matplotlib inline", "_____no_output_____" ], [ "%run notebook_setup", "_____no_output_____" ], [ "ndim = 15", "_____no_output_____" ], [ "import time\n\nimport emcee\nimport numpy as np\n\nimport pymc3 as pm\nfrom pymc3.step_methods.hmc import quadpotential as quad", "_____no_output_____" ], [ "np.random.seed(41)\n\nwith pm.Model() as model:\n pm.Normal(\"x\", shape=ndim)\n\n potential = quad.QuadPotentialDiag(np.ones(ndim))\n\n step_kwargs = dict()\n step_kwargs[\"model\"] = model\n step_kwargs[\"step_scale\"] = 1.0 * model.ndim ** 0.25\n step_kwargs[\"adapt_step_size\"] = False\n step = pm.NUTS(potential=potential, **step_kwargs)\n\n start = time.time()\n trace = pm.sample(tune=0, draws=10000, step=step, cores=1)\n time_pymc3 = time.time() - start", "_____no_output_____" ], [ "samples_pymc3 = np.array(trace.get_values(\"x\", combine=False))\nsamples_pymc3 = np.moveaxis(samples_pymc3, 0, 1)\ntau_pymc3 = emcee.autocorr.integrated_time(samples_pymc3)\nneff_pymc3 = np.prod(samples_pymc3.shape[:2]) / tau_pymc3\nteff_pymc3 = time_pymc3 / neff_pymc3\nteff_pymc3", "_____no_output_____" ], [ "np.random.seed(1234)\n\nimport exoplanet as xo\n\nwith model:\n func = xo.get_theano_function_for_var(model.logpt)\n\n def logprob(theta):\n point = model.bijection.rmap(theta)\n args = xo.get_args_for_theano_function(point)\n return func(*args)\n\n x0 = np.random.randn(ndim)\n nwalkers = 36\n x0 = np.random.randn(nwalkers, ndim)\n\n emcee_sampler = emcee.EnsembleSampler(nwalkers, ndim, logprob)\n state = emcee_sampler.run_mcmc(x0, 2000, progress=True)\n emcee_sampler.reset()\n strt = time.time()\n emcee_sampler.run_mcmc(state, 20000, progress=True)\n time_emcee = time.time() - strt", "_____no_output_____" ], [ "samples_emcee = emcee_sampler.get_chain()\ntau_emcee = emcee.autocorr.integrated_time(samples_emcee)\nneff_emcee = np.prod(samples_emcee.shape[:2]) / tau_emcee\nteff_emcee = time_emcee / neff_emcee\nteff_emcee", "_____no_output_____" ], [ "def get_function(x):\n n_t, n_w = x.shape\n f = np.zeros(n_t)\n for k in range(n_w):\n f += emcee.autocorr.function_1d(x[:, k])\n f /= n_w\n return f\n\n\nfig, axes = plt.subplots(2, 2, figsize=(10, 8))\n\nax = axes[0, 0]\nt_emcee = np.linspace(0, time_emcee, samples_emcee.shape[0])\nm = t_emcee < 5\nax.plot(t_emcee[m], samples_emcee[m, 5, 0], lw=0.75)\nax.annotate(\n \"emcee\",\n xy=(0, 1),\n xycoords=\"axes fraction\",\n ha=\"left\",\n va=\"top\",\n fontsize=16,\n xytext=(5, -5),\n textcoords=\"offset points\",\n)\nax.set_ylabel(r\"$\\theta_1$\")\nax.set_xlim(0, 5)\nax.set_ylim(-4, 4)\nax.set_xticklabels([])\n\nax = axes[1, 0]\nt_pymc3 = np.linspace(0, time_pymc3, samples_pymc3.shape[0])\nm = t_pymc3 < 5\nax.plot(t_pymc3[m], samples_pymc3[m, 0, 0], lw=0.75)\nax.annotate(\n \"pymc3\",\n xy=(0, 1),\n xycoords=\"axes fraction\",\n ha=\"left\",\n va=\"top\",\n fontsize=16,\n xytext=(5, -5),\n textcoords=\"offset points\",\n)\nax.set_ylabel(r\"$\\theta_1$\")\nax.set_xlabel(\"walltime [s]\")\nax.set_xlim(0, 5)\nax.set_ylim(-4, 4)\n\nax = axes[0, 1]\nf_emcee = get_function(samples_emcee[:, :, 0])\nscale = 1e3 * time_emcee / np.prod(samples_emcee.shape[:2])\nax.plot(scale * np.arange(len(f_emcee)), f_emcee)\nax.axhline(0, color=\"k\", lw=0.5)\nax.annotate(\n \"emcee\",\n xy=(1, 1),\n xycoords=\"axes fraction\",\n ha=\"right\",\n va=\"top\",\n fontsize=16,\n xytext=(-5, -5),\n textcoords=\"offset points\",\n)\nval = 2 * scale * tau_emcee[0]\nmax_x = 1.5 * val\nax.axvline(val, color=\"k\", lw=3, alpha=0.3)\nax.annotate(\n \"{0:.1f} ms\".format(val),\n xy=(val / max_x, 1),\n xycoords=\"axes fraction\",\n ha=\"right\",\n va=\"top\",\n fontsize=12,\n alpha=0.3,\n xytext=(-5, -5),\n textcoords=\"offset points\",\n)\nax.set_xlim(0, max_x)\nax.set_xticklabels([])\nax.set_yticks([])\nax.set_ylabel(\"autocorrelation\")\n\nax = axes[1, 1]\nf_pymc3 = get_function(samples_pymc3[:, :, 0])\nscale = 1e3 * time_pymc3 / np.prod(samples_pymc3.shape[:2])\nax.plot(scale * np.arange(len(f_pymc3)), f_pymc3)\nax.axhline(0, color=\"k\", lw=0.5)\nax.annotate(\n \"pymc3\",\n xy=(1, 1),\n xycoords=\"axes fraction\",\n ha=\"right\",\n va=\"top\",\n fontsize=16,\n xytext=(-5, -5),\n textcoords=\"offset points\",\n)\nval = 2 * scale * tau_pymc3[0]\nax.axvline(val, color=\"k\", lw=3, alpha=0.3)\nax.annotate(\n \"{0:.1f} ms\".format(val),\n xy=(val / max_x, 1),\n xycoords=\"axes fraction\",\n ha=\"left\",\n va=\"top\",\n fontsize=12,\n alpha=0.3,\n xytext=(5, -5),\n textcoords=\"offset points\",\n)\nax.set_xlim(0, max_x)\nax.set_yticks([])\nax.set_xlabel(\"walltime lag [ms]\")\nax.set_ylabel(\"autocorrelation\")\n\nfig.subplots_adjust(hspace=0.05, wspace=0.15)\nfig.savefig(\"gaussians.pdf\", bbox_inches=\"tight\");", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb681eac01f4f19adc3859e299a82d6291221b6e
466,588
ipynb
Jupyter Notebook
Data512_Final_Project.ipynb
Gmoog/data512_finalproject
846e957d868d7dcdb46e38478b180b16a77a8a98
[ "MIT" ]
null
null
null
Data512_Final_Project.ipynb
Gmoog/data512_finalproject
846e957d868d7dcdb46e38478b180b16a77a8a98
[ "MIT" ]
null
null
null
Data512_Final_Project.ipynb
Gmoog/data512_finalproject
846e957d868d7dcdb46e38478b180b16a77a8a98
[ "MIT" ]
null
null
null
338.843863
223,518
0.902548
[ [ [ "<h1 id=\"i1\"> Data 512 - A6 : Predicting Earthquakes : Final Project</h1>\n\nGautam Moogimane <br>\nUniversity of Washington - Fall 2018", "_____no_output_____" ], [ "<h2 id=\"i1\">I. Introduction </h2> \n \nHaving stayed in Japan for a long time, I've been accustomed to getting up at odd hours, with everything shaking around me. Tremors and earthquakes are so common, its rare for a week to go by without one. Considering the amount of damage these natural disasters are capable of, the fact that we are no closer to predicting them than we were a 100 years ago, is slightly surprising to say the least. With this analysis, I aim to use machine learning to analyze historic earthquake data from around the world, and use to it to hopefully come up with some observations about earthquakes in the future.\n\nAs per the statistics, there are hundreds of earthquakes that happen every day around the globe, with magnitudes ranging from 2-4 on the richter scale. The larger ones, between 5-7 on the scale occur every week or so, while the biggest at 7.5 and above are seen once a year. The 2011 Japan earthquake with its epicenter in Fukushima only had a magnitude of about 6.6, but was strong enough to cause buildings in Tokyo, which is a 100 miles away from Fukushima, to sway for around 30 seconds. Electricty went down, trains were stalled on the tracks, traffic came to a standstill, and thousands of people took to the streets, walking many miles to get back home. I was reading a paper on the economic damages caused by this earthquake, and it was in the range of around 360 billion. This is about 6% of Japans revenue for that year.\n\nThe aim of this study is not to break some new ground as far as predicting earthquakes go, but a way to see how appropriate or accurate machine learning can be in this situation. Statistics deals with probabilites, and machine learning, which applies these concepts on a computer, can only predict with a certain amount of accuracy, based on the data that it is trained on. To accurately predict earthquakes, one needs to be able to say with a degree of certainty, what the exact location, time of occurance and the magnitude will be. Considering the data we have, and how spread out the locations are, it would be an unrealistic goal trying to achieve this using machine learning at this point in time. Instead, with this analysis, given a certain location(like country with latitudes and longitudes), and time( year, instead of down to the exact second), if we can come up with information about the magnitude of the next earthquake/earthquakes, based on what happened in the past, that would be a good start. \n\nFrom a human centered ethics perspective, the system needs to ensure that any inherent bias in the data does not trickle down in the output generated. From a personal standpoint, I would need to ensure my experience in Japan, does not make me expect or not expect certain results from the model, thereby skewing the predictions in a particular direction.\n\n", "_____no_output_____" ], [ "<h2 id=\"i2\">II. Background </h2>\n\nThere has been plenty of work done in this space, and some interesting work that I happened to come across are detailed below <br>\n[Machine learning predicts earthquakes in a lab](https://www.cam.ac.uk/research/news/machine-learning-used-to-predict-earthquakes-in-a-lab-setting) <br>\nThis is a fascinating read of a team of researchers from University of Cambridge, Los Alamos National Laboratory and Boston University, who were able to identify signals that preempt the arrival of an earthquake under controlled settings. They had steel blocks set up to replicate the physical forces at work under the earths surface, and found particular acoustic signals being generated by the faults, just before an earthquake. Using a machine learning algorithm, that was fed this signal, it was able to identify instances when the fault was under stress, and about to cause an earthquake. <br>\nAn obvious drawback, is that the actual forces under the earths surface, are a lot different than what is found under controlled settings. So the sucess they have had in a lab, has not yet been replicated in actual settings. But the results are encouraging. <br>\n\nAnother paper that is an interesting read, is the research done in the Hindukush region, to predict the magnitude of an earthquake using machine learning. <br>\n[Hindukush earthquake magnitude prediction](https://www.researchgate.net/publication/307951466_Earthquake_magnitude_prediction_in_Hindukush_region_using_machine_learning_techniques) <br>\nThey use mathematically calculated eight seismic indicators, and then apply four machine learning algorithms,\npattern recognition neural network, recurrent neural network, random forest and linear programming boost ensemble classifier to model relationships between the indicators and future earthquake occurences.", "_____no_output_____" ], [ "<h2 id=\"i3\">III. Data</h2> \n\nThe data is from the significant earthquake database, and contains historic data from 2150 BC to the present day, of earthquakes from all over the world. The data is constantly updated to reflect the latest events.\n\n\nAs per the description from the 'data.nodc.noaa.gov' site where the data is hosted:\n > The Significant Earthquake Database is a global listing of over 5,700 earthquakes from 2150 BC to the present. A significant earthquake is classified as one that meets at least one of the following criteria:\n \n > caused deaths, caused moderate damage (approximately 1 million dollars or more), magnitude 7.5 or greater, Modified Mercalli Intensity (MMI) X or greater, or the earthquake generated a tsunami. \n \n > The database provides information on the date and time of occurrence, latitude and longitude, focal depth, magnitude, maximum MMI intensity, and socio-economic data such as the total number of casualties, injuries, houses destroyed, and houses damaged, and dollar damage estimates. \nReferences, political geography, and additional comments are also provided for each earthquake. If the earthquake was associated with a tsunami or volcanic eruption, it is flagged and linked to the related tsunami event or significant volcanic eruption.\n \n\nThe fields that are key from the perspective of our analysis are detailed in the table below <br>\n\n| Field Name | Datatype | Description |\n| :-------------: | :-------------: | :-------------: |\n| Year | Integer | The year of occurence |\n| Focal Depth | Integer | Depth of the epicenter |\n| Eq_Primary | Float | Magnitude of the earthquake |\n| Country | String | Name of the country |\n| Location_Name | String | Specific location in the country | \n| Latitude | Float | Coordinates of the exact location |\n| Longitude | Float | Coordinates of the exact location |\n\n\n\nThe data can be downloaded in a tab separated file, and can be imported into excel or python for analysis. <br>\nWe start by ingesting the data from the link provided below <br>\n[National Geophysical Data Center / World Data Service (NGDC/WDS): Significant Earthquake Database. National Geophysical Data Center, NOAA](http://dx.doi.org/10.7289/V5TD9V7K)", "_____no_output_____" ], [ "### Step-1 Ingesting the data", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\n# the data is contained in a tab seperated file\nraw_data = pd.read_csv('earthquake_historical.tsv', sep='\\t')", "_____no_output_____" ], [ "# Describe the data\nraw_data.describe()", "_____no_output_____" ] ], [ [ "### Step-2 Preparing the data", "_____no_output_____" ], [ "First thing to check is what the EQ fields other than EQ_PRIMARY contain, and if at any point they contain different values. <br>\nWe intend to use EQ_PRIMARY, but need to make sure the other fields do not contain additional information.<br>\nAlso dropping rows where EQ_PRIMARY or EQ_MAG_MS is null", "_____no_output_____" ] ], [ [ "# drop empty rows\ncomp = raw_data.dropna(subset=['EQ_PRIMARY', 'EQ_MAG_MS'])\ncomp = comp[['I_D','EQ_PRIMARY','EQ_MAG_MS']]\n# compare the values of EQ_PRIMARY and EQ_MAG_MS\ncomp['Result'] = np.where(comp['EQ_PRIMARY'] == comp['EQ_MAG_MS'], 'TRUE', 'FALSE')\n# find the ratio of rows that match to total rows \n(len(comp[comp.Result == 'TRUE']))/(len(comp))", "_____no_output_____" ] ], [ [ "About 25% of the values seem to be different for the 2 columns. I suspect the different EQ columns \nare just recording values from different sources.", "_____no_output_____" ], [ "Another point to check is if there are rows where EQ_PRIMARY is null and data exists in other 6 EQ rows. ", "_____no_output_____" ] ], [ [ "# filter the data to rows where EQ_PRIMARY is null\ntemp = raw_data[pd.isnull(raw_data['EQ_PRIMARY'])]\n# check for cases where the other rows are not null\ntemp[(temp.EQ_MAG_MS.notnull()) | (temp.EQ_MAG_MW.notnull()) | (temp.EQ_MAG_MB.notnull()) | (temp.EQ_MAG_ML.notnull()) | (temp.EQ_MAG_MFA.notnull()) | (temp.EQ_MAG_UNK.notnull())] ", "_____no_output_____" ] ], [ [ "Turns out there are no such cases.<br>\nWe will continue to stick with EQ_PRIMARY for our analysis", "_____no_output_____" ], [ "The fields we are mainly concerned with are 'YEAR','MONTH','DAY','EQ_PRIMARY','COUNTRY','LATITUDE' and 'LONGITUDE'.\nCreating a new dataframe with these fields\n", "_____no_output_____" ] ], [ [ "eq_df = raw_data[['YEAR','MONTH','DAY','EQ_PRIMARY','COUNTRY','LATITUDE','LONGITUDE']]\n# renaming EQ_PRIMARY to MAGNITUDE\neq_df = eq_df.rename(columns={\"EQ_PRIMARY\":\"MAGNITUDE\"})\n# rows where the magnitude is missing, can be deleted as they are of no use to us.\neq_df = eq_df[eq_df.MAGNITUDE.notnull()]\neq_df.head()", "_____no_output_____" ] ], [ [ "<h2 id=\"i4\">IV. Methods</h2> ", "_____no_output_____" ], [ "### Visualizing the data", "_____no_output_____" ], [ "Using the Basemap python package along with matplotlib, we can plot the different latitudes and longitudes on a world map, and color code the different points based on the magnitude. ", "_____no_output_____" ] ], [ [ "# prepare the data for projection on a world map\n# extract latitudes,longitudes and magnitude from the dataframe as a list\neq_df['LATITUDE'] = lat = pd.to_numeric(eq_df['LATITUDE'], errors='coerce').tolist() \neq_df['LONGITUDE'] = lon = pd.to_numeric(eq_df['LONGITUDE'], errors='coerce').tolist()\neq_df['MAGNITUDE'] = mag = pd.to_numeric(eq_df['MAGNITUDE'], errors='coerce').tolist()\n# some rows have null data, these can be manually filled in\neq_df.loc[1759,'LATITUDE'] = 40.9006\neq_df.loc[1759,'LONGITUDE'] = 174.8860\neq_df.loc[2261,'LATITUDE'] = 0.7893\neq_df.loc[3256,'LATITUDE'] = 0.7893\neq_df.loc[3341,'LATITUDE'] = 0.8893\neq_df.loc[3382,'LATITUDE'] = 0.8693\neq_df.loc[3437,'LATITUDE'] = 1.3733\n# save the cleaned data\neq_df.to_csv('clean_earthquake.csv')", "_____no_output_____" ], [ "from mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\nfrom pylab import rcParams\n%matplotlib inline\n# set the size of the plot in width and height\nrcParams['figure.figsize'] = (16,12)\n# lon_0 is central longitude of projection.\n# resolution = 'l' means use low resolution, which loads faster and works for a large map.\neq_map = Basemap(projection='robin', lon_0=0, lat_0=0, resolution='l', area_thresh=1500.0)\neq_map.drawcoastlines()\neq_map.fillcontinents(color='gray')\neq_map.drawmapboundary(fill_color='white')\nx,y = eq_map(lon, lat)\n# ro stands for red color and 'o' marker\neq_map.plot(x, y, 'ro', markersize=4)\nplt.title(\"Map of all Earthquakes\")\nplt.show()", "_____no_output_____" ], [ "# for a slightly different perspective, lets visualize different colors based on the magnitude \nimport matplotlib.lines as mlines\ndef color(magnitude):\n # Returns green for small earthquakes, yellow for medium earthquakes, and red for large earthquakes.\n if magnitude < 4.0:\n return ('go')\n elif magnitude < 6.0:\n return ('yo')\n else:\n return ('ro')\n# specify the labels for the legend \ngreen_line = mlines.Line2D([], [], color='green', marker='o',\n markersize=5, label='Magnitude less than 4')\nyellow_line = mlines.Line2D([], [], color='yellow', marker='o',\n markersize=5, label='Magnitude between 4 and 6')\nred_line = mlines.Line2D([], [], color='red', marker='o',\n markersize=5, label='Magnitude greater than 6')\n\nrcParams['figure.figsize'] = (16,12)\n# lon_0 is central longitude of projection.\n# resolution = 'l' means use low resolution, which loads faster and works for a large map.\neq_map_col = Basemap(projection='robin', lon_0=0, lat_0=0, resolution='l', area_thresh=1500.0)\neq_map_col.drawcoastlines()\neq_map_col.fillcontinents(color='gray')\neq_map_col.drawmapboundary(fill_color='white')\n# go through each value and plot with color according to the magnitude\nfor lo, la, ma in zip(lon, lat, mag):\n x,y = eq_map_col(lo, la)\n col = color(ma)\n eq_map_col.plot(x, y, col, markersize=4)\n\nplt.title(\"Map of all Earthquakes\")\nplt.legend(handles=[green_line,yellow_line,red_line],bbox_to_anchor=(1, 1))\nplt.show()", "_____no_output_____" ] ], [ [ "### Running algorithms on the Data", "_____no_output_____" ], [ "We start by trying to fit a linear regression model on the data, which will use a linear combination of the input variables that can best map to the target value . In this instance, I do not think this would be a great fit, as intuitively, it does not seem that there is a linear relationship between Year, latitude and longitude with the magnitude of an earthquake. ", "_____no_output_____" ] ], [ [ "# for running machine learning algorthms, lets concentrate on the features YEAR,LATITUDE and LONGITUDE with MAGNITUDE as the label\n# creating a new dataset with these 3 columns\neqml_df = eq_df[['YEAR','LATITUDE','LONGITUDE','MAGNITUDE']]\nX = eq_df[['YEAR','LATITUDE','LONGITUDE']]\ny = eq_df['MAGNITUDE']", "_____no_output_____" ], [ "# splitting the data into test and train sets using sklearn modules\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=28)\nprint(X_train.shape, X_test.shape, y_train.shape, X_test.shape)", "(3210, 3) (1070, 3) (3210,) (1070, 3)\n" ], [ "from sklearn.linear_model import LinearRegression\n# initialize a linear regression model\nregression_model = LinearRegression()\n# fit the model using the training data above\nregression_model.fit(X_train, y_train)\n# after fitting, check the values predicted by the model on the test data\nregression_model.predict(X_test)", "_____no_output_____" ], [ "# prediction score for this model on the test data\nregression_model.score(X_test,y_test)", "_____no_output_____" ] ], [ [ "As sort of expected, the score is very low on the predicted values, which does not seem to map to the magnitude values from our target variable.", "_____no_output_____" ], [ "The next algorithm is a decision tree regressor, and the way this works is similar to a binary tree with a root and nodes on it. It proceeds down a sequential root answering 'If this then that' questions along the way, that ultimately leads to a result. It works well on both categorical and numerical data, and performance wise is also fast. Some of its downfalls include overfitting, especially if there are many features in the model and the tree runs deep.", "_____no_output_____" ] ], [ [ "from sklearn import tree\nmod_tree = tree.DecisionTreeRegressor()\nmod_tree.fit(X_train,y_train)\nmod_tree.predict(X_test)", "_____no_output_____" ], [ "# prediction score for this model on the test data\nmod_tree.score(X_test,y_test)", "_____no_output_____" ] ], [ [ "Surprisingly the score isnt great here either, on default settings, with max_depth as none and min_samples_split=2.", "_____no_output_____" ], [ "A random forest is an aggregation of multiple decision trees that combines all their results into one final result. This makes it a lot more robust than a single decision tree, and can help reduce errors due to bias and variance, that can creep into decision tree models. It randomly selects a subset of the features for each of its decision trees, which ultimately when combined, tends to cover all the features. Its also fairly resistant to overfitting. ", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestRegressor\n# initialize the model\nreg = RandomForestRegressor(random_state=28)\n# fit the parameters\nreg.fit(X_train, y_train)\nreg.predict(X_test)", "_____no_output_____" ], [ "reg.score(X_test,y_test)", "_____no_output_____" ] ], [ [ "This score is a significant improvement over the previous algorithms used, and we can try to further tune it by using cross validation to optimize the values of the hyperparameters.", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import GridSearchCV\n# initialize the parameters in multiples of 10\nparameters = {'n_estimators':[1,10,100,500,1000]}\n# initialize the gridsearch cross validation object\ngrid_obj = GridSearchCV(reg, parameters)\ngrid_fit = grid_obj.fit(X_train, y_train)\n# find the best fit from the parameters\nbest_fit = grid_fit.best_estimator_\nbest_fit.score(X_test,y_test)", "_____no_output_____" ] ], [ [ "This model gives us a pretty decent score of around 45%, which we will use for our findings ahead", "_____no_output_____" ], [ "<h2 id=\"i4\">V. Findings </h2> \n\nIn the following section, we try to answer some of the research questions we had before the analysis began", "_____no_output_____" ], [ "### What would the approximate magnitude of an earthquake in the US in 2019 be?", "_____no_output_____" ] ], [ [ "# predicting using the best fit model, by passing the year as 2019, and the country latitudes and longitudes for the US.\nx1 = [[2019,37.09,95.71]]\nbest_fit.predict(x1)", "_____no_output_____" ] ], [ [ "So, we can expect an earthquake of magnitude around 5.95 in the US next year.", "_____no_output_____" ], [ "### In what year can we expect a large earthquake in the US (magnitude > 7.0)?", "_____no_output_____" ], [ "To answer this question, we would need to train the model using Year as the output while the magnitude, and country coordinates act as the features. ", "_____no_output_____" ] ], [ [ "# training the model with year as the output label\nX = eq_df[['MAGNITUDE','LATITUDE','LONGITUDE']]\ny = eq_df['YEAR']\n# training and fitting the same model as previously\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=28)\nreg = RandomForestRegressor(random_state=30)\nreg.fit(X_train, y_train)\ngrid_obj = GridSearchCV(reg, parameters)\ngrid_fit = grid_obj.fit(X_train, y_train)\nbest_fit = grid_fit.best_estimator_\nbest_fit.score(X_test,y_test)\n# the score is a lot less than with Magnitude as the label", "_____no_output_____" ], [ "x2 = [[7.0,37.09,95.71]]\nbest_fit.predict(x2)", "_____no_output_____" ] ], [ [ "The problem with this prediction, is that the Year column is being fed in as integer instead of datetime. Trying to convert this column to datetime, gives an error since python does not seem to work well with negative dates(BC).", "_____no_output_____" ], [ "### Which country has historically had most number of earthquakes?", "_____no_output_____" ] ], [ [ "eq_df.groupby('COUNTRY').size().sort_values(ascending=False)", "_____no_output_____" ] ], [ [ "Grouping the dataset by Country, looking at the count and ordering by a descending number of the count, gives us the list above. \n\nChina leads the pack with 559 occurences in the list, which was slightly surprising, but I suspect it has something to do with how the territories were divided between China and Japan historically. ", "_____no_output_____" ], [ "<h2 id=\"i5\">VI. Conclusion </h2> ", "_____no_output_____" ], [ "Overall, I think this was a learning experience for me personally, where I could experiment with different machine learning algorithms and see how well they scaled with historical earthquake data. <br>\nWhat makes predicting earthquakes so challenging, in spite of having detailed historical data, is that it doesn't seem to follow any particular pattern precisely. Fault lines around the world do tend to slip in a somewhat cyclical pattern, but any predictions made using this, is likely to be a window of +-20 years at best, rather than a precise time. <br> This case is best highlighted when in 1981, scientists made a prediction saying the California fault line could trigger an earthquake in the next few months, and in order to monitor the forces before and after the event, huge stations and monitoring equipment was set up all over the place, with a significant investment. It turned out that the earthquake actually occured in 2001, 20 years after they were expecting it. <br>\nHowever, machine learning does open up a new perspective to tackle this challenge, and I believe that if we can finetune our algorithms to achieve a high degree of accuracy with the data, it can definitely lead to more accurate predictions, that might not pinpoint the occurrence down to the exact second, but can help reduce the uncertainty window down significantly. That would be a huge step forward. <br>\nFrom a human design perspective, the solution must present end users, with enough time to act upon their warnings. There is a system currently in Japan, that can sound an alarm before an earthquake is about to occur. This is apparently the time it takes for the waves to travel from the epicenter to the location of the alarm, which is usually less than 30 seconds. While better than nothing, the window is still too small for people to really act on it, and just provides enough time to duck underneath a sturdy table perhaps. <br>\nThe most promising research in my opinion, comes from trying to mimic the actual forces at play under the ground, in a lab setting, to produce acoustic signals that can then be used to train a machine learning algorithm. The signals produced just before the fault line releases that energy, has a particular sound signature to it, that can be used to identify and predict future occurrences. This method was highlighted in one of the papers referenced above, in the background section. <br>\n[Machine learning predicts earthquakes in a lab](https://www.cam.ac.uk/research/news/machine-learning-used-to-predict-earthquakes-in-a-lab-setting) <br>\nThere is a lot of exciting ongoing research on this topic, and I do hope one of these days we manage to make a breakthrough, and end one of the long standing mysteries of our planet.", "_____no_output_____" ], [ "<h2 id=\"i7\">VII. References </h2> ", "_____no_output_____" ], [ "[Machine learning predicts earthquakes in a lab](https://www.cam.ac.uk/research/news/machine-learning-used-to-predict-earthquakes-in-a-lab-setting) <br>\n[Hindukush earthquake magnitude prediction](https://www.researchgate.net/publication/307951466_Earthquake_magnitude_prediction_in_Hindukush_region_using_machine_learning_techniques) <br>\n[Analysis of soil radon data using decision trees](https://www.sciencedirect.com/science/article/pii/S0969804303000940)<br>\n[Using Neural Networks to predict earthquake magnitude](https://www.sciencedirect.com/science/article/pii/S0893608009000926)<br>\nhttps://www.ncbi.nlm.nih.gov/pmc/articles/PMC6033417/ <br>\nhttps://earthquake.usgs.gov/data/data.php#eq <br>\nhttps://arxiv.org/pdf/1702.05774.pdf <br>\nhttps://www.scientificamerican.com/article/can-artificial-intelligence-predict-earthquakes/", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cb6847398d167a8acdfe32617c7ddf012ec7e900
2,933
ipynb
Jupyter Notebook
01 Machine Learning/scikit_examples_jupyter/model_selection/plot_validation_curve.ipynb
alphaolomi/colab
19e4eb1bed56346dd18ba65638cda2d17a960d0c
[ "Apache-2.0" ]
null
null
null
01 Machine Learning/scikit_examples_jupyter/model_selection/plot_validation_curve.ipynb
alphaolomi/colab
19e4eb1bed56346dd18ba65638cda2d17a960d0c
[ "Apache-2.0" ]
null
null
null
01 Machine Learning/scikit_examples_jupyter/model_selection/plot_validation_curve.ipynb
alphaolomi/colab
19e4eb1bed56346dd18ba65638cda2d17a960d0c
[ "Apache-2.0" ]
null
null
null
54.314815
1,406
0.63314
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "\n# Plotting Validation Curves\n\n\nIn this plot you can see the training scores and validation scores of an SVM\nfor different values of the kernel parameter gamma. For very low values of\ngamma, you can see that both the training score and the validation score are\nlow. This is called underfitting. Medium values of gamma will result in high\nvalues for both scores, i.e. the classifier is performing fairly well. If gamma\nis too high, the classifier will overfit, which means that the training score\nis good but the validation score is poor.\n\n", "_____no_output_____" ] ], [ [ "print(__doc__)\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn.datasets import load_digits\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import validation_curve\n\ndigits = load_digits()\nX, y = digits.data, digits.target\n\nparam_range = np.logspace(-6, -1, 5)\ntrain_scores, test_scores = validation_curve(\n SVC(), X, y, param_name=\"gamma\", param_range=param_range,\n cv=5, scoring=\"accuracy\", n_jobs=1)\ntrain_scores_mean = np.mean(train_scores, axis=1)\ntrain_scores_std = np.std(train_scores, axis=1)\ntest_scores_mean = np.mean(test_scores, axis=1)\ntest_scores_std = np.std(test_scores, axis=1)\n\nplt.title(\"Validation Curve with SVM\")\nplt.xlabel(r\"$\\gamma$\")\nplt.ylabel(\"Score\")\nplt.ylim(0.0, 1.1)\nlw = 2\nplt.semilogx(param_range, train_scores_mean, label=\"Training score\",\n color=\"darkorange\", lw=lw)\nplt.fill_between(param_range, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.2,\n color=\"darkorange\", lw=lw)\nplt.semilogx(param_range, test_scores_mean, label=\"Cross-validation score\",\n color=\"navy\", lw=lw)\nplt.fill_between(param_range, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.2,\n color=\"navy\", lw=lw)\nplt.legend(loc=\"best\")\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ] ]
cb6848908946acda0cfcb7ba75651f06b52d283f
4,046
ipynb
Jupyter Notebook
ipynb/Italy.ipynb
RobertRosca/oscovida.github.io
d609949076e3f881e38ec674ecbf0887e9a2ec25
[ "CC-BY-4.0" ]
null
null
null
ipynb/Italy.ipynb
RobertRosca/oscovida.github.io
d609949076e3f881e38ec674ecbf0887e9a2ec25
[ "CC-BY-4.0" ]
null
null
null
ipynb/Italy.ipynb
RobertRosca/oscovida.github.io
d609949076e3f881e38ec674ecbf0887e9a2ec25
[ "CC-BY-4.0" ]
null
null
null
28.293706
159
0.50692
[ [ [ "# Italy\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/Italy.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(\"Italy\");", "_____no_output_____" ], [ "# load the data\ncases, deaths, region_label = get_country_data(\"Italy\")\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/Italy.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" ] ]
cb68782ba649ecec9dd9eae09a0be3f082aeb349
151,177
ipynb
Jupyter Notebook
math/PreCalculus.ipynb
tvaught/education
f96f12c178ab353957bf1ab26eeb302c4f272eea
[ "MIT" ]
null
null
null
math/PreCalculus.ipynb
tvaught/education
f96f12c178ab353957bf1ab26eeb302c4f272eea
[ "MIT" ]
null
null
null
math/PreCalculus.ipynb
tvaught/education
f96f12c178ab353957bf1ab26eeb302c4f272eea
[ "MIT" ]
null
null
null
154.104995
68,285
0.592709
[ [ [ "# Pre-Calculus Notebook", "_____no_output_____" ] ], [ [ "# Begin with some useful imports\nimport numpy as np\nimport pylab\nfrom fractions import Fraction\nfrom IPython.display import display, Math\nfrom sympy import init_printing, N, pi, sqrt, symbols, Symbol\nfrom sympy.abc import x, y, theta, phi\ninit_printing(use_latex='mathjax') # do this to allow sympy to print mathy stuff\n%matplotlib inline", "_____no_output_____" ] ], [ [ "## Trig Functions", "_____no_output_____" ], [ "This notebook will introduce basic trigonometric functions.\n\nGiven an angle, θ, there are two units used to indicate the measure of the angle: degrees and radians.", "_____no_output_____" ], [ "### First make a simple function to convert from degrees to radians", "_____no_output_____" ] ], [ [ "def deg_to_rad(angle, as_expr=False):\n \"\"\" Convert degrees to radians \n param: theta: degrees as a float or numpy array of values that can be cast to a float\n param: as_text: True/False output as text with multiple of 'π' (Default = False)\n \n The formula for this is:\n 2πθ/360°\n \n Note: it's usually bad form to allow a function argument to change an output type. Oh, well.\n \"\"\"\n radians = (angle * 2 * np.pi) / 360.0\n \n if as_expr:\n # note: this requires sympy\n radians = 2*pi*angle/360\n \n return radians", "_____no_output_____" ], [ "# Test our function\n# Note: normally you would print results, but with sympy expressions, \n# the `display` function of jupyter notebooks is used to print using MathJax.\n\ndisplay(deg_to_rad(210, as_expr=True))\ndisplay(deg_to_rad(360, as_expr=True))\n", "_____no_output_____" ] ], [ [ "### Now, let's make a list of angles around a unit circle and convert them to radians", "_____no_output_____" ] ], [ [ "base_angles = [0, 30, 45, 60]\nunit_circle_angles = []\nfor i in range(4):\n unit_circle_angles.extend(np.array(base_angles)+(i*90))\nunit_circle_angles.append(360)", "_____no_output_____" ], [ "# make a list of the angles converted to radians (list items are a sympy expression)\nunit_circle_angles_rad = [deg_to_rad(x, False) for x in unit_circle_angles]\nunit_circle_angles_rad_expr = [deg_to_rad(x, True) for x in unit_circle_angles]", "_____no_output_____" ], [ "unit_circle_angles_rad", "_____no_output_____" ], [ "unit_circle_angles_rad_expr", "_____no_output_____" ], [ "# show the list of angles in degrees\nunit_circle_angles", "_____no_output_____" ] ], [ [ "### So, what are radians", "_____no_output_____" ], [ "Radians are a unit of angle measure (similar to degrees). Radians correspond to the chord length that an angle sweeps out on the unit circle. A complete circle with a radius of 1 (a unit circle) has a circumference of $2\\pi$ (from the formula for circumference: $C = 2\\pi r$ )", "_____no_output_____" ], [ "Let's import some things to help us create a plot to see this in action.", "_____no_output_____" ] ], [ [ "from bokeh.plotting import figure, show, output_notebook\noutput_notebook()", "_____no_output_____" ] ], [ [ "If you were to map out our angle values on the circle drawn on a cartesian coordinate grid, it might look like this:", "_____no_output_____" ] ], [ [ "p = figure(plot_width=600, plot_height=600, match_aspect=True)\n\n\n# draw angle lines\nx = np.cos(unit_circle_angles_rad)\ny = np.sin(unit_circle_angles_rad)\norigin = np.zeros(x.shape)\n\n\nfor i in range(len(unit_circle_angles_rad)):\n #print (x[i], y[i])\n p.line((0, x[i]), (0, y[i]))\n\n# draw unit circle\np.circle(0,0, radius=1.0, color=\"white\", line_width=0.5, line_color='black',\n alpha=0.0, line_alpha=1.0)\n", "_____no_output_____" ], [ "show(p)", "_____no_output_____" ], [ "import bokeh", "_____no_output_____" ], [ "bokeh.__version__", "_____no_output_____" ], [ " from bokeh.plotting import figure, output_file, show\n\n output_file(\"circle_v1.html\")\n\n p = figure(plot_width=400, plot_height=400, match_aspect=True, tools='save')\n p.circle(0, 0, radius=1.0, fill_alpha=0)\n p.line((0, 1), (0, 0))\n p.line((0, -1), (0, 0))\n p.line((0, 0), (0, 1))\n p.line((0, 0), (0, -1))\n #p.rect(0, 0, 2, 2, fill_alpha=0)\n\n show(p)\n ", "_____no_output_____" ], [ "import sys, IPython, bokeh\nprint \"Python: \", sys.version\nprint \"IPython: \", IPython.__version__\nprint \"Bokeh: \", bokeh.__version__", "Python: 2.7.13 |Continuum Analytics, Inc.| (default, Dec 20 2016, 23:05:08) \n[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]\nIPython: 5.3.0\nBokeh: 0.12.10\n" ], [ "%reload_ext version_information", "_____no_output_____" ], [ "%version_information", "_____no_output_____" ], [ "from bokeh.plotting import figure, output_file, show\nfrom bokeh.layouts import layout\n\np1 = figure(match_aspect=True, title=\"Circle touches all 4 sides of square\")\n#p1.rect(0, 0, 300, 300, line_color='black')\np1.circle(x=0, y=0, radius=10, line_color='black', fill_color='grey',\n radius_units='data')\n\ndef draw_test_figure(aspect_scale=1, width=300, height=300):\n p = figure(\n plot_width=width,\n plot_height=height,\n match_aspect=True,\n aspect_scale=aspect_scale,\n title=\"Aspect scale = {0}\".format(aspect_scale),\n toolbar_location=None)\n p.circle([-1, +1, +1, -1], [-1, -1, +1, +1])\n return p\n\naspect_scales = [0.25, 0.5, 1, 2, 4]\np2s = [draw_test_figure(aspect_scale=i) for i in aspect_scales]\n\nsizes = [(100, 400), (200, 400), (400, 200), (400, 100)]\np3s = [draw_test_figure(width=a, height=b) for (a, b) in sizes]\n\nlayout = layout(children=[[p1], p2s, p3s])\n\noutput_file(\"aspect.html\")\nshow(layout)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb68983f919cd0d83fcece3d4a84f4bc593d21f7
137,366
ipynb
Jupyter Notebook
src/SentimentAnalysis/.ipynb_checkpoints/Distribution-checkpoint.ipynb
naseebth/Budget_Text_Analysis
cac0210b8b4b998fe798da92a9bbdd10eb1c4773
[ "MIT" ]
null
null
null
src/SentimentAnalysis/.ipynb_checkpoints/Distribution-checkpoint.ipynb
naseebth/Budget_Text_Analysis
cac0210b8b4b998fe798da92a9bbdd10eb1c4773
[ "MIT" ]
13
2019-09-24T14:32:26.000Z
2019-12-12T02:16:03.000Z
src/SentimentAnalysis/.ipynb_checkpoints/Distribution-checkpoint.ipynb
naseebth/Budget_Text_Analysis
cac0210b8b4b998fe798da92a9bbdd10eb1c4773
[ "MIT" ]
2
2020-01-04T07:32:56.000Z
2020-09-16T07:20:09.000Z
137.641283
20,780
0.861145
[ [ [ "import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nstyle.use('ggplot')\nfrom scipy.stats import norm, kde, kstest\nfrom scipy.stats import poisson\n\nfrom numpy import inf\nimport math\nfrom sklearn.cluster import KMeans\n", "_____no_output_____" ], [ "GCF08 = pd.read_csv(r\"C:\\unnati\\datascience\\project\\Repo\\new branch\\Budget_Text_Analysis\\util\\data\\structured\\emotion\\GC2008.csv\") # General Fund Summary 2008 #\nGCF08.drop(['Unnamed: 0'], axis=1,inplace=True)", "_____no_output_____" ], [ "GCF08_vc = GCF08.word.value_counts()\nGCF08_vc.head()", "_____no_output_____" ], [ "GCF08.sentiment = GCF08.sentiment.replace({\"Negative\": \"0\",\"Positive\": \"1\",\"Trust\" :\"2\",\"Sadness\":\"0\",\"Anticipation\":\"3\",\"Surprise\":\"4\",\"Fear\":\"5\",\"Joy\":\"6\",\"Anger\":\"7\",\"Disgust\":\"8\"})", "_____no_output_____" ], [ "GCF08.head(20)", "_____no_output_____" ], [ "GCF08.sentiment.value_counts()", "_____no_output_____" ], [ "GCF08['sentiment'] = pd.to_numeric(GCF08['sentiment'])\nGCF08.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1266 entries, 0 to 1265\nData columns (total 5 columns):\npage_number 1266 non-null int64\nword 1266 non-null object\nsent_count 1266 non-null int64\nsentiment 1266 non-null int64\ncategory 1266 non-null object\ndtypes: int64(3), object(2)\nmemory usage: 49.5+ KB\n" ], [ "sns.distplot(GCF08.sentiment)", "_____no_output_____" ], [ "#sen_density = kde.gaussian_kde(GCF08, bw_method=None)", "_____no_output_____" ], [ "sns.distplot(GCF08.sentiment.value_counts())", "_____no_output_____" ], [ "sns.distplot(GCF08_vc)", "_____no_output_____" ], [ "GCF08.drop(\"category\",axis=1,inplace=True)\nGCF08.drop(\"page_number\",axis=1,inplace=True)\nGCF08.drop(\"sent_count\",axis=1,inplace=True)", "_____no_output_____" ], [ "v = GCF08.to_numpy(copy=True)\nv", "_____no_output_____" ], [ "#clf = KMeans(n_clusters = 8)\n#clf.fit(GCF08)", "_____no_output_____" ], [ "#GCF08.sentiment = GCF08.sentiment.replace({\"Negative\": \"0\",\"Positive\": \"1\",\"Trust\" :\"1\",\"Sadness\":\"0\",\"Anticipation\":\"1\",\"Surprise\":\"1\",\"Fear\":\"0\",\"Joy\":\"1\",\"Anger\":\"0\",\"Disgust\":\"0\"})", "_____no_output_____" ], [ "GCF08['sentiment'] = pd.to_numeric(GCF08['sentiment'])\nGCF08.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1266 entries, 0 to 1265\nData columns (total 2 columns):\nword 1266 non-null object\nsentiment 1266 non-null int64\ndtypes: int64(1), object(1)\nmemory usage: 19.9+ KB\n" ], [ "sns.distplot(GCF08.sentiment,kde=False)", "_____no_output_____" ], [ "#sns.distplot(GCF08.sent_count)", "_____no_output_____" ], [ "GCF08.tail(20)", "_____no_output_____" ], [ "CCE = pd.read_csv(r\"C:\\unnati\\datascience\\project\\Repo\\new branch\\Budget_Text_Analysis\\util\\data\\FY2008\\structured\\emotion\\CharlotteCityEmotionDataFY08.csv\")\nCCE.drop(['Unnamed: 0'], axis=1,inplace=True)", "_____no_output_____" ], [ "CCE.sentiment = CCE.sentiment.replace({\"Negative\": \"0\",\"Positive\": \"1\",\"Trust\" :\"2\",\"Sadness\":\"0\",\"Anticipation\":\"3\",\"Surprise\":\"4\",\"Fear\":\"5\",\"Joy\":\"6\",\"Anger\":\"7\",\"Disgust\":\"8\"})", "_____no_output_____" ], [ "CCE.sentiment = pd.to_numeric(CCE['sentiment'])", "_____no_output_____" ], [ "sentiment_mean = CCE.sentiment.mean()\nsentiment_mean", "_____no_output_____" ], [ "sentiment_var = CCE.sentiment.var()\nsentiment_var", "_____no_output_____" ], [ "sns.distplot(CCE.sent_count)", "_____no_output_____" ], [ "sns.distplot(CCE['sentiment'])", "_____no_output_____" ], [ "#GCF08", "_____no_output_____" ], [ "k = np.arange(GCF08['sentiment'].max()+1)", "_____no_output_____" ], [ "sns.countplot(GCF08['sentiment'], order=k, color='g', alpha=0.5)", "_____no_output_____" ], [ "mlest = GCF08['sentiment'].mean()", "_____no_output_____" ], [ "plt.plot(k, poisson.pmf(k, mlest)*len(GCF08['sentiment']), 'go', markersize=12)", "_____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" ] ]
cb68b5c11ad1fe4367c8d64d517b665cfc9539c9
124,080
ipynb
Jupyter Notebook
UMSLHackRestAPI/research/researchv1.ipynb
trujivan/climate-impact-changes
609b8197b0ede1c1fdac3aa82b34e73e6f4526e3
[ "MIT" ]
1
2020-03-29T17:52:26.000Z
2020-03-29T17:52:26.000Z
UMSLHackRestAPI/research/researchv1.ipynb
trujivan/climate-impact-changes
609b8197b0ede1c1fdac3aa82b34e73e6f4526e3
[ "MIT" ]
6
2021-03-19T00:01:21.000Z
2021-09-22T18:37:17.000Z
UMSLHackRestAPI/research/researchv1.ipynb
trujivan/MAPredict
609b8197b0ede1c1fdac3aa82b34e73e6f4526e3
[ "MIT" ]
null
null
null
91.436993
27,996
0.767223
[ [ [ "#importing the packages\nimport pandas as pd\nimport numpy as np\nimport random \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\nimport joblib # for saving algorithm and preprocessing objects\nfrom sklearn.linear_model import LinearRegression", "_____no_output_____" ], [ "# uploading the dataset\ndf = pd.read_csv('pollution_us_2000_2016.csv')\ndf.head()", "_____no_output_____" ], [ "df.columns", "_____no_output_____" ], [ "#droping all the unnecessary features\ndf.drop(['Unnamed: 0','State Code', 'County Code', 'Site Num', 'Address', 'County', 'City',\n 'NO2 Units', 'O3 Units' ,'SO2 Units', 'CO Units',\n 'NO2 1st Max Hour', 'O3 1st Max Hour', 'SO2 1st Max Hour', 'CO 1st Max Hour'], axis=1, inplace=True)", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ], [ "df.describe()", "_____no_output_____" ], [ "#IQR range\nQ1 = df.quantile(0.25)\nQ3 = df.quantile(0.75)\nIQR = Q3 - Q1\nprint(IQR)", "NO2 Mean 11.963636\nNO2 1st Max Value 22.700000\nNO2 AQI 21.000000\nO3 Mean 0.016042\nO3 1st Max Value 0.019000\nO3 AQI 17.000000\nSO2 Mean 2.068478\nSO2 1st Max Value 4.200000\nSO2 AQI 8.000000\nCO Mean 0.283209\nCO 1st Max Value 0.508000\nCO AQI 6.000000\ndtype: float64\n" ], [ "#removing Outliers\ndf = df[~((df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR))).any(axis=1)]\ndf.shape", "_____no_output_____" ], [ "#encoding dates\ndf.insert(loc=1, column='Year', value=df['Date Local'].apply(lambda year: year.split('-')[0])) \ndf.drop('Date Local', axis=1, inplace=True)\ndf['Year']=df['Year'].astype('int')", "_____no_output_____" ], [ "#filling the FIRST Nan values with the means by the state\nfor i in df.columns[2:]:\n df[i] = df[i].fillna(df.groupby('State')[i].transform('mean'))", "_____no_output_____" ], [ "df[df[\"State\"]=='Missouri']['NO2 AQI'].plot(kind='density', subplots=True, layout=(1, 2), \n sharex=False, figsize=(10, 4));", "_____no_output_____" ], [ "plt.scatter(df[df['State']=='Missouri']['Year'], df[df['State']=='Missouri']['NO2 AQI']);", "_____no_output_____" ], [ "# grouped dataset\ndfG = df.groupby(['State', 'Year']).mean().reset_index()", "_____no_output_____" ], [ "dfG.shape", "_____no_output_____" ], [ "dfG.describe()", "_____no_output_____" ], [ "plt.scatter(dfG[dfG['State']=='Missouri']['Year'], dfG[dfG['State']=='Missouri']['NO2 AQI']);", "_____no_output_____" ], [ "#function for inserting a row\ndef Insert_row_(row_number, df, row_value): \n # Slice the upper half of the dataframe \n df1 = df[0:row_number] \n \n # Store the result of lower half of the dataframe \n df2 = df[row_number:] \n \n # Inser the row in the upper half dataframe \n df1.loc[row_number]=row_value \n \n # Concat the two dataframes \n df_result = pd.concat([df1, df2]) \n \n # Reassign the index labels \n df_result.index = [*range(df_result.shape[0])] \n \n # Return the updated dataframe \n return df_result ", "_____no_output_____" ], [ "#all the years\nyear_list = df['Year'].unique()\nprint(year_list)", "[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013\n 2014 2015 2016]\n" ], [ "#all the states\nstate_list = df['State'].unique()\nprint(state_list)", "['Arizona' 'California' 'Colorado' 'District Of Columbia' 'Florida'\n 'Illinois' 'Indiana' 'Kansas' 'Kentucky' 'Louisiana' 'Michigan'\n 'Missouri' 'New Jersey' 'New York' 'North Carolina' 'Oklahoma'\n 'Pennsylvania' 'Texas' 'Virginia' 'Massachusetts' 'Nevada'\n 'New Hampshire' 'South Carolina' 'Connecticut' 'Iowa' 'Maine' 'Maryland'\n 'Wisconsin' 'Country Of Mexico' 'Arkansas' 'Oregon' 'Wyoming'\n 'North Dakota' 'Tennessee' 'Idaho' 'Ohio' 'Georgia' 'Delaware' 'Hawaii'\n 'Minnesota' 'New Mexico' 'Rhode Island' 'South Dakota' 'Utah' 'Alabama'\n 'Washington' 'Alaska']\n" ], [ "# add more years with NaN values\nfor state in state_list:\n year_diff = set(year_list).difference(list(dfG[dfG['State']==state]['Year']))\n for i in year_diff:\n row_value = [state, i, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,np.nan,np.nan,np.nan,np.nan,np.nan] \n dfG = Insert_row_(random.randint(1,494), dfG, row_value) ", "c:\\users\\khud4\\appdata\\local\\programs\\python\\python36-32\\lib\\site-packages\\pandas\\core\\indexing.py:205: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n self._setitem_with_indexer(indexer, value)\n" ], [ "# fill Nan values with means by the state\nfor i in dfG.columns[2:]:\n dfG[i] = dfG[i].fillna(dfG.groupby('State')[i].transform('mean'))", "_____no_output_____" ], [ "total_AQI = dfG['NO2 AQI'] + dfG['SO2 AQI'] + \\\n dfG['CO AQI'] + dfG['O3 AQI']\ndfG.insert(loc=len(dfG.columns), column='Total_AQI', value=total_AQI)", "_____no_output_____" ], [ "dfG.head()", "_____no_output_____" ], [ "plt.scatter(dfG[dfG['State']=='Missouri']['Year'], dfG[dfG['State']=='Missouri']['Total_AQI']);", "_____no_output_____" ], [ "dfG[dfG[\"State\"]=='Missouri']['Total_AQI'].plot(kind='density', subplots=True, layout=(1, 2), \n sharex=False, figsize=(10, 4));", "_____no_output_____" ], [ "joblib.dump(dfG, \"./processed_data.joblib\", compress=True)", "_____no_output_____" ], [ "testing_Data = joblib.load(\"./processed_data.joblib\")\nstates = list(testing_Data['State'].unique())\nprint(states)", "['Alabama', 'Hawaii', 'Alaska', 'Arizona', 'Country Of Mexico', 'Arkansas', 'Minnesota', 'New Mexico', 'Kentucky', 'Rhode Island', 'Delaware', 'Ohio', 'Nevada', 'Wisconsin', 'Wyoming', 'Oregon', 'South Dakota', 'Washington', 'California', 'Tennessee', 'Michigan', 'Utah', 'North Dakota', 'Connecticut', 'Maine', 'Colorado', 'South Carolina', 'New Jersey', 'District Of Columbia', 'Idaho', 'Missouri', 'Virginia', 'Georgia', 'Florida', 'Illinois', 'New Hampshire', 'Indiana', 'Iowa', 'Kansas', 'Louisiana', 'Maryland', 'Massachusetts', 'New York', 'North Carolina', 'Oklahoma', 'Pennsylvania', 'Texas']\n" ], [ "from sklearn.linear_model import LinearRegression\n\ndef state_data(state, data, df):\n t = df[df['State']==state].sort_values(by='Year')\n \n clf = LinearRegression()\n clf.fit(t[['Year']], t[data])\n years = np.arange(2017, 2020, 1)\n tt = pd.DataFrame({'Year': years, data: clf.predict(years.reshape(-1, 1))})\n \n pd.concat([t, tt], sort=False).set_index('Year')[data].plot(color='red')\n t.set_index('Year')[data].plot(figsize=(15, 5), xticks=(np.arange(2000, 2020, 1)))\n \n return print(clf.predict(years.reshape(-1, 1)))", "_____no_output_____" ], [ "state_data('Missouri', 'NO2 AQI', testing_Data)", "[22.30133441 21.99118935 21.6810443 ]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb68cfc78529e08a049f10a9c8e1583a2d5690ae
305,330
ipynb
Jupyter Notebook
code/chap05.ipynb
MarcChevallier/ModSimPy
0e7fb9b7072c549fe7f6d47bdd3b5f1158542c04
[ "MIT" ]
1
2021-04-13T01:09:39.000Z
2021-04-13T01:09:39.000Z
code/chap05.ipynb
MarcChevallier/ModSimPy
0e7fb9b7072c549fe7f6d47bdd3b5f1158542c04
[ "MIT" ]
null
null
null
code/chap05.ipynb
MarcChevallier/ModSimPy
0e7fb9b7072c549fe7f6d47bdd3b5f1158542c04
[ "MIT" ]
1
2021-04-13T01:10:41.000Z
2021-04-13T01:10:41.000Z
164.421109
40,920
0.885743
[ [ [ "# Modeling and Simulation in Python\n\nChapter 5: Design\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n", "_____no_output_____" ] ], [ [ "# If you want the figures to appear in the notebook, \n# and you want to interact with them, use\n# %matplotlib notebook\n\n# If you want the figures to appear in the notebook, \n# and you don't want to interact with them, use\n# %matplotlib inline\n\n# If you want the figures to appear in separate windows, use\n# %matplotlib qt5\n\n# To switch from one to another, you have to select Kernel->Restart\n\n%matplotlib inline\n\nfrom modsim import *", "_____no_output_____" ] ], [ [ "### SIR implementation\n\nWe'll use a `State` object to represent the number or fraction of people in each compartment.", "_____no_output_____" ] ], [ [ "init = State(S=89, I=1, R=0)\ninit", "_____no_output_____" ] ], [ [ "To convert from number of people to fractions, we divide through by the total.", "_____no_output_____" ] ], [ [ "init /= sum(init)\ninit", "_____no_output_____" ] ], [ [ "`make_system` creates a `System` object with the given parameters.", "_____no_output_____" ] ], [ [ "def make_system(beta, gamma):\n \"\"\"Make a system object for the SIR model.\n \n beta: contact rate in days\n gamma: recovery rate in days\n \n returns: System object\n \"\"\"\n init = State(S=89, I=1, R=0)\n init /= sum(init)\n\n t0 = 0\n t_end = 7 * 14\n\n return System(init=init, t0=t0, t_end=t_end,\n beta=beta, gamma=gamma)", "_____no_output_____" ] ], [ [ "Here's an example with hypothetical values for `beta` and `gamma`.", "_____no_output_____" ] ], [ [ "tc = 3 # time between contacts in days \ntr = 4 # recovery time in days\n\nbeta = 1 / tc # contact rate in per day\ngamma = 1 / tr # recovery rate in per day\n\nsystem = make_system(beta, gamma)", "_____no_output_____" ] ], [ [ "The update function takes the state during the current time step and returns the state during the next time step.", "_____no_output_____" ] ], [ [ "def update1(state, system):\n \"\"\"Update the SIR model.\n \n state: State with variables S, I, R\n system: System with beta and gamma\n \n returns: State object\n \"\"\"\n s, i, r = state\n\n infected = system.beta * i * s \n recovered = system.gamma * i\n \n s -= infected\n i += infected - recovered\n r += recovered\n \n return State(S=s, I=i, R=r)", "_____no_output_____" ] ], [ [ "To run a single time step, we call it like this:", "_____no_output_____" ] ], [ [ "state = update1(init, system)\nstate", "_____no_output_____" ] ], [ [ "Now we can run a simulation by calling the update function for each time step.", "_____no_output_____" ] ], [ [ "def run_simulation(system, update_func):\n \"\"\"Runs a simulation of the system.\n \n system: System object\n update_func: function that updates state\n \n returns: State object for final state\n \"\"\"\n state = system.init\n \n for t in linrange(system.t0, system.t_end-1):\n state = update_func(state, system)\n \n return state", "_____no_output_____" ] ], [ [ "The result is the state of the system at `t_end`", "_____no_output_____" ] ], [ [ "run_simulation(system, update1)", "_____no_output_____" ] ], [ [ "**Exercise** Suppose the time between contacts is 4 days and the recovery time is 5 days. After 14 weeks, how many students, total, have been infected?\n\nHint: what is the change in `S` between the beginning and the end of the simulation?", "_____no_output_____" ] ], [ [ "# Solution goes here", "_____no_output_____" ] ], [ [ "### Using Series objects", "_____no_output_____" ], [ "If we want to store the state of the system at each time step, we can use one `TimeSeries` object for each state variable.", "_____no_output_____" ] ], [ [ "def run_simulation(system, update_func):\n \"\"\"Runs a simulation of the system.\n \n Add three Series objects to the System: S, I, R\n \n system: System object\n update_func: function that updates state\n \"\"\"\n S = TimeSeries()\n I = TimeSeries()\n R = TimeSeries()\n\n state = system.init\n t0 = system.t0\n S[t0], I[t0], R[t0] = state\n \n for t in linrange(system.t0, system.t_end-1):\n state = update_func(state, system)\n S[t+1], I[t+1], R[t+1] = state\n \n system.S = S\n system.I = I\n system.R = R", "_____no_output_____" ] ], [ [ "Here's how we call it.", "_____no_output_____" ] ], [ [ "tc = 3 # time between contacts in days \ntr = 4 # recovery time in days\n\nbeta = 1 / tc # contact rate in per day\ngamma = 1 / tr # recovery rate in per day\n\nsystem = make_system(beta, gamma)\nrun_simulation(system, update1)", "_____no_output_____" ] ], [ [ "And then we can plot the results.", "_____no_output_____" ] ], [ [ "def plot_results(S, I, R):\n \"\"\"Plot the results of a SIR model.\n \n S: TimeSeries\n I: TimeSeries\n R: TimeSeries\n \"\"\"\n plot(S, '--', color='blue', label='Susceptible')\n plot(I, '-', color='red', label='Infected')\n plot(R, ':', color='green', label='Recovered')\n decorate(xlabel='Time (days)',\n ylabel='Fraction of population')", "_____no_output_____" ] ], [ [ "Here's what they look like.", "_____no_output_____" ] ], [ [ "plot_results(system.S, system.I, system.R)\nsavefig('chap05-fig01.pdf')", "Saving figure to file chap05-fig01.pdf\n" ] ], [ [ "### Using a DataFrame", "_____no_output_____" ], [ "Instead of making three `TimeSeries` objects, we can use one `DataFrame`.\n\nWe have to use `loc` to indicate which row we want to assign the results to. But then Pandas does the right thing, matching up the state variables with the columns of the `DataFrame`.", "_____no_output_____" ] ], [ [ "def run_simulation(system, update_func):\n \"\"\"Runs a simulation of the system.\n \n Add a DataFrame to the System: results\n \n system: System object\n update_func: function that updates state\n \"\"\"\n frame = DataFrame(columns=system.init.index)\n frame.loc[system.t0] = system.init\n \n for t in linrange(system.t0, system.t_end-1):\n frame.loc[t+1] = update_func(frame.loc[t], system)\n \n system.results = frame", "_____no_output_____" ] ], [ [ "Here's how we run it, and what the result looks like.", "_____no_output_____" ] ], [ [ "tc = 3 # time between contacts in days \ntr = 4 # recovery time in days\n\nbeta = 1 / tc # contact rate in per day\ngamma = 1 / tr # recovery rate in per day\n\nsystem = make_system(beta, gamma)\nrun_simulation(system, update1)\nsystem.results.head()", "_____no_output_____" ] ], [ [ "We can extract the results and plot them.", "_____no_output_____" ] ], [ [ "frame = system.results\nplot_results(frame.S, frame.I, frame.R)", "_____no_output_____" ] ], [ [ "**Exercise** Suppose the time between contacts is 4 days and the recovery time is 5 days. Simulate this scenario for 14 days and plot the results.", "_____no_output_____" ] ], [ [ "# Solution goes here", "_____no_output_____" ] ], [ [ "### Metrics", "_____no_output_____" ], [ "Given the results, we can compute metrics that quantify whatever we are interested in, like the total number of sick students, for example.", "_____no_output_____" ] ], [ [ "def calc_total_infected(system):\n \"\"\"Fraction of population infected during the simulation.\n \n system: System object with results.\n \n returns: fraction of population\n \"\"\"\n frame = system.results\n return frame.S[system.t0] - frame.S[system.t_end]", "_____no_output_____" ] ], [ [ "Here's an example.|", "_____no_output_____" ] ], [ [ "system.beta = 0.333\nsystem.gamma = 0.25\nrun_simulation(system, update1)\nprint(system.beta, system.gamma, calc_total_infected(system))", "0.333 0.25 0.467162931836\n" ] ], [ [ "**Exercise:** Write functions that take a `System` object as a parameter, extract the `results` object from it, and compute the other metrics mentioned in the book:\n\n1. The fraction of students who are sick at the peak of the outbreak.\n\n2. The day the outbreak peaks.\n\n3. The fraction of students who are sick at the end of the semester.\n\nHint: If you have a `TimeSeries` called `I`, you can compute the largest value of the series like this:\n\n I.max()\n\nAnd the index of the largest value like this:\n\n I.idxmax()\n\nYou can read about these functions in the `Series` [documentation](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html).", "_____no_output_____" ] ], [ [ "# Solution goes here", "_____no_output_____" ], [ "# Solution goes here", "_____no_output_____" ], [ "# Solution goes here", "_____no_output_____" ], [ "# Solution goes here", "_____no_output_____" ], [ "# Solution goes here", "_____no_output_____" ], [ "# Solution goes here", "_____no_output_____" ] ], [ [ "### What if?", "_____no_output_____" ], [ "We can use this model to evaluate \"what if\" scenarios. For example, this function models the effect of immunization by moving some fraction of the population from S to R before the simulation starts.", "_____no_output_____" ] ], [ [ "def add_immunization(system, fraction):\n \"\"\"Immunize a fraction of the population.\n \n Moves the given fraction from S to R.\n \n system: System object\n fraction: number from 0 to 1\n \"\"\"\n system.init.S -= fraction\n system.init.R += fraction", "_____no_output_____" ] ], [ [ "Let's start again with the system we used in the previous sections.", "_____no_output_____" ] ], [ [ "tc = 3 # time between contacts in days \ntr = 4 # recovery time in days\n\nbeta = 1 / tc # contact rate in per day\ngamma = 1 / tr # recovery rate in per day\n\nsystem = make_system(beta, gamma)\nsystem.beta, system.gamma", "_____no_output_____" ] ], [ [ "And run the model without immunization.", "_____no_output_____" ] ], [ [ "run_simulation(system, update1)\ncalc_total_infected(system)", "_____no_output_____" ] ], [ [ "Now with 10% immunization.", "_____no_output_____" ] ], [ [ "system2 = make_system(beta, gamma)\nadd_immunization(system2, 0.1)\nrun_simulation(system2, update1)\ncalc_total_infected(system2)", "_____no_output_____" ] ], [ [ "10% immunization leads to a drop in infections of 16 percentage points.\n\nHere's what the time series looks like for S, with and without immunization.", "_____no_output_____" ] ], [ [ "plot(system.results.S, '-', label='No immunization')\nplot(system2.results.S, 'g--', label='10% immunization')\n\ndecorate(xlabel='Time (days)',\n ylabel='Fraction susceptible')\n\nsavefig('chap05-fig02.pdf')", "Saving figure to file chap05-fig02.pdf\n" ] ], [ [ "Now we can sweep through a range of values for the fraction of the population who are immunized.", "_____no_output_____" ] ], [ [ "immunize_array = linspace(0, 1, 11)\nfor fraction in immunize_array:\n system = make_system(beta, gamma)\n add_immunization(system, fraction)\n run_simulation(system, update1)\n print(fraction, calc_total_infected(system))", "0.0 0.468320811029\n0.1 0.30650802854\n0.2 0.161365457006\n0.3 0.0728155898425\n0.4 0.035520216753\n0.5 0.0196887157825\n0.6 0.0116220579983\n0.7 0.00683873780062\n0.8 0.00369649625371\n0.9 0.00148153267227\n1.0 -0.000161212109412\n" ] ], [ [ "This function does the same thing and stores the results in a `Sweep` object.", "_____no_output_____" ] ], [ [ "def sweep_immunity(immunize_array):\n \"\"\"Sweeps a range of values for immunity.\n \n immunize_array: array of fraction immunized\n \n returns: Sweep object\n \"\"\"\n sweep = SweepSeries()\n \n for fraction in immunize_array:\n system = make_system(beta, gamma)\n add_immunization(system, fraction)\n run_simulation(system, update1)\n sweep[fraction] = calc_total_infected(system)\n \n return sweep", "_____no_output_____" ] ], [ [ "Here's how we run it.", "_____no_output_____" ] ], [ [ "immunize_array = linspace(0, 1, 21)\ninfected_sweep = sweep_immunity(immunize_array)", "_____no_output_____" ] ], [ [ "And here's what the results look like.", "_____no_output_____" ] ], [ [ "plot(infected_sweep)\n\ndecorate(xlabel='Fraction immunized',\n ylabel='Total fraction infected',\n title='Fraction infected vs. immunization rate',\n legend=False)\n\nsavefig('chap05-fig03.pdf')", "Saving figure to file chap05-fig03.pdf\n" ] ], [ [ "If 40% of the population is immunized, less than 4% of the population gets sick.", "_____no_output_____" ], [ "### Logistic function", "_____no_output_____" ], [ "To model the effect of a hand-washing campaign, I'll use a [generalized logistic function](https://en.wikipedia.org/wiki/Generalised_logistic_function), which is a convenient function for modeling curves that have a generally sigmoid shape. The parameters of the GLF correspond to various features of the curve in a way that makes it easy to find a function that has the shape you want, based on data or background information about the scenario.", "_____no_output_____" ] ], [ [ "def logistic(x, A=0, B=1, C=1, M=0, K=1, Q=1, nu=1):\n \"\"\"Computes the generalize logistic function.\n \n A: controls the lower bound\n B: controls the steepness of the transition \n C: not all that useful, AFAIK\n M: controls the location of the transition\n K: controls the upper bound\n Q: shift the transition left or right\n nu: affects the symmetry of the transition\n \n returns: float or array\n \"\"\"\n exponent = -B * (x - M)\n denom = C + Q * exp(exponent)\n return A + (K-A) / denom ** (1/nu)", "_____no_output_____" ] ], [ [ "The following array represents the range of possible spending.", "_____no_output_____" ] ], [ [ "spending = linspace(0, 1200, 21)\nspending", "_____no_output_____" ] ], [ [ "`compute_factor` computes the reduction in `beta` for a given level of campaign spending.\n\n`M` is chosen so the transition happens around \\$500.\n\n`K` is the maximum reduction in `beta`, 20%.\n\n`B` is chosen by trial and error to yield a curve that seems feasible.", "_____no_output_____" ] ], [ [ "def compute_factor(spending):\n \"\"\"Reduction factor as a function of spending.\n \n spending: dollars from 0 to 1200\n \n returns: fractional reduction in beta\n \"\"\"\n return logistic(spending, M=500, K=0.2, B=0.01)", "_____no_output_____" ] ], [ [ "Here's what it looks like.", "_____no_output_____" ] ], [ [ "percent_reduction = compute_factor(spending) * 100\n\nplot(spending, percent_reduction)\n\ndecorate(xlabel='Hand-washing campaign spending (USD)',\n ylabel='Percent reduction in infection rate',\n title='Effect of hand washing on infection rate',\n legend=False)\n\nsavefig('chap05-fig04.pdf')", "Saving figure to file chap05-fig04.pdf\n" ] ], [ [ "**Exercise:** Modify the parameters `M`, `K`, and `B`, and see what effect they have on the shape of the curve. Read about the [generalized logistic function on Wikipedia](https://en.wikipedia.org/wiki/Generalised_logistic_function). Modify the other parameters and see what effect they have.", "_____no_output_____" ], [ "### Hand washing", "_____no_output_____" ], [ "Now we can model the effect of a hand-washing campaign by modifying `beta`", "_____no_output_____" ] ], [ [ "def add_hand_washing(system, spending):\n \"\"\"Modifies system to model the effect of hand washing.\n \n system: System object\n spending: campaign spending in USD\n \"\"\"\n factor = compute_factor(spending)\n system.beta *= (1 - factor)", "_____no_output_____" ] ], [ [ "Let's start with the same values of `beta` and `gamma` we've been using.", "_____no_output_____" ] ], [ [ "tc = 3 # time between contacts in days \ntr = 4 # recovery time in days\n\nbeta = 1 / tc # contact rate in per day\ngamma = 1 / tr # recovery rate in per day\n\nbeta, gamma", "_____no_output_____" ] ], [ [ "Now we can sweep different levels of campaign spending.", "_____no_output_____" ] ], [ [ "spending_array = linspace(0, 1200, 13)\n\nfor spending in spending_array:\n system = make_system(beta, gamma)\n add_hand_washing(system, spending)\n run_simulation(system, update1)\n print(spending, system.beta, calc_total_infected(system))", "0.0 0.332887143272 0.466770231236\n100.0 0.332134252669 0.464141650401\n200.0 0.330171608455 0.457217006313\n300.0 0.325386471865 0.439887202912\n400.0 0.315403905242 0.401630646271\n500.0 0.3 0.33703425949\n600.0 0.284596094758 0.267317030568\n700.0 0.274613528135 0.22184699046\n800.0 0.269828391545 0.200791598416\n900.0 0.267865747331 0.192392183393\n1000.0 0.267112856728 0.189213207818\n1100.0 0.26683150821 0.18803175228\n1200.0 0.266727403413 0.187595503995\n" ] ], [ [ "Here's a function that sweeps a range of spending and stores the results in a `Sweep` object.", "_____no_output_____" ] ], [ [ "def sweep_hand_washing(spending_array):\n \"\"\"Run simulations with a range of spending.\n \n spending_array: array of dollars from 0 to 1200\n \n returns: Sweep object\n \"\"\"\n sweep = SweepSeries()\n \n for spending in spending_array:\n system = make_system(beta, gamma)\n add_hand_washing(system, spending)\n run_simulation(system, update1)\n sweep[spending] = calc_total_infected(system)\n \n return sweep", "_____no_output_____" ] ], [ [ "Here's how we run it.", "_____no_output_____" ] ], [ [ "spending_array = linspace(0, 1200, 20)\ninfected_sweep = sweep_hand_washing(spending_array)", "_____no_output_____" ] ], [ [ "And here's what it looks like.", "_____no_output_____" ] ], [ [ "plot(infected_sweep)\n\ndecorate(xlabel='Hand-washing campaign spending (USD)',\n ylabel='Total fraction infected',\n title='Effect of hand washing on total infections',\n legend=False)\n\nsavefig('chap05-fig05.pdf')", "Saving figure to file chap05-fig05.pdf\n" ] ], [ [ "Now let's put it all together to make some public health spending decisions.", "_____no_output_____" ], [ "### Optimization", "_____no_output_____" ], [ "Suppose we have \\$1200 to spend on any combination of vaccines and a hand-washing campaign.", "_____no_output_____" ] ], [ [ "num_students = 90\nbudget = 1200\nprice_per_dose = 100\nmax_doses = int(budget / price_per_dose)\ndose_array = linrange(max_doses)\nmax_doses", "_____no_output_____" ] ], [ [ "We can sweep through a range of doses from, 0 to `max_doses`, model the effects of immunization and the hand-washing campaign, and run simulations.\n\nFor each scenario, we compute the fraction of students who get sick.", "_____no_output_____" ] ], [ [ "for doses in dose_array:\n fraction = doses / num_students\n spending = budget - doses * price_per_dose\n \n system = make_system(beta, gamma)\n add_immunization(system, fraction)\n add_hand_washing(system, spending)\n \n run_simulation(system, update1)\n print(doses, system.init.S, system.beta, calc_total_infected(system))", "0.0 0.988888888889 0.266727403413 0.187595503995\n1.0 0.977777777778 0.26683150821 0.174580718826\n2.0 0.966666666667 0.267112856728 0.162909838349\n3.0 0.955555555556 0.267865747331 0.153508349478\n4.0 0.944444444444 0.269828391545 0.148565092315\n5.0 0.933333333333 0.274613528135 0.152945950611\n6.0 0.922222222222 0.284596094758 0.174964415024\n7.0 0.911111111111 0.3 0.217343161684\n8.0 0.9 0.315403905242 0.259071044488\n9.0 0.888888888889 0.325386471865 0.278402884103\n10.0 0.877777777778 0.330171608455 0.277914534623\n11.0 0.866666666667 0.332134252669 0.267357496693\n12.0 0.855555555556 0.332887143272 0.252796945636\n" ] ], [ [ "The following function wraps that loop and stores the results in a `Sweep` object.", "_____no_output_____" ] ], [ [ "def sweep_doses(dose_array):\n \"\"\"Runs simulations with different doses and campaign spending.\n \n dose_array: range of values for number of vaccinations\n \n return: Sweep object with total number of infections \n \"\"\"\n sweep = SweepSeries()\n \n for doses in dose_array:\n fraction = doses / num_students\n spending = budget - doses * price_per_dose\n \n system = make_system(beta, gamma)\n add_immunization(system, fraction)\n add_hand_washing(system, spending)\n \n run_simulation(system, update1)\n sweep[doses] = calc_total_infected(system)\n\n return sweep", "_____no_output_____" ] ], [ [ "Now we can compute the number of infected students for each possible allocation of the budget.", "_____no_output_____" ] ], [ [ "infected_sweep = sweep_doses(dose_array)", "_____no_output_____" ] ], [ [ "And plot the results.", "_____no_output_____" ] ], [ [ "plot(infected_sweep)\n\ndecorate(xlabel='Doses of vaccine',\n ylabel='Total fraction infected',\n title='Total infections vs. doses',\n legend=False)\n\nsavefig('chap05-fig06.pdf')", "Saving figure to file chap05-fig06.pdf\n" ] ], [ [ "**Exercise:** Suppose the price of the vaccine drops to $50 per dose. How does that affect the optimal allocation of the spending?", "_____no_output_____" ], [ "**Exercise:** Suppose we have the option to quarantine infected students. For example, a student who feels ill might be moved to an infirmary, or a private dorm room, until they are no longer infectious.\n\nHow might you incorporate the effect of quarantine in the SIR model?", "_____no_output_____" ] ], [ [ "# Solution goes here", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "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", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
cb68d1b397d4d172eb281bbafac421949154c77a
345,434
ipynb
Jupyter Notebook
Model backlog/ResNet50/72 - ResNet50 - Regression - Finetune top 1st conv.ipynb
ThinkBricks/APTOS2019BlindnessDetection
e524fd69f83a1252710076c78b6a5236849cd885
[ "MIT" ]
23
2019-09-08T17:19:16.000Z
2022-02-02T16:20:09.000Z
Model backlog/ResNet50/72 - ResNet50 - Regression - Finetune top 1st conv.ipynb
ThinkBricks/APTOS2019BlindnessDetection
e524fd69f83a1252710076c78b6a5236849cd885
[ "MIT" ]
1
2020-03-10T18:42:12.000Z
2020-09-18T22:02:38.000Z
Model backlog/ResNet50/72 - ResNet50 - Regression - Finetune top 1st conv.ipynb
ThinkBricks/APTOS2019BlindnessDetection
e524fd69f83a1252710076c78b6a5236849cd885
[ "MIT" ]
16
2019-09-21T12:29:59.000Z
2022-03-21T00:42:26.000Z
169.247428
84,088
0.835028
[ [ [ "## Dependencies", "_____no_output_____" ] ], [ [ "import os\nimport cv2\nimport shutil\nimport random\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import class_weight\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, cohen_kappa_score\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.utils import to_categorical\nfrom keras import optimizers, applications\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau, Callback, LearningRateScheduler\nfrom keras.layers import Dense, Dropout, GlobalAveragePooling2D, Input\n\n# Set seeds to make the experiment more reproducible.\nfrom tensorflow import set_random_seed\ndef seed_everything(seed=0):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n set_random_seed(0)\nseed = 0\nseed_everything(seed)\n\n%matplotlib inline\nsns.set(style=\"whitegrid\")\nwarnings.filterwarnings(\"ignore\")", "Using TensorFlow backend.\n" ] ], [ [ "## Load data", "_____no_output_____" ] ], [ [ "hold_out_set = pd.read_csv('../input/aptos-data-split/hold-out.csv')\nX_train = hold_out_set[hold_out_set['set'] == 'train']\nX_val = hold_out_set[hold_out_set['set'] == 'validation']\ntest = pd.read_csv('../input/aptos2019-blindness-detection/test.csv')\nprint('Number of train samples: ', X_train.shape[0])\nprint('Number of validation samples: ', X_val.shape[0])\nprint('Number of test samples: ', test.shape[0])\n\n# Preprocecss data\nX_train[\"id_code\"] = X_train[\"id_code\"].apply(lambda x: x + \".png\")\nX_val[\"id_code\"] = X_val[\"id_code\"].apply(lambda x: x + \".png\")\ntest[\"id_code\"] = test[\"id_code\"].apply(lambda x: x + \".png\")\nX_train['diagnosis'] = X_train['diagnosis']\nX_val['diagnosis'] = X_val['diagnosis']\ndisplay(X_train.head())", "Number of train samples: 2929\nNumber of validation samples: 733\nNumber of test samples: 1928\n" ] ], [ [ "# Model parameters", "_____no_output_____" ] ], [ [ "# Model parameters\nBATCH_SIZE = 8\nEPOCHS = 40\nWARMUP_EPOCHS = 5\nLEARNING_RATE = 1e-4\nWARMUP_LEARNING_RATE = 1e-3\nHEIGHT = 224\nWIDTH = 224\nCHANNELS = 3\nES_PATIENCE = 5\nRLROP_PATIENCE = 3\nDECAY_DROP = 0.5", "_____no_output_____" ] ], [ [ "# Pre-procecess images", "_____no_output_____" ] ], [ [ "train_base_path = '../input/aptos2019-blindness-detection/train_images/'\ntest_base_path = '../input/aptos2019-blindness-detection/test_images/'\ntrain_dest_path = 'base_dir/train_images/'\nvalidation_dest_path = 'base_dir/validation_images/'\ntest_dest_path = 'base_dir/test_images/'\n\n# Making sure directories don't exist\nif os.path.exists(train_dest_path):\n shutil.rmtree(train_dest_path)\nif os.path.exists(validation_dest_path):\n shutil.rmtree(validation_dest_path)\nif os.path.exists(test_dest_path):\n shutil.rmtree(test_dest_path)\n \n# Creating train, validation and test directories\nos.makedirs(train_dest_path)\nos.makedirs(validation_dest_path)\nos.makedirs(test_dest_path)\n\ndef crop_image(img, tol=7):\n if img.ndim ==2:\n mask = img>tol\n return img[np.ix_(mask.any(1),mask.any(0))]\n elif img.ndim==3:\n gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n mask = gray_img>tol\n check_shape = img[:,:,0][np.ix_(mask.any(1),mask.any(0))].shape[0]\n if (check_shape == 0): # image is too dark so that we crop out everything,\n return img # return original image\n else:\n img1=img[:,:,0][np.ix_(mask.any(1),mask.any(0))]\n img2=img[:,:,1][np.ix_(mask.any(1),mask.any(0))]\n img3=img[:,:,2][np.ix_(mask.any(1),mask.any(0))]\n img = np.stack([img1,img2,img3],axis=-1)\n return img\n \ndef circle_crop(img): \n img = crop_image(img) \n \n height, width, depth = img.shape\n \n x = int(width/2)\n y = int(height/2)\n r = np.amin((x,y))\n \n circle_img = np.zeros((height, width), np.uint8)\n cv2.circle(circle_img, (x,y), int(r), 1, thickness=-1)\n img = cv2.bitwise_and(img, img, mask=circle_img)\n img = crop_image(img)\n \n return img \n \ndef preprocess_image(base_path, save_path, image_id, HEIGHT, WIDTH, sigmaX=10):\n image = cv2.imread(base_path + image_id)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = circle_crop(image)\n image = cv2.resize(image, (HEIGHT, WIDTH))\n image = cv2.addWeighted(image, 4, cv2.GaussianBlur(image, (0,0), sigmaX), -4 , 128)\n cv2.imwrite(save_path + image_id, image)\n \n# Pre-procecss train set\nfor i, image_id in enumerate(X_train['id_code']):\n preprocess_image(train_base_path, train_dest_path, image_id, HEIGHT, WIDTH)\n \n# Pre-procecss validation set\nfor i, image_id in enumerate(X_val['id_code']):\n preprocess_image(train_base_path, validation_dest_path, image_id, HEIGHT, WIDTH)\n \n# Pre-procecss test set\nfor i, image_id in enumerate(test['id_code']):\n preprocess_image(test_base_path, test_dest_path, image_id, HEIGHT, WIDTH)", "_____no_output_____" ] ], [ [ "# Data generator", "_____no_output_____" ] ], [ [ "datagen=ImageDataGenerator(rescale=1./255, \n rotation_range=360,\n horizontal_flip=True,\n vertical_flip=True,\n fill_mode='constant',\n cval=0.)\n\ntrain_generator=datagen.flow_from_dataframe(\n dataframe=X_train,\n directory=train_dest_path,\n x_col=\"id_code\",\n y_col=\"diagnosis\",\n class_mode=\"raw\",\n batch_size=BATCH_SIZE,\n target_size=(HEIGHT, WIDTH),\n seed=seed)\n\nvalid_generator=datagen.flow_from_dataframe(\n dataframe=X_val,\n directory=validation_dest_path,\n x_col=\"id_code\",\n y_col=\"diagnosis\",\n class_mode=\"raw\",\n batch_size=BATCH_SIZE,\n target_size=(HEIGHT, WIDTH),\n seed=seed)\n\ntest_generator=datagen.flow_from_dataframe( \n dataframe=test,\n directory=test_dest_path,\n x_col=\"id_code\",\n batch_size=1,\n class_mode=None,\n shuffle=False,\n target_size=(HEIGHT, WIDTH),\n seed=seed)", "Found 2929 validated image filenames.\nFound 733 validated image filenames.\nFound 1928 validated image filenames.\n" ] ], [ [ "# Model", "_____no_output_____" ] ], [ [ "def create_model(input_shape):\n input_tensor = Input(shape=input_shape)\n base_model = applications.ResNet50(weights=None, \n include_top=False,\n input_tensor=input_tensor)\n base_model.load_weights('../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5')\n\n x = GlobalAveragePooling2D()(base_model.output)\n x = Dropout(0.5)(x)\n x = Dense(2048, activation='relu')(x)\n x = Dropout(0.5)(x)\n final_output = Dense(1, activation='linear', name='final_output')(x)\n model = Model(input_tensor, final_output)\n \n return model", "_____no_output_____" ] ], [ [ "# Train top layers", "_____no_output_____" ] ], [ [ "model = create_model(input_shape=(HEIGHT, WIDTH, CHANNELS))\n\nfor layer in model.layers:\n layer.trainable = False\n\nfor i in range(-5, 0):\n model.layers[i].trainable = True\n \nmetric_list = [\"accuracy\"]\noptimizer = optimizers.Adam(lr=WARMUP_LEARNING_RATE)\nmodel.compile(optimizer=optimizer, loss='mean_squared_error', metrics=metric_list)\nmodel.summary()", "__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) (None, 224, 224, 3) 0 \n__________________________________________________________________________________________________\nconv1_pad (ZeroPadding2D) (None, 230, 230, 3) 0 input_1[0][0] \n__________________________________________________________________________________________________\nconv1 (Conv2D) (None, 112, 112, 64) 9472 conv1_pad[0][0] \n__________________________________________________________________________________________________\nbn_conv1 (BatchNormalization) (None, 112, 112, 64) 256 conv1[0][0] \n__________________________________________________________________________________________________\nactivation_1 (Activation) (None, 112, 112, 64) 0 bn_conv1[0][0] \n__________________________________________________________________________________________________\npool1_pad (ZeroPadding2D) (None, 114, 114, 64) 0 activation_1[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_1 (MaxPooling2D) (None, 56, 56, 64) 0 pool1_pad[0][0] \n__________________________________________________________________________________________________\nres2a_branch2a (Conv2D) (None, 56, 56, 64) 4160 max_pooling2d_1[0][0] \n__________________________________________________________________________________________________\nbn2a_branch2a (BatchNormalizati (None, 56, 56, 64) 256 res2a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_2 (Activation) (None, 56, 56, 64) 0 bn2a_branch2a[0][0] \n__________________________________________________________________________________________________\nres2a_branch2b (Conv2D) (None, 56, 56, 64) 36928 activation_2[0][0] \n__________________________________________________________________________________________________\nbn2a_branch2b (BatchNormalizati (None, 56, 56, 64) 256 res2a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_3 (Activation) (None, 56, 56, 64) 0 bn2a_branch2b[0][0] \n__________________________________________________________________________________________________\nres2a_branch2c (Conv2D) (None, 56, 56, 256) 16640 activation_3[0][0] \n__________________________________________________________________________________________________\nres2a_branch1 (Conv2D) (None, 56, 56, 256) 16640 max_pooling2d_1[0][0] \n__________________________________________________________________________________________________\nbn2a_branch2c (BatchNormalizati (None, 56, 56, 256) 1024 res2a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn2a_branch1 (BatchNormalizatio (None, 56, 56, 256) 1024 res2a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_1 (Add) (None, 56, 56, 256) 0 bn2a_branch2c[0][0] \n bn2a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_4 (Activation) (None, 56, 56, 256) 0 add_1[0][0] \n__________________________________________________________________________________________________\nres2b_branch2a (Conv2D) (None, 56, 56, 64) 16448 activation_4[0][0] \n__________________________________________________________________________________________________\nbn2b_branch2a (BatchNormalizati (None, 56, 56, 64) 256 res2b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_5 (Activation) (None, 56, 56, 64) 0 bn2b_branch2a[0][0] \n__________________________________________________________________________________________________\nres2b_branch2b (Conv2D) (None, 56, 56, 64) 36928 activation_5[0][0] \n__________________________________________________________________________________________________\nbn2b_branch2b (BatchNormalizati (None, 56, 56, 64) 256 res2b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_6 (Activation) (None, 56, 56, 64) 0 bn2b_branch2b[0][0] \n__________________________________________________________________________________________________\nres2b_branch2c (Conv2D) (None, 56, 56, 256) 16640 activation_6[0][0] \n__________________________________________________________________________________________________\nbn2b_branch2c (BatchNormalizati (None, 56, 56, 256) 1024 res2b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_2 (Add) (None, 56, 56, 256) 0 bn2b_branch2c[0][0] \n activation_4[0][0] \n__________________________________________________________________________________________________\nactivation_7 (Activation) (None, 56, 56, 256) 0 add_2[0][0] \n__________________________________________________________________________________________________\nres2c_branch2a (Conv2D) (None, 56, 56, 64) 16448 activation_7[0][0] \n__________________________________________________________________________________________________\nbn2c_branch2a (BatchNormalizati (None, 56, 56, 64) 256 res2c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_8 (Activation) (None, 56, 56, 64) 0 bn2c_branch2a[0][0] \n__________________________________________________________________________________________________\nres2c_branch2b (Conv2D) (None, 56, 56, 64) 36928 activation_8[0][0] \n__________________________________________________________________________________________________\nbn2c_branch2b (BatchNormalizati (None, 56, 56, 64) 256 res2c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_9 (Activation) (None, 56, 56, 64) 0 bn2c_branch2b[0][0] \n__________________________________________________________________________________________________\nres2c_branch2c (Conv2D) (None, 56, 56, 256) 16640 activation_9[0][0] \n__________________________________________________________________________________________________\nbn2c_branch2c (BatchNormalizati (None, 56, 56, 256) 1024 res2c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_3 (Add) (None, 56, 56, 256) 0 bn2c_branch2c[0][0] \n activation_7[0][0] \n__________________________________________________________________________________________________\nactivation_10 (Activation) (None, 56, 56, 256) 0 add_3[0][0] \n__________________________________________________________________________________________________\nres3a_branch2a (Conv2D) (None, 28, 28, 128) 32896 activation_10[0][0] \n__________________________________________________________________________________________________\nbn3a_branch2a (BatchNormalizati (None, 28, 28, 128) 512 res3a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_11 (Activation) (None, 28, 28, 128) 0 bn3a_branch2a[0][0] \n__________________________________________________________________________________________________\nres3a_branch2b (Conv2D) (None, 28, 28, 128) 147584 activation_11[0][0] \n__________________________________________________________________________________________________\nbn3a_branch2b (BatchNormalizati (None, 28, 28, 128) 512 res3a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_12 (Activation) (None, 28, 28, 128) 0 bn3a_branch2b[0][0] \n__________________________________________________________________________________________________\nres3a_branch2c (Conv2D) (None, 28, 28, 512) 66048 activation_12[0][0] \n__________________________________________________________________________________________________\nres3a_branch1 (Conv2D) (None, 28, 28, 512) 131584 activation_10[0][0] \n__________________________________________________________________________________________________\nbn3a_branch2c (BatchNormalizati (None, 28, 28, 512) 2048 res3a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn3a_branch1 (BatchNormalizatio (None, 28, 28, 512) 2048 res3a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_4 (Add) (None, 28, 28, 512) 0 bn3a_branch2c[0][0] \n bn3a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_13 (Activation) (None, 28, 28, 512) 0 add_4[0][0] \n__________________________________________________________________________________________________\nres3b_branch2a (Conv2D) (None, 28, 28, 128) 65664 activation_13[0][0] \n__________________________________________________________________________________________________\nbn3b_branch2a (BatchNormalizati (None, 28, 28, 128) 512 res3b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_14 (Activation) (None, 28, 28, 128) 0 bn3b_branch2a[0][0] \n__________________________________________________________________________________________________\nres3b_branch2b (Conv2D) (None, 28, 28, 128) 147584 activation_14[0][0] \n__________________________________________________________________________________________________\nbn3b_branch2b (BatchNormalizati (None, 28, 28, 128) 512 res3b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_15 (Activation) (None, 28, 28, 128) 0 bn3b_branch2b[0][0] \n__________________________________________________________________________________________________\nres3b_branch2c (Conv2D) (None, 28, 28, 512) 66048 activation_15[0][0] \n__________________________________________________________________________________________________\nbn3b_branch2c (BatchNormalizati (None, 28, 28, 512) 2048 res3b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_5 (Add) (None, 28, 28, 512) 0 bn3b_branch2c[0][0] \n activation_13[0][0] \n__________________________________________________________________________________________________\nactivation_16 (Activation) (None, 28, 28, 512) 0 add_5[0][0] \n__________________________________________________________________________________________________\nres3c_branch2a (Conv2D) (None, 28, 28, 128) 65664 activation_16[0][0] \n__________________________________________________________________________________________________\nbn3c_branch2a (BatchNormalizati (None, 28, 28, 128) 512 res3c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_17 (Activation) (None, 28, 28, 128) 0 bn3c_branch2a[0][0] \n__________________________________________________________________________________________________\nres3c_branch2b (Conv2D) (None, 28, 28, 128) 147584 activation_17[0][0] \n__________________________________________________________________________________________________\nbn3c_branch2b (BatchNormalizati (None, 28, 28, 128) 512 res3c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_18 (Activation) (None, 28, 28, 128) 0 bn3c_branch2b[0][0] \n__________________________________________________________________________________________________\nres3c_branch2c (Conv2D) (None, 28, 28, 512) 66048 activation_18[0][0] \n__________________________________________________________________________________________________\nbn3c_branch2c (BatchNormalizati (None, 28, 28, 512) 2048 res3c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_6 (Add) (None, 28, 28, 512) 0 bn3c_branch2c[0][0] \n activation_16[0][0] \n__________________________________________________________________________________________________\nactivation_19 (Activation) (None, 28, 28, 512) 0 add_6[0][0] \n__________________________________________________________________________________________________\nres3d_branch2a (Conv2D) (None, 28, 28, 128) 65664 activation_19[0][0] \n__________________________________________________________________________________________________\nbn3d_branch2a (BatchNormalizati (None, 28, 28, 128) 512 res3d_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_20 (Activation) (None, 28, 28, 128) 0 bn3d_branch2a[0][0] \n__________________________________________________________________________________________________\nres3d_branch2b (Conv2D) (None, 28, 28, 128) 147584 activation_20[0][0] \n__________________________________________________________________________________________________\nbn3d_branch2b (BatchNormalizati (None, 28, 28, 128) 512 res3d_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_21 (Activation) (None, 28, 28, 128) 0 bn3d_branch2b[0][0] \n__________________________________________________________________________________________________\nres3d_branch2c (Conv2D) (None, 28, 28, 512) 66048 activation_21[0][0] \n__________________________________________________________________________________________________\nbn3d_branch2c (BatchNormalizati (None, 28, 28, 512) 2048 res3d_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_7 (Add) (None, 28, 28, 512) 0 bn3d_branch2c[0][0] \n activation_19[0][0] \n__________________________________________________________________________________________________\nactivation_22 (Activation) (None, 28, 28, 512) 0 add_7[0][0] \n__________________________________________________________________________________________________\nres4a_branch2a (Conv2D) (None, 14, 14, 256) 131328 activation_22[0][0] \n__________________________________________________________________________________________________\nbn4a_branch2a (BatchNormalizati (None, 14, 14, 256) 1024 res4a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_23 (Activation) (None, 14, 14, 256) 0 bn4a_branch2a[0][0] \n__________________________________________________________________________________________________\nres4a_branch2b (Conv2D) (None, 14, 14, 256) 590080 activation_23[0][0] \n__________________________________________________________________________________________________\nbn4a_branch2b (BatchNormalizati (None, 14, 14, 256) 1024 res4a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_24 (Activation) (None, 14, 14, 256) 0 bn4a_branch2b[0][0] \n__________________________________________________________________________________________________\nres4a_branch2c (Conv2D) (None, 14, 14, 1024) 263168 activation_24[0][0] \n__________________________________________________________________________________________________\nres4a_branch1 (Conv2D) (None, 14, 14, 1024) 525312 activation_22[0][0] \n__________________________________________________________________________________________________\nbn4a_branch2c (BatchNormalizati (None, 14, 14, 1024) 4096 res4a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn4a_branch1 (BatchNormalizatio (None, 14, 14, 1024) 4096 res4a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_8 (Add) (None, 14, 14, 1024) 0 bn4a_branch2c[0][0] \n bn4a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_25 (Activation) (None, 14, 14, 1024) 0 add_8[0][0] \n__________________________________________________________________________________________________\nres4b_branch2a (Conv2D) (None, 14, 14, 256) 262400 activation_25[0][0] \n__________________________________________________________________________________________________\nbn4b_branch2a (BatchNormalizati (None, 14, 14, 256) 1024 res4b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_26 (Activation) (None, 14, 14, 256) 0 bn4b_branch2a[0][0] \n__________________________________________________________________________________________________\nres4b_branch2b (Conv2D) (None, 14, 14, 256) 590080 activation_26[0][0] \n__________________________________________________________________________________________________\nbn4b_branch2b (BatchNormalizati (None, 14, 14, 256) 1024 res4b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_27 (Activation) (None, 14, 14, 256) 0 bn4b_branch2b[0][0] \n__________________________________________________________________________________________________\nres4b_branch2c (Conv2D) (None, 14, 14, 1024) 263168 activation_27[0][0] \n__________________________________________________________________________________________________\nbn4b_branch2c (BatchNormalizati (None, 14, 14, 1024) 4096 res4b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_9 (Add) (None, 14, 14, 1024) 0 bn4b_branch2c[0][0] \n activation_25[0][0] \n__________________________________________________________________________________________________\nactivation_28 (Activation) (None, 14, 14, 1024) 0 add_9[0][0] \n__________________________________________________________________________________________________\nres4c_branch2a (Conv2D) (None, 14, 14, 256) 262400 activation_28[0][0] \n__________________________________________________________________________________________________\nbn4c_branch2a (BatchNormalizati (None, 14, 14, 256) 1024 res4c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_29 (Activation) (None, 14, 14, 256) 0 bn4c_branch2a[0][0] \n__________________________________________________________________________________________________\nres4c_branch2b (Conv2D) (None, 14, 14, 256) 590080 activation_29[0][0] \n__________________________________________________________________________________________________\nbn4c_branch2b (BatchNormalizati (None, 14, 14, 256) 1024 res4c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_30 (Activation) (None, 14, 14, 256) 0 bn4c_branch2b[0][0] \n__________________________________________________________________________________________________\nres4c_branch2c (Conv2D) (None, 14, 14, 1024) 263168 activation_30[0][0] \n__________________________________________________________________________________________________\nbn4c_branch2c (BatchNormalizati (None, 14, 14, 1024) 4096 res4c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_10 (Add) (None, 14, 14, 1024) 0 bn4c_branch2c[0][0] \n activation_28[0][0] \n__________________________________________________________________________________________________\nactivation_31 (Activation) (None, 14, 14, 1024) 0 add_10[0][0] \n__________________________________________________________________________________________________\nres4d_branch2a (Conv2D) (None, 14, 14, 256) 262400 activation_31[0][0] \n__________________________________________________________________________________________________\nbn4d_branch2a (BatchNormalizati (None, 14, 14, 256) 1024 res4d_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_32 (Activation) (None, 14, 14, 256) 0 bn4d_branch2a[0][0] \n__________________________________________________________________________________________________\nres4d_branch2b (Conv2D) (None, 14, 14, 256) 590080 activation_32[0][0] \n__________________________________________________________________________________________________\nbn4d_branch2b (BatchNormalizati (None, 14, 14, 256) 1024 res4d_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_33 (Activation) (None, 14, 14, 256) 0 bn4d_branch2b[0][0] \n__________________________________________________________________________________________________\nres4d_branch2c (Conv2D) (None, 14, 14, 1024) 263168 activation_33[0][0] \n__________________________________________________________________________________________________\nbn4d_branch2c (BatchNormalizati (None, 14, 14, 1024) 4096 res4d_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_11 (Add) (None, 14, 14, 1024) 0 bn4d_branch2c[0][0] \n activation_31[0][0] \n__________________________________________________________________________________________________\nactivation_34 (Activation) (None, 14, 14, 1024) 0 add_11[0][0] \n__________________________________________________________________________________________________\nres4e_branch2a (Conv2D) (None, 14, 14, 256) 262400 activation_34[0][0] \n__________________________________________________________________________________________________\nbn4e_branch2a (BatchNormalizati (None, 14, 14, 256) 1024 res4e_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_35 (Activation) (None, 14, 14, 256) 0 bn4e_branch2a[0][0] \n__________________________________________________________________________________________________\nres4e_branch2b (Conv2D) (None, 14, 14, 256) 590080 activation_35[0][0] \n__________________________________________________________________________________________________\nbn4e_branch2b (BatchNormalizati (None, 14, 14, 256) 1024 res4e_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_36 (Activation) (None, 14, 14, 256) 0 bn4e_branch2b[0][0] \n__________________________________________________________________________________________________\nres4e_branch2c (Conv2D) (None, 14, 14, 1024) 263168 activation_36[0][0] \n__________________________________________________________________________________________________\nbn4e_branch2c (BatchNormalizati (None, 14, 14, 1024) 4096 res4e_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_12 (Add) (None, 14, 14, 1024) 0 bn4e_branch2c[0][0] \n activation_34[0][0] \n__________________________________________________________________________________________________\nactivation_37 (Activation) (None, 14, 14, 1024) 0 add_12[0][0] \n__________________________________________________________________________________________________\nres4f_branch2a (Conv2D) (None, 14, 14, 256) 262400 activation_37[0][0] \n__________________________________________________________________________________________________\nbn4f_branch2a (BatchNormalizati (None, 14, 14, 256) 1024 res4f_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_38 (Activation) (None, 14, 14, 256) 0 bn4f_branch2a[0][0] \n__________________________________________________________________________________________________\nres4f_branch2b (Conv2D) (None, 14, 14, 256) 590080 activation_38[0][0] \n__________________________________________________________________________________________________\nbn4f_branch2b (BatchNormalizati (None, 14, 14, 256) 1024 res4f_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_39 (Activation) (None, 14, 14, 256) 0 bn4f_branch2b[0][0] \n__________________________________________________________________________________________________\nres4f_branch2c (Conv2D) (None, 14, 14, 1024) 263168 activation_39[0][0] \n__________________________________________________________________________________________________\nbn4f_branch2c (BatchNormalizati (None, 14, 14, 1024) 4096 res4f_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_13 (Add) (None, 14, 14, 1024) 0 bn4f_branch2c[0][0] \n activation_37[0][0] \n__________________________________________________________________________________________________\nactivation_40 (Activation) (None, 14, 14, 1024) 0 add_13[0][0] \n__________________________________________________________________________________________________\nres5a_branch2a (Conv2D) (None, 7, 7, 512) 524800 activation_40[0][0] \n__________________________________________________________________________________________________\nbn5a_branch2a (BatchNormalizati (None, 7, 7, 512) 2048 res5a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_41 (Activation) (None, 7, 7, 512) 0 bn5a_branch2a[0][0] \n__________________________________________________________________________________________________\nres5a_branch2b (Conv2D) (None, 7, 7, 512) 2359808 activation_41[0][0] \n__________________________________________________________________________________________________\nbn5a_branch2b (BatchNormalizati (None, 7, 7, 512) 2048 res5a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_42 (Activation) (None, 7, 7, 512) 0 bn5a_branch2b[0][0] \n__________________________________________________________________________________________________\nres5a_branch2c (Conv2D) (None, 7, 7, 2048) 1050624 activation_42[0][0] \n__________________________________________________________________________________________________\nres5a_branch1 (Conv2D) (None, 7, 7, 2048) 2099200 activation_40[0][0] \n__________________________________________________________________________________________________\nbn5a_branch2c (BatchNormalizati (None, 7, 7, 2048) 8192 res5a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn5a_branch1 (BatchNormalizatio (None, 7, 7, 2048) 8192 res5a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_14 (Add) (None, 7, 7, 2048) 0 bn5a_branch2c[0][0] \n bn5a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_43 (Activation) (None, 7, 7, 2048) 0 add_14[0][0] \n__________________________________________________________________________________________________\nres5b_branch2a (Conv2D) (None, 7, 7, 512) 1049088 activation_43[0][0] \n__________________________________________________________________________________________________\nbn5b_branch2a (BatchNormalizati (None, 7, 7, 512) 2048 res5b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_44 (Activation) (None, 7, 7, 512) 0 bn5b_branch2a[0][0] \n__________________________________________________________________________________________________\nres5b_branch2b (Conv2D) (None, 7, 7, 512) 2359808 activation_44[0][0] \n__________________________________________________________________________________________________\nbn5b_branch2b (BatchNormalizati (None, 7, 7, 512) 2048 res5b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_45 (Activation) (None, 7, 7, 512) 0 bn5b_branch2b[0][0] \n__________________________________________________________________________________________________\nres5b_branch2c (Conv2D) (None, 7, 7, 2048) 1050624 activation_45[0][0] \n__________________________________________________________________________________________________\nbn5b_branch2c (BatchNormalizati (None, 7, 7, 2048) 8192 res5b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_15 (Add) (None, 7, 7, 2048) 0 bn5b_branch2c[0][0] \n activation_43[0][0] \n__________________________________________________________________________________________________\nactivation_46 (Activation) (None, 7, 7, 2048) 0 add_15[0][0] \n__________________________________________________________________________________________________\nres5c_branch2a (Conv2D) (None, 7, 7, 512) 1049088 activation_46[0][0] \n__________________________________________________________________________________________________\nbn5c_branch2a (BatchNormalizati (None, 7, 7, 512) 2048 res5c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_47 (Activation) (None, 7, 7, 512) 0 bn5c_branch2a[0][0] \n__________________________________________________________________________________________________\nres5c_branch2b (Conv2D) (None, 7, 7, 512) 2359808 activation_47[0][0] \n__________________________________________________________________________________________________\nbn5c_branch2b (BatchNormalizati (None, 7, 7, 512) 2048 res5c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_48 (Activation) (None, 7, 7, 512) 0 bn5c_branch2b[0][0] \n__________________________________________________________________________________________________\nres5c_branch2c (Conv2D) (None, 7, 7, 2048) 1050624 activation_48[0][0] \n__________________________________________________________________________________________________\nbn5c_branch2c (BatchNormalizati (None, 7, 7, 2048) 8192 res5c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_16 (Add) (None, 7, 7, 2048) 0 bn5c_branch2c[0][0] \n activation_46[0][0] \n__________________________________________________________________________________________________\nactivation_49 (Activation) (None, 7, 7, 2048) 0 add_16[0][0] \n__________________________________________________________________________________________________\nglobal_average_pooling2d_1 (Glo (None, 2048) 0 activation_49[0][0] \n__________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 2048) 0 global_average_pooling2d_1[0][0] \n__________________________________________________________________________________________________\ndense_1 (Dense) (None, 2048) 4196352 dropout_1[0][0] \n__________________________________________________________________________________________________\ndropout_2 (Dropout) (None, 2048) 0 dense_1[0][0] \n__________________________________________________________________________________________________\nfinal_output (Dense) (None, 1) 2049 dropout_2[0][0] \n==================================================================================================\nTotal params: 27,786,113\nTrainable params: 4,198,401\nNon-trainable params: 23,587,712\n__________________________________________________________________________________________________\n" ], [ "STEP_SIZE_TRAIN = train_generator.n//train_generator.batch_size\nSTEP_SIZE_VALID = valid_generator.n//valid_generator.batch_size\n\nhistory_warmup = model.fit_generator(generator=train_generator,\n steps_per_epoch=STEP_SIZE_TRAIN,\n validation_data=valid_generator,\n validation_steps=STEP_SIZE_VALID,\n epochs=WARMUP_EPOCHS,\n verbose=1).history", "Epoch 1/5\n366/366 [==============================] - 46s 125ms/step - loss: 1.9607 - acc: 0.3429 - val_loss: 1.7618 - val_acc: 0.0975\nEpoch 2/5\n366/366 [==============================] - 39s 107ms/step - loss: 0.9850 - acc: 0.4583 - val_loss: 2.0307 - val_acc: 0.0924\nEpoch 3/5\n366/366 [==============================] - 39s 108ms/step - loss: 0.8719 - acc: 0.5027 - val_loss: 2.0844 - val_acc: 0.1090\nEpoch 4/5\n366/366 [==============================] - 39s 107ms/step - loss: 0.9367 - acc: 0.5027 - val_loss: 1.9153 - val_acc: 0.0979\nEpoch 5/5\n366/366 [==============================] - 40s 109ms/step - loss: 0.8845 - acc: 0.5000 - val_loss: 1.9451 - val_acc: 0.0979\n" ] ], [ [ "# Fine-tune the complete model (1st step)", "_____no_output_____" ] ], [ [ "for i in range(-15, 0):\n model.layers[i].trainable = True\n\nes = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE, restore_best_weights=True, verbose=1)\nrlrop = ReduceLROnPlateau(monitor='val_loss', mode='min', patience=RLROP_PATIENCE, factor=DECAY_DROP, min_lr=1e-6, verbose=1)\n\ncallback_list = [es, rlrop]\noptimizer = optimizers.Adam(lr=LEARNING_RATE)\nmodel.compile(optimizer=optimizer, loss='mean_squared_error', metrics=metric_list)\nmodel.summary()", "__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) (None, 224, 224, 3) 0 \n__________________________________________________________________________________________________\nconv1_pad (ZeroPadding2D) (None, 230, 230, 3) 0 input_1[0][0] \n__________________________________________________________________________________________________\nconv1 (Conv2D) (None, 112, 112, 64) 9472 conv1_pad[0][0] \n__________________________________________________________________________________________________\nbn_conv1 (BatchNormalization) (None, 112, 112, 64) 256 conv1[0][0] \n__________________________________________________________________________________________________\nactivation_1 (Activation) (None, 112, 112, 64) 0 bn_conv1[0][0] \n__________________________________________________________________________________________________\npool1_pad (ZeroPadding2D) (None, 114, 114, 64) 0 activation_1[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_1 (MaxPooling2D) (None, 56, 56, 64) 0 pool1_pad[0][0] \n__________________________________________________________________________________________________\nres2a_branch2a (Conv2D) (None, 56, 56, 64) 4160 max_pooling2d_1[0][0] \n__________________________________________________________________________________________________\nbn2a_branch2a (BatchNormalizati (None, 56, 56, 64) 256 res2a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_2 (Activation) (None, 56, 56, 64) 0 bn2a_branch2a[0][0] \n__________________________________________________________________________________________________\nres2a_branch2b (Conv2D) (None, 56, 56, 64) 36928 activation_2[0][0] \n__________________________________________________________________________________________________\nbn2a_branch2b (BatchNormalizati (None, 56, 56, 64) 256 res2a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_3 (Activation) (None, 56, 56, 64) 0 bn2a_branch2b[0][0] \n__________________________________________________________________________________________________\nres2a_branch2c (Conv2D) (None, 56, 56, 256) 16640 activation_3[0][0] \n__________________________________________________________________________________________________\nres2a_branch1 (Conv2D) (None, 56, 56, 256) 16640 max_pooling2d_1[0][0] \n__________________________________________________________________________________________________\nbn2a_branch2c (BatchNormalizati (None, 56, 56, 256) 1024 res2a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn2a_branch1 (BatchNormalizatio (None, 56, 56, 256) 1024 res2a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_1 (Add) (None, 56, 56, 256) 0 bn2a_branch2c[0][0] \n bn2a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_4 (Activation) (None, 56, 56, 256) 0 add_1[0][0] \n__________________________________________________________________________________________________\nres2b_branch2a (Conv2D) (None, 56, 56, 64) 16448 activation_4[0][0] \n__________________________________________________________________________________________________\nbn2b_branch2a (BatchNormalizati (None, 56, 56, 64) 256 res2b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_5 (Activation) (None, 56, 56, 64) 0 bn2b_branch2a[0][0] \n__________________________________________________________________________________________________\nres2b_branch2b (Conv2D) (None, 56, 56, 64) 36928 activation_5[0][0] \n__________________________________________________________________________________________________\nbn2b_branch2b (BatchNormalizati (None, 56, 56, 64) 256 res2b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_6 (Activation) (None, 56, 56, 64) 0 bn2b_branch2b[0][0] \n__________________________________________________________________________________________________\nres2b_branch2c (Conv2D) (None, 56, 56, 256) 16640 activation_6[0][0] \n__________________________________________________________________________________________________\nbn2b_branch2c (BatchNormalizati (None, 56, 56, 256) 1024 res2b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_2 (Add) (None, 56, 56, 256) 0 bn2b_branch2c[0][0] \n activation_4[0][0] \n__________________________________________________________________________________________________\nactivation_7 (Activation) (None, 56, 56, 256) 0 add_2[0][0] \n__________________________________________________________________________________________________\nres2c_branch2a (Conv2D) (None, 56, 56, 64) 16448 activation_7[0][0] \n__________________________________________________________________________________________________\nbn2c_branch2a (BatchNormalizati (None, 56, 56, 64) 256 res2c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_8 (Activation) (None, 56, 56, 64) 0 bn2c_branch2a[0][0] \n__________________________________________________________________________________________________\nres2c_branch2b (Conv2D) (None, 56, 56, 64) 36928 activation_8[0][0] \n__________________________________________________________________________________________________\nbn2c_branch2b (BatchNormalizati (None, 56, 56, 64) 256 res2c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_9 (Activation) (None, 56, 56, 64) 0 bn2c_branch2b[0][0] \n__________________________________________________________________________________________________\nres2c_branch2c (Conv2D) (None, 56, 56, 256) 16640 activation_9[0][0] \n__________________________________________________________________________________________________\nbn2c_branch2c (BatchNormalizati (None, 56, 56, 256) 1024 res2c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_3 (Add) (None, 56, 56, 256) 0 bn2c_branch2c[0][0] \n activation_7[0][0] \n__________________________________________________________________________________________________\nactivation_10 (Activation) (None, 56, 56, 256) 0 add_3[0][0] \n__________________________________________________________________________________________________\nres3a_branch2a (Conv2D) (None, 28, 28, 128) 32896 activation_10[0][0] \n__________________________________________________________________________________________________\nbn3a_branch2a (BatchNormalizati (None, 28, 28, 128) 512 res3a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_11 (Activation) (None, 28, 28, 128) 0 bn3a_branch2a[0][0] \n__________________________________________________________________________________________________\nres3a_branch2b (Conv2D) (None, 28, 28, 128) 147584 activation_11[0][0] \n__________________________________________________________________________________________________\nbn3a_branch2b (BatchNormalizati (None, 28, 28, 128) 512 res3a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_12 (Activation) (None, 28, 28, 128) 0 bn3a_branch2b[0][0] \n__________________________________________________________________________________________________\nres3a_branch2c (Conv2D) (None, 28, 28, 512) 66048 activation_12[0][0] \n__________________________________________________________________________________________________\nres3a_branch1 (Conv2D) (None, 28, 28, 512) 131584 activation_10[0][0] \n__________________________________________________________________________________________________\nbn3a_branch2c (BatchNormalizati (None, 28, 28, 512) 2048 res3a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn3a_branch1 (BatchNormalizatio (None, 28, 28, 512) 2048 res3a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_4 (Add) (None, 28, 28, 512) 0 bn3a_branch2c[0][0] \n bn3a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_13 (Activation) (None, 28, 28, 512) 0 add_4[0][0] \n__________________________________________________________________________________________________\nres3b_branch2a (Conv2D) (None, 28, 28, 128) 65664 activation_13[0][0] \n__________________________________________________________________________________________________\nbn3b_branch2a (BatchNormalizati (None, 28, 28, 128) 512 res3b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_14 (Activation) (None, 28, 28, 128) 0 bn3b_branch2a[0][0] \n__________________________________________________________________________________________________\nres3b_branch2b (Conv2D) (None, 28, 28, 128) 147584 activation_14[0][0] \n__________________________________________________________________________________________________\nbn3b_branch2b (BatchNormalizati (None, 28, 28, 128) 512 res3b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_15 (Activation) (None, 28, 28, 128) 0 bn3b_branch2b[0][0] \n__________________________________________________________________________________________________\nres3b_branch2c (Conv2D) (None, 28, 28, 512) 66048 activation_15[0][0] \n__________________________________________________________________________________________________\nbn3b_branch2c (BatchNormalizati (None, 28, 28, 512) 2048 res3b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_5 (Add) (None, 28, 28, 512) 0 bn3b_branch2c[0][0] \n activation_13[0][0] \n__________________________________________________________________________________________________\nactivation_16 (Activation) (None, 28, 28, 512) 0 add_5[0][0] \n__________________________________________________________________________________________________\nres3c_branch2a (Conv2D) (None, 28, 28, 128) 65664 activation_16[0][0] \n__________________________________________________________________________________________________\nbn3c_branch2a (BatchNormalizati (None, 28, 28, 128) 512 res3c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_17 (Activation) (None, 28, 28, 128) 0 bn3c_branch2a[0][0] \n__________________________________________________________________________________________________\nres3c_branch2b (Conv2D) (None, 28, 28, 128) 147584 activation_17[0][0] \n__________________________________________________________________________________________________\nbn3c_branch2b (BatchNormalizati (None, 28, 28, 128) 512 res3c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_18 (Activation) (None, 28, 28, 128) 0 bn3c_branch2b[0][0] \n__________________________________________________________________________________________________\nres3c_branch2c (Conv2D) (None, 28, 28, 512) 66048 activation_18[0][0] \n__________________________________________________________________________________________________\nbn3c_branch2c (BatchNormalizati (None, 28, 28, 512) 2048 res3c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_6 (Add) (None, 28, 28, 512) 0 bn3c_branch2c[0][0] \n activation_16[0][0] \n__________________________________________________________________________________________________\nactivation_19 (Activation) (None, 28, 28, 512) 0 add_6[0][0] \n__________________________________________________________________________________________________\nres3d_branch2a (Conv2D) (None, 28, 28, 128) 65664 activation_19[0][0] \n__________________________________________________________________________________________________\nbn3d_branch2a (BatchNormalizati (None, 28, 28, 128) 512 res3d_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_20 (Activation) (None, 28, 28, 128) 0 bn3d_branch2a[0][0] \n__________________________________________________________________________________________________\nres3d_branch2b (Conv2D) (None, 28, 28, 128) 147584 activation_20[0][0] \n__________________________________________________________________________________________________\nbn3d_branch2b (BatchNormalizati (None, 28, 28, 128) 512 res3d_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_21 (Activation) (None, 28, 28, 128) 0 bn3d_branch2b[0][0] \n__________________________________________________________________________________________________\nres3d_branch2c (Conv2D) (None, 28, 28, 512) 66048 activation_21[0][0] \n__________________________________________________________________________________________________\nbn3d_branch2c (BatchNormalizati (None, 28, 28, 512) 2048 res3d_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_7 (Add) (None, 28, 28, 512) 0 bn3d_branch2c[0][0] \n activation_19[0][0] \n__________________________________________________________________________________________________\nactivation_22 (Activation) (None, 28, 28, 512) 0 add_7[0][0] \n__________________________________________________________________________________________________\nres4a_branch2a (Conv2D) (None, 14, 14, 256) 131328 activation_22[0][0] \n__________________________________________________________________________________________________\nbn4a_branch2a (BatchNormalizati (None, 14, 14, 256) 1024 res4a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_23 (Activation) (None, 14, 14, 256) 0 bn4a_branch2a[0][0] \n__________________________________________________________________________________________________\nres4a_branch2b (Conv2D) (None, 14, 14, 256) 590080 activation_23[0][0] \n__________________________________________________________________________________________________\nbn4a_branch2b (BatchNormalizati (None, 14, 14, 256) 1024 res4a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_24 (Activation) (None, 14, 14, 256) 0 bn4a_branch2b[0][0] \n__________________________________________________________________________________________________\nres4a_branch2c (Conv2D) (None, 14, 14, 1024) 263168 activation_24[0][0] \n__________________________________________________________________________________________________\nres4a_branch1 (Conv2D) (None, 14, 14, 1024) 525312 activation_22[0][0] \n__________________________________________________________________________________________________\nbn4a_branch2c (BatchNormalizati (None, 14, 14, 1024) 4096 res4a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn4a_branch1 (BatchNormalizatio (None, 14, 14, 1024) 4096 res4a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_8 (Add) (None, 14, 14, 1024) 0 bn4a_branch2c[0][0] \n bn4a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_25 (Activation) (None, 14, 14, 1024) 0 add_8[0][0] \n__________________________________________________________________________________________________\nres4b_branch2a (Conv2D) (None, 14, 14, 256) 262400 activation_25[0][0] \n__________________________________________________________________________________________________\nbn4b_branch2a (BatchNormalizati (None, 14, 14, 256) 1024 res4b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_26 (Activation) (None, 14, 14, 256) 0 bn4b_branch2a[0][0] \n__________________________________________________________________________________________________\nres4b_branch2b (Conv2D) (None, 14, 14, 256) 590080 activation_26[0][0] \n__________________________________________________________________________________________________\nbn4b_branch2b (BatchNormalizati (None, 14, 14, 256) 1024 res4b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_27 (Activation) (None, 14, 14, 256) 0 bn4b_branch2b[0][0] \n__________________________________________________________________________________________________\nres4b_branch2c (Conv2D) (None, 14, 14, 1024) 263168 activation_27[0][0] \n__________________________________________________________________________________________________\nbn4b_branch2c (BatchNormalizati (None, 14, 14, 1024) 4096 res4b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_9 (Add) (None, 14, 14, 1024) 0 bn4b_branch2c[0][0] \n activation_25[0][0] \n__________________________________________________________________________________________________\nactivation_28 (Activation) (None, 14, 14, 1024) 0 add_9[0][0] \n__________________________________________________________________________________________________\nres4c_branch2a (Conv2D) (None, 14, 14, 256) 262400 activation_28[0][0] \n__________________________________________________________________________________________________\nbn4c_branch2a (BatchNormalizati (None, 14, 14, 256) 1024 res4c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_29 (Activation) (None, 14, 14, 256) 0 bn4c_branch2a[0][0] \n__________________________________________________________________________________________________\nres4c_branch2b (Conv2D) (None, 14, 14, 256) 590080 activation_29[0][0] \n__________________________________________________________________________________________________\nbn4c_branch2b (BatchNormalizati (None, 14, 14, 256) 1024 res4c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_30 (Activation) (None, 14, 14, 256) 0 bn4c_branch2b[0][0] \n__________________________________________________________________________________________________\nres4c_branch2c (Conv2D) (None, 14, 14, 1024) 263168 activation_30[0][0] \n__________________________________________________________________________________________________\nbn4c_branch2c (BatchNormalizati (None, 14, 14, 1024) 4096 res4c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_10 (Add) (None, 14, 14, 1024) 0 bn4c_branch2c[0][0] \n activation_28[0][0] \n__________________________________________________________________________________________________\nactivation_31 (Activation) (None, 14, 14, 1024) 0 add_10[0][0] \n__________________________________________________________________________________________________\nres4d_branch2a (Conv2D) (None, 14, 14, 256) 262400 activation_31[0][0] \n__________________________________________________________________________________________________\nbn4d_branch2a (BatchNormalizati (None, 14, 14, 256) 1024 res4d_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_32 (Activation) (None, 14, 14, 256) 0 bn4d_branch2a[0][0] \n__________________________________________________________________________________________________\nres4d_branch2b (Conv2D) (None, 14, 14, 256) 590080 activation_32[0][0] \n__________________________________________________________________________________________________\nbn4d_branch2b (BatchNormalizati (None, 14, 14, 256) 1024 res4d_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_33 (Activation) (None, 14, 14, 256) 0 bn4d_branch2b[0][0] \n__________________________________________________________________________________________________\nres4d_branch2c (Conv2D) (None, 14, 14, 1024) 263168 activation_33[0][0] \n__________________________________________________________________________________________________\nbn4d_branch2c (BatchNormalizati (None, 14, 14, 1024) 4096 res4d_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_11 (Add) (None, 14, 14, 1024) 0 bn4d_branch2c[0][0] \n activation_31[0][0] \n__________________________________________________________________________________________________\nactivation_34 (Activation) (None, 14, 14, 1024) 0 add_11[0][0] \n__________________________________________________________________________________________________\nres4e_branch2a (Conv2D) (None, 14, 14, 256) 262400 activation_34[0][0] \n__________________________________________________________________________________________________\nbn4e_branch2a (BatchNormalizati (None, 14, 14, 256) 1024 res4e_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_35 (Activation) (None, 14, 14, 256) 0 bn4e_branch2a[0][0] \n__________________________________________________________________________________________________\nres4e_branch2b (Conv2D) (None, 14, 14, 256) 590080 activation_35[0][0] \n__________________________________________________________________________________________________\nbn4e_branch2b (BatchNormalizati (None, 14, 14, 256) 1024 res4e_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_36 (Activation) (None, 14, 14, 256) 0 bn4e_branch2b[0][0] \n__________________________________________________________________________________________________\nres4e_branch2c (Conv2D) (None, 14, 14, 1024) 263168 activation_36[0][0] \n__________________________________________________________________________________________________\nbn4e_branch2c (BatchNormalizati (None, 14, 14, 1024) 4096 res4e_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_12 (Add) (None, 14, 14, 1024) 0 bn4e_branch2c[0][0] \n activation_34[0][0] \n__________________________________________________________________________________________________\nactivation_37 (Activation) (None, 14, 14, 1024) 0 add_12[0][0] \n__________________________________________________________________________________________________\nres4f_branch2a (Conv2D) (None, 14, 14, 256) 262400 activation_37[0][0] \n__________________________________________________________________________________________________\nbn4f_branch2a (BatchNormalizati (None, 14, 14, 256) 1024 res4f_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_38 (Activation) (None, 14, 14, 256) 0 bn4f_branch2a[0][0] \n__________________________________________________________________________________________________\nres4f_branch2b (Conv2D) (None, 14, 14, 256) 590080 activation_38[0][0] \n__________________________________________________________________________________________________\nbn4f_branch2b (BatchNormalizati (None, 14, 14, 256) 1024 res4f_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_39 (Activation) (None, 14, 14, 256) 0 bn4f_branch2b[0][0] \n__________________________________________________________________________________________________\nres4f_branch2c (Conv2D) (None, 14, 14, 1024) 263168 activation_39[0][0] \n__________________________________________________________________________________________________\nbn4f_branch2c (BatchNormalizati (None, 14, 14, 1024) 4096 res4f_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_13 (Add) (None, 14, 14, 1024) 0 bn4f_branch2c[0][0] \n activation_37[0][0] \n__________________________________________________________________________________________________\nactivation_40 (Activation) (None, 14, 14, 1024) 0 add_13[0][0] \n__________________________________________________________________________________________________\nres5a_branch2a (Conv2D) (None, 7, 7, 512) 524800 activation_40[0][0] \n__________________________________________________________________________________________________\nbn5a_branch2a (BatchNormalizati (None, 7, 7, 512) 2048 res5a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_41 (Activation) (None, 7, 7, 512) 0 bn5a_branch2a[0][0] \n__________________________________________________________________________________________________\nres5a_branch2b (Conv2D) (None, 7, 7, 512) 2359808 activation_41[0][0] \n__________________________________________________________________________________________________\nbn5a_branch2b (BatchNormalizati (None, 7, 7, 512) 2048 res5a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_42 (Activation) (None, 7, 7, 512) 0 bn5a_branch2b[0][0] \n__________________________________________________________________________________________________\nres5a_branch2c (Conv2D) (None, 7, 7, 2048) 1050624 activation_42[0][0] \n__________________________________________________________________________________________________\nres5a_branch1 (Conv2D) (None, 7, 7, 2048) 2099200 activation_40[0][0] \n__________________________________________________________________________________________________\nbn5a_branch2c (BatchNormalizati (None, 7, 7, 2048) 8192 res5a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn5a_branch1 (BatchNormalizatio (None, 7, 7, 2048) 8192 res5a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_14 (Add) (None, 7, 7, 2048) 0 bn5a_branch2c[0][0] \n bn5a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_43 (Activation) (None, 7, 7, 2048) 0 add_14[0][0] \n__________________________________________________________________________________________________\nres5b_branch2a (Conv2D) (None, 7, 7, 512) 1049088 activation_43[0][0] \n__________________________________________________________________________________________________\nbn5b_branch2a (BatchNormalizati (None, 7, 7, 512) 2048 res5b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_44 (Activation) (None, 7, 7, 512) 0 bn5b_branch2a[0][0] \n__________________________________________________________________________________________________\nres5b_branch2b (Conv2D) (None, 7, 7, 512) 2359808 activation_44[0][0] \n__________________________________________________________________________________________________\nbn5b_branch2b (BatchNormalizati (None, 7, 7, 512) 2048 res5b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_45 (Activation) (None, 7, 7, 512) 0 bn5b_branch2b[0][0] \n__________________________________________________________________________________________________\nres5b_branch2c (Conv2D) (None, 7, 7, 2048) 1050624 activation_45[0][0] \n__________________________________________________________________________________________________\nbn5b_branch2c (BatchNormalizati (None, 7, 7, 2048) 8192 res5b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_15 (Add) (None, 7, 7, 2048) 0 bn5b_branch2c[0][0] \n activation_43[0][0] \n__________________________________________________________________________________________________\nactivation_46 (Activation) (None, 7, 7, 2048) 0 add_15[0][0] \n__________________________________________________________________________________________________\nres5c_branch2a (Conv2D) (None, 7, 7, 512) 1049088 activation_46[0][0] \n__________________________________________________________________________________________________\nbn5c_branch2a (BatchNormalizati (None, 7, 7, 512) 2048 res5c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_47 (Activation) (None, 7, 7, 512) 0 bn5c_branch2a[0][0] \n__________________________________________________________________________________________________\nres5c_branch2b (Conv2D) (None, 7, 7, 512) 2359808 activation_47[0][0] \n__________________________________________________________________________________________________\nbn5c_branch2b (BatchNormalizati (None, 7, 7, 512) 2048 res5c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_48 (Activation) (None, 7, 7, 512) 0 bn5c_branch2b[0][0] \n__________________________________________________________________________________________________\nres5c_branch2c (Conv2D) (None, 7, 7, 2048) 1050624 activation_48[0][0] \n__________________________________________________________________________________________________\nbn5c_branch2c (BatchNormalizati (None, 7, 7, 2048) 8192 res5c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_16 (Add) (None, 7, 7, 2048) 0 bn5c_branch2c[0][0] \n activation_46[0][0] \n__________________________________________________________________________________________________\nactivation_49 (Activation) (None, 7, 7, 2048) 0 add_16[0][0] \n__________________________________________________________________________________________________\nglobal_average_pooling2d_1 (Glo (None, 2048) 0 activation_49[0][0] \n__________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 2048) 0 global_average_pooling2d_1[0][0] \n__________________________________________________________________________________________________\ndense_1 (Dense) (None, 2048) 4196352 dropout_1[0][0] \n__________________________________________________________________________________________________\ndropout_2 (Dropout) (None, 2048) 0 dense_1[0][0] \n__________________________________________________________________________________________________\nfinal_output (Dense) (None, 1) 2049 dropout_2[0][0] \n==================================================================================================\nTotal params: 27,786,113\nTrainable params: 8,664,065\nNon-trainable params: 19,122,048\n__________________________________________________________________________________________________\n" ], [ "history_finetunning = model.fit_generator(generator=train_generator,\n steps_per_epoch=STEP_SIZE_TRAIN,\n validation_data=valid_generator,\n validation_steps=STEP_SIZE_VALID,\n epochs=int(EPOCHS*0.8),\n callbacks=callback_list,\n verbose=1).history", "Epoch 1/32\n366/366 [==============================] - 43s 119ms/step - loss: 0.7625 - acc: 0.5410 - val_loss: 1.9997 - val_acc: 0.1021\nEpoch 2/32\n366/366 [==============================] - 40s 109ms/step - loss: 0.6287 - acc: 0.6045 - val_loss: 2.0249 - val_acc: 0.0938\nEpoch 3/32\n366/366 [==============================] - 40s 108ms/step - loss: 0.5787 - acc: 0.6199 - val_loss: 1.7465 - val_acc: 0.0952\nEpoch 4/32\n366/366 [==============================] - 40s 110ms/step - loss: 0.5818 - acc: 0.6380 - val_loss: 1.7452 - val_acc: 0.1007\nEpoch 5/32\n366/366 [==============================] - 40s 109ms/step - loss: 0.5466 - acc: 0.6557 - val_loss: 1.8478 - val_acc: 0.2152\nEpoch 6/32\n366/366 [==============================] - 40s 109ms/step - loss: 0.5217 - acc: 0.6636 - val_loss: 1.8561 - val_acc: 0.1062\nEpoch 7/32\n366/366 [==============================] - 40s 109ms/step - loss: 0.4992 - acc: 0.6602 - val_loss: 1.7846 - val_acc: 0.0869\n\nEpoch 00007: ReduceLROnPlateau reducing learning rate to 4.999999873689376e-05.\nEpoch 8/32\n366/366 [==============================] - 41s 111ms/step - loss: 0.4809 - acc: 0.6865 - val_loss: 1.9221 - val_acc: 0.2772\nEpoch 9/32\n366/366 [==============================] - 40s 109ms/step - loss: 0.4582 - acc: 0.6885 - val_loss: 1.7371 - val_acc: 0.1103\nEpoch 10/32\n366/366 [==============================] - 40s 110ms/step - loss: 0.4844 - acc: 0.6732 - val_loss: 1.7593 - val_acc: 0.0910\nEpoch 11/32\n366/366 [==============================] - 40s 109ms/step - loss: 0.4458 - acc: 0.6878 - val_loss: 1.7774 - val_acc: 0.0993\nEpoch 12/32\n366/366 [==============================] - 40s 109ms/step - loss: 0.4106 - acc: 0.7046 - val_loss: 1.8502 - val_acc: 0.0952\n\nEpoch 00012: ReduceLROnPlateau reducing learning rate to 2.499999936844688e-05.\nEpoch 13/32\n366/366 [==============================] - 40s 109ms/step - loss: 0.4090 - acc: 0.6926 - val_loss: 1.8029 - val_acc: 0.0993\nEpoch 14/32\n366/366 [==============================] - 40s 110ms/step - loss: 0.3947 - acc: 0.7059 - val_loss: 1.8551 - val_acc: 0.1655\nRestoring model weights from the end of the best epoch\nEpoch 00014: early stopping\n" ] ], [ [ "# Fine-tune the complete model (2nd step)", "_____no_output_____" ] ], [ [ "optimizer = optimizers.SGD(lr=LEARNING_RATE, momentum=0.9, nesterov=True)\nmodel.compile(optimizer=optimizer, loss='mean_squared_error', metrics=metric_list)", "_____no_output_____" ], [ "history_finetunning_2 = model.fit_generator(generator=train_generator,\n steps_per_epoch=STEP_SIZE_TRAIN,\n validation_data=valid_generator,\n validation_steps=STEP_SIZE_VALID,\n epochs=int(EPOCHS*0.2),\n callbacks=callback_list,\n verbose=1).history", "Epoch 1/8\n366/366 [==============================] - 44s 119ms/step - loss: 0.4996 - acc: 0.6773 - val_loss: 1.7992 - val_acc: 0.0966\nEpoch 2/8\n366/366 [==============================] - 40s 109ms/step - loss: 0.4740 - acc: 0.6834 - val_loss: 1.8806 - val_acc: 0.2579\nEpoch 3/8\n366/366 [==============================] - 40s 109ms/step - loss: 0.5012 - acc: 0.6670 - val_loss: 1.7135 - val_acc: 0.0979\nEpoch 4/8\n366/366 [==============================] - 40s 110ms/step - loss: 0.4573 - acc: 0.6790 - val_loss: 1.9142 - val_acc: 0.2179\nEpoch 5/8\n366/366 [==============================] - 40s 109ms/step - loss: 0.4903 - acc: 0.6697 - val_loss: 1.9250 - val_acc: 0.2607\nEpoch 6/8\n366/366 [==============================] - 40s 109ms/step - loss: 0.4520 - acc: 0.6882 - val_loss: 1.8016 - val_acc: 0.1655\n\nEpoch 00006: ReduceLROnPlateau reducing learning rate to 4.999999873689376e-05.\nEpoch 7/8\n366/366 [==============================] - 40s 108ms/step - loss: 0.4171 - acc: 0.7049 - val_loss: 1.8324 - val_acc: 0.0993\nEpoch 8/8\n366/366 [==============================] - 40s 109ms/step - loss: 0.4214 - acc: 0.7029 - val_loss: 1.8703 - val_acc: 0.2331\nRestoring model weights from the end of the best epoch\nEpoch 00008: early stopping\n" ] ], [ [ "# Model loss graph ", "_____no_output_____" ] ], [ [ "history = {'loss': history_finetunning['loss'] + history_finetunning_2['loss'], \n 'val_loss': history_finetunning['val_loss'] + history_finetunning_2['val_loss'], \n 'acc': history_finetunning['acc'] + history_finetunning_2['acc'], \n 'val_acc': history_finetunning['val_acc'] + history_finetunning_2['val_acc']}\n\nsns.set_style(\"whitegrid\")\nfig, (ax1, ax2) = plt.subplots(2, 1, sharex='col', figsize=(20, 14))\n\nax1.plot(history['loss'], label='Train loss')\nax1.plot(history['val_loss'], label='Validation loss')\nax1.legend(loc='best')\nax1.set_title('Loss')\n\nax2.plot(history['acc'], label='Train accuracy')\nax2.plot(history['val_acc'], label='Validation accuracy')\nax2.legend(loc='best')\nax2.set_title('Accuracy')\n\nplt.xlabel('Epochs')\nsns.despine()\nplt.show()", "_____no_output_____" ], [ "# Create empty arays to keep the predictions and labels\ndf_preds = pd.DataFrame(columns=['label', 'pred', 'set'])\ntrain_generator.reset()\nvalid_generator.reset()\n\n# Add train predictions and labels\nfor i in range(STEP_SIZE_TRAIN + 1):\n im, lbl = next(train_generator)\n preds = model.predict(im, batch_size=train_generator.batch_size)\n for index in range(len(preds)):\n df_preds.loc[len(df_preds)] = [lbl[index], preds[index][0], 'train']\n\n# Add validation predictions and labels\nfor i in range(STEP_SIZE_VALID + 1):\n im, lbl = next(valid_generator)\n preds = model.predict(im, batch_size=valid_generator.batch_size)\n for index in range(len(preds)):\n df_preds.loc[len(df_preds)] = [lbl[index], preds[index][0], 'validation']\n\ndf_preds['label'] = df_preds['label'].astype('int')", "_____no_output_____" ] ], [ [ "# Threshold optimization", "_____no_output_____" ] ], [ [ "def classify(x):\n if x < 0.5:\n return 0\n elif x < 1.5:\n return 1\n elif x < 2.5:\n return 2\n elif x < 3.5:\n return 3\n return 4\n\ndef classify_opt(x):\n if x <= (0 + best_thr_0):\n return 0\n elif x <= (1 + best_thr_1):\n return 1\n elif x <= (2 + best_thr_2):\n return 2\n elif x <= (3 + best_thr_3):\n return 3\n return 4\n\n\ndef find_best_threshold(df, label, label_col='label', pred_col='pred', do_plot=True):\n score = []\n thrs = np.arange(0, 1, 0.01)\n for thr in thrs:\n preds_thr = [label if ((pred >= label and pred < label+1) and (pred < (label+thr))) else classify(pred) for pred in df[pred_col]]\n score.append(cohen_kappa_score(df[label_col].astype('int'), preds_thr))\n\n score = np.array(score)\n pm = score.argmax()\n best_thr, best_score = thrs[pm], score[pm].item()\n print('Label %s: thr=%.2f, Kappa=%.3f' % (label, best_thr, best_score))\n plt.rcParams[\"figure.figsize\"] = (20, 5)\n plt.plot(thrs, score)\n plt.vlines(x=best_thr, ymin=score.min(), ymax=score.max())\n plt.show()\n \n return best_thr\n\n# Best threshold for label 3\nbest_thr_3 = find_best_threshold(df_preds, 3)\n\n# Best threshold for label 2\nbest_thr_2 = find_best_threshold(df_preds, 2)\n\n# Best threshold for label 1\nbest_thr_1 = find_best_threshold(df_preds, 1)\n\n# Best threshold for label 0\nbest_thr_0 = find_best_threshold(df_preds, 0)", "Label 3: thr=0.00, Kappa=0.000\n" ], [ "# Classify predictions\ndf_preds['predictions'] = df_preds['pred'].apply(lambda x: classify(x))\n# Apply optimized thresholds to the predictions\ndf_preds['predictions_opt'] = df_preds['pred'].apply(lambda x: classify_opt(x))\n\ntrain_preds = df_preds[df_preds['set'] == 'train']\nvalidation_preds = df_preds[df_preds['set'] == 'validation']", "_____no_output_____" ] ], [ [ "# Model Evaluation", "_____no_output_____" ], [ "## Confusion Matrix\n\n### Original thresholds", "_____no_output_____" ] ], [ [ "labels = ['0 - No DR', '1 - Mild', '2 - Moderate', '3 - Severe', '4 - Proliferative DR']\ndef plot_confusion_matrix(train, validation, labels=labels):\n train_labels, train_preds = train\n validation_labels, validation_preds = validation\n fig, (ax1, ax2) = plt.subplots(1, 2, sharex='col', figsize=(24, 7))\n train_cnf_matrix = confusion_matrix(train_labels, train_preds)\n validation_cnf_matrix = confusion_matrix(validation_labels, validation_preds)\n\n train_cnf_matrix_norm = train_cnf_matrix.astype('float') / train_cnf_matrix.sum(axis=1)[:, np.newaxis]\n validation_cnf_matrix_norm = validation_cnf_matrix.astype('float') / validation_cnf_matrix.sum(axis=1)[:, np.newaxis]\n\n train_df_cm = pd.DataFrame(train_cnf_matrix_norm, index=labels, columns=labels)\n validation_df_cm = pd.DataFrame(validation_cnf_matrix_norm, index=labels, columns=labels)\n\n sns.heatmap(train_df_cm, annot=True, fmt='.2f', cmap=\"Blues\",ax=ax1).set_title('Train')\n sns.heatmap(validation_df_cm, annot=True, fmt='.2f', cmap=sns.cubehelix_palette(8),ax=ax2).set_title('Validation')\n plt.show()\n\nplot_confusion_matrix((train_preds['label'], train_preds['predictions']), (validation_preds['label'], validation_preds['predictions']))", "_____no_output_____" ] ], [ [ "### Optimized thresholds", "_____no_output_____" ] ], [ [ "plot_confusion_matrix((train_preds['label'], train_preds['predictions_opt']), (validation_preds['label'], validation_preds['predictions_opt']))", "_____no_output_____" ] ], [ [ "## Quadratic Weighted Kappa", "_____no_output_____" ] ], [ [ "def evaluate_model(train, validation):\n train_labels, train_preds = train\n validation_labels, validation_preds = validation\n print(\"Train Cohen Kappa score: %.3f\" % cohen_kappa_score(train_preds, train_labels, weights='quadratic'))\n print(\"Validation Cohen Kappa score: %.3f\" % cohen_kappa_score(validation_preds, validation_labels, weights='quadratic'))\n print(\"Complete set Cohen Kappa score: %.3f\" % cohen_kappa_score(np.append(train_preds, validation_preds), np.append(train_labels, validation_labels), weights='quadratic'))\n \nprint(\" Original thresholds\")\nevaluate_model((train_preds['label'], train_preds['predictions']), (validation_preds['label'], validation_preds['predictions']))\nprint(\" Optimized thresholds\")\nevaluate_model((train_preds['label'], train_preds['predictions_opt']), (validation_preds['label'], validation_preds['predictions_opt']))", " Original thresholds\nTrain Cohen Kappa score: 0.000\nValidation Cohen Kappa score: 0.000\nComplete set Cohen Kappa score: 0.000\n Optimized thresholds\nTrain Cohen Kappa score: 0.000\nValidation Cohen Kappa score: 0.000\nComplete set Cohen Kappa score: 0.000\n" ] ], [ [ "## Apply model to test set and output predictions", "_____no_output_____" ] ], [ [ "def apply_tta(model, generator, steps=10):\n step_size = generator.n//generator.batch_size\n preds_tta = []\n for i in range(steps):\n generator.reset()\n preds = model.predict_generator(generator, steps=step_size)\n preds_tta.append(preds)\n\n return np.mean(preds_tta, axis=0)\n\npreds = apply_tta(model, test_generator)\npredictions = [classify(x) for x in preds]\npredictions_opt = [classify_opt(x) for x in preds]\n\nresults = pd.DataFrame({'id_code':test['id_code'], 'diagnosis':predictions})\nresults['id_code'] = results['id_code'].map(lambda x: str(x)[:-4])\n\nresults_opt = pd.DataFrame({'id_code':test['id_code'], 'diagnosis':predictions_opt})\nresults_opt['id_code'] = results_opt['id_code'].map(lambda x: str(x)[:-4])", "_____no_output_____" ], [ "# Cleaning created directories\nif os.path.exists(train_dest_path):\n shutil.rmtree(train_dest_path)\nif os.path.exists(validation_dest_path):\n shutil.rmtree(validation_dest_path)\nif os.path.exists(test_dest_path):\n shutil.rmtree(test_dest_path)", "_____no_output_____" ] ], [ [ "# Predictions class distribution", "_____no_output_____" ] ], [ [ "fig, (ax1, ax2) = plt.subplots(1, 2, sharex='col', figsize=(24, 8.7))\nsns.countplot(x=\"diagnosis\", data=results, palette=\"GnBu_d\", ax=ax1).set_title('Test')\nsns.countplot(x=\"diagnosis\", data=results_opt, palette=\"GnBu_d\", ax=ax2).set_title('Test optimized')\nsns.despine()\nplt.show()", "_____no_output_____" ], [ "val_kappa = cohen_kappa_score(validation_preds['label'], validation_preds['predictions'], weights='quadratic')\nval_opt_kappa = cohen_kappa_score(validation_preds['label'], validation_preds['predictions_opt'], weights='quadratic')\n\nresults_name = 'submission.csv'\nresults_opt_name = 'submission_opt.csv'\n# if val_kappa > val_opt_kappa:\n# results_name = 'submission.csv'\n# results_opt_name = 'submission_opt.csv'\n# else:\n# results_name = 'submission_norm.csv'\n# results_opt_name = 'submission.csv'", "_____no_output_____" ], [ "results.to_csv(results_name, index=False)\ndisplay(results.head())\n\nresults_opt.to_csv(results_opt_name, index=False)\ndisplay(results_opt.head())", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cb68e29a58048909f6ac0404983b2172e4f7709e
719,762
ipynb
Jupyter Notebook
code/Demo Covid-19 Prediction.ipynb
MattiaRigi97/Covid-Prediction-Lung-CT
43014e125e2bbcdd66c07d2c00cdc8cc36c5c40e
[ "MIT" ]
null
null
null
code/Demo Covid-19 Prediction.ipynb
MattiaRigi97/Covid-Prediction-Lung-CT
43014e125e2bbcdd66c07d2c00cdc8cc36c5c40e
[ "MIT" ]
null
null
null
code/Demo Covid-19 Prediction.ipynb
MattiaRigi97/Covid-Prediction-Lung-CT
43014e125e2bbcdd66c07d2c00cdc8cc36c5c40e
[ "MIT" ]
2
2021-04-15T07:17:02.000Z
2021-04-15T07:19:40.000Z
1,392.189555
208,276
0.957298
[ [ [ "# Covid-19 Prediction from Lung CT", "_____no_output_____" ], [ "This notebook utilizes a trained **classifier** to recognize **Covid-19** positive patients from their **CT lungs** scans in order to support the physician’s decision process with a quantitative approach.", "_____no_output_____" ] ], [ [ "from esmlib import *", "_____no_output_____" ] ], [ [ "## Select an exam folder", "_____no_output_____" ], [ "With the following code you can select the folder that contains the **.dcm** file images.", "_____no_output_____" ] ], [ [ "path_exam = askdirectory()", "_____no_output_____" ] ], [ [ "Read some interesting **metadata** relative to the patient exam:", "_____no_output_____" ] ], [ [ "get_metadata(path_exam)", "PatientID: MIDRC-RICORD-1A-419639-000082\n\tSex: F\n\tAge: 85\n\nStudy Description: CT CHEST WITHOUT CONTRAST\n\tExam Modality: CT\n\tNumber of scans: 255\n\tImage size 512x512\n\tPatient Position: HFS\n\tSlice Thickness: 1.250000\n\tSpace between slices: 1.25\n" ] ], [ [ "## Interactive Slider for visualizing the exam folder", "_____no_output_____" ] ], [ [ "def dicom_animation(x):\n plt.figure(1, figsize=(12,10))\n plt.imshow(m[x], cmap=plt.cm.gray)\n return x", "_____no_output_____" ], [ "files = sorted(os.listdir(path_exam))\nm = np.zeros((len(files), 410, 450))\nfor n in range(0,len(files)):\n pathtemp = path_exam + \"\\\\\" + files[n]\n img = load_and_preprocess_dcm(pathtemp)\n m[n, : , : ] = img", "_____no_output_____" ] ], [ [ "Move the slider to scroll through the images", "_____no_output_____" ] ], [ [ "interact(dicom_animation, x=(0, len(m)-1))", "_____no_output_____" ] ], [ [ "## Automatic selection of three scans", "_____no_output_____" ] ], [ [ "lista, idx_sel = select_paths(path_exam)", "_____no_output_____" ], [ "lista_img = select_and_show_3(lista, idx_sel)", "_____no_output_____" ] ], [ [ "### If the selected scans are not good enough, you can specify in the following code the number of scans to select", "_____no_output_____" ] ], [ [ "a = input(\"Insert the index number of the first scan: \")", "_____no_output_____" ], [ "b = input(\"Insert the index number of the second scan: \")", "_____no_output_____" ], [ "c = input(\"Insert the index number of the third scan: \")", "_____no_output_____" ], [ "idx_sel = [int(a), int(b), int(c)]\nlista_img = select_and_show_3(lista, idx_sel)", "_____no_output_____" ] ], [ [ "## Get the mask of the three images", "_____no_output_____" ] ], [ [ "mask_list = []\nfor img in lista_img:\n first_mask = mask_kmeans(img)\n final_mask = fill_mask(first_mask)\n mask_list.append(final_mask)", "_____no_output_____" ], [ "show_3_mask(mask_list, idx_sel)", "_____no_output_____" ] ], [ [ "### If the selected mask are not good enough, you can specify in the following code the number of mask to modify", "_____no_output_____" ] ], [ [ "n_mask = input(\"Insert the index number of the scan you want to replace: \")", "_____no_output_____" ] ], [ [ "With the following code, you can *draw manually* the lung mask (ROI)", "_____no_output_____" ] ], [ [ "%matplotlib qt \nroi1, mask = manually_roi_select(lista_img, mask_list, n_mask)", "_____no_output_____" ] ], [ [ "Show the manually selected mask", "_____no_output_____" ] ], [ [ "%matplotlib inline \nshow_roi_selected(roi1, mask, n_mask, lista_img)", "_____no_output_____" ] ], [ [ "#### If you want to modify another mask, just repeat the process", "_____no_output_____" ], [ "Finally, the mask considered are:", "_____no_output_____" ] ], [ [ "show_3_mask(mask_list, idx_sel)", "_____no_output_____" ] ], [ [ "## Features extraction", "_____no_output_____" ], [ "We extract the **Haralick Features** from the equalized and filtered masked images selected", "_____no_output_____" ] ], [ [ "feat = features_and_plot(lista_img, mask_list, printing=True)", "_____no_output_____" ] ], [ [ "## Covid-19 Prediction", "_____no_output_____" ], [ "Run the classifier on the extracted features and get the prediction for the patient", "_____no_output_____" ] ], [ [ "covid_predict(feat)", "The patient is positive to Covid-19 with a confidence of 66.86%\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", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
cb68ec9e47310fa5be919872e0e00ef15c2f7962
135,317
ipynb
Jupyter Notebook
Monte_Carlo/Monte_Carlo_Simulations_with_Python/Part1.ipynb
ysraell/examples
b41df16ddda3db2cbafc4e4c85ac9bd5d000d375
[ "BSD-3-Clause" ]
7
2020-06-11T19:15:29.000Z
2021-01-31T22:04:56.000Z
Monte_Carlo/Monte_Carlo_Simulations_with_Python/Part1.ipynb
ysraell/examples
b41df16ddda3db2cbafc4e4c85ac9bd5d000d375
[ "BSD-3-Clause" ]
2
2019-12-30T13:09:07.000Z
2020-06-22T03:14:28.000Z
Monte_Carlo/Monte_Carlo_Simulations_with_Python/Part1.ipynb
ysraell/examples
b41df16ddda3db2cbafc4e4c85ac9bd5d000d375
[ "BSD-3-Clause" ]
3
2020-06-15T18:17:53.000Z
2020-06-22T20:32:33.000Z
132.40411
43,300
0.867245
[ [ [ "# Monte Carlo Simulations with Python (Part 1)\n[Patrick Hanbury](https://towardsdatascience.com/monte-carlo-simulations-with-python-part-1-f5627b7d60b0)\n\n- Notebook author: Israel Oliveira [\\[e-mail\\]](mailto:'Israel%20Oliveira%20'<[email protected]>)", "_____no_output_____" ] ], [ [ "%load_ext watermark", "_____no_output_____" ], [ "import numpy as np\nimport math\nimport random\nfrom matplotlib import pyplot as plt\nfrom IPython.display import clear_output, display, Markdown, Latex, Math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Polygon\n\nimport scipy.integrate as integrate\nfrom decimal import Decimal\n\nimport pandas as pd\n\nPI = math.pi\ne = math.e", "_____no_output_____" ], [ "# Run this cell before close.\n%watermark\n%watermark --iversion\n%watermark -b -r -g", "2020-06-11T14:41:50+00:00\n\nCPython 3.7.7\nIPython 7.15.0\n\ncompiler : GCC 8.3.0\nsystem : Linux\nrelease : 4.19.76-linuxkit\nmachine : x86_64\nprocessor : \nCPU cores : 16\ninterpreter: 64bit\nnumpy 1.18.5\n\nGit hash: 65fe9d3ebc619f55a31549efb1f85ee7505089bf\nGit repo: https://github.com/ysraell/examples.git\nGit branch: master\n" ] ], [ [ "We want:\n\n\n$I_{ab} = \\int\\limits_{a}^{b} f(x) dx ~~~(1)$\n\nso, we could achive that with a avarage value of $f$:\n\n$\\hat{f}_{ab} = \\frac{1}{b-a} \\int\\limits_{a}^{b} f(x) dx ~~~(2)$", "_____no_output_____" ] ], [ [ "\ndef func(x):\n return (x - 3) * (x - 5) * (x - 7) + 85\n\na, b = 2, 9 # integral limits\nx = np.linspace(0, 10)\ny = func(x)\n\nfig, ax = plt.subplots()\nax.plot(x, y, 'r', linewidth=2)\nax.set_ylim(bottom=0)\n\n# Make the shaded region\nix = np.linspace(a, b)\niy = func(ix)\nverts = [(a, 0), *zip(ix, iy), (b, 0)]\npoly = Polygon(verts, facecolor='0.9', edgecolor='0.5')\nax.add_patch(poly)\n\nax.text(0.5 * (a + b), 30, r\"$\\int_a^b f(x)\\mathrm{d}x$\",\n horizontalalignment='center', fontsize=20)\n\nfig.text(0.9, 0.05, '$x$')\nfig.text(0.1, 0.9, '$y$')\n\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nax.xaxis.set_ticks_position('bottom')\n\nax.set_xticks((a, b))\nax.set_xticklabels(('$a$', '$b$'))\nax.set_yticks([])\n\nplt.axhline(90, xmin=0.225, xmax=0.87)\nax.text(0.5 * (a + b), 30, r\"$\\int_a^b f(x)\\mathrm{d}x$\",\n horizontalalignment='center', fontsize=20)\n\nplt.show()", "_____no_output_____" ] ], [ [ "With $(1)$ and $(2)$:\n\n$\\hat{f}_{ab} = \\frac{1}{b-a} I $\n\n\n$I = (b-a)\\hat{f}_{ab} ~~~(3)$\n\nSampling $f(\\cdot)$, it is possible to calculate a approximate value for $\\hat{f}_{ab}$ (with a random variable $\\mathbf{x}$):\n\n$\\mathbf{F}_{ab} = {f(\\mathbf{x}) ~|~ \\mathbf{x} ~\\in~ [a, b]}$\n\nThe expectation for $\\mathbf{F}_{ab}$ is:\n\n$E[\\mathbf{F}_{ab}] = \\hat{f}_{ab}$\n\nand concluding with\n\n$I = E[\\mathbf{F}_{ab}](b-a)$\n\nSo, how we could calculate $E[\\mathbf{F}_{ab}]$? With $N$ uniform sampling of $x~\\in~[a, b]$. If $N$ is large enough and $\\mathbf{x}$ is uniform between $[a, b]$:\n\n$ E[\\mathbf{F}_{ab}] = \\frac{1}{N} \\sum\\limits_{i}^N f(\\mathbf{x}) ~|~ \\mathbf{x} ~\\in~ [a, b]$ \n\nand\n\n$I = E[\\mathbf{F}_{ab}](b-a) = \\lim\\limits_{N \\rightarrow \\infty} \\frac{b-a}{N} \\sum\\limits_{i}^N f(\\mathbf{x}) ~|~ \\mathbf{x} ~\\in~ [a, b] ~~~(4)$\n\n\nThis is the *Crude Monte Carlo*.", "_____no_output_____" ], [ "#### Example 1:\n\nCalculate:\n\n$I = \\int\\limits_{0}^{+\\infty} \\frac{e^{-x}}{(x-1)^2 + 1} dx ~~~(5)$", "_____no_output_____" ] ], [ [ "def get_rand_number(min_value, max_value):\n \"\"\"\n This function gets a random number from a uniform distribution between\n the two input values [min_value, max_value] inclusively\n Args:\n - min_value (float)\n - max_value (float)\n Return:\n - Random number between this range (float)\n \"\"\"\n range = max_value - min_value\n choice = random.uniform(0,1)\n return min_value + range*choice\n\ndef f_of_x(x):\n \"\"\"\n This is the main function we want to integrate over.\n Args:\n - x (float) : input to function; must be in radians\n Return:\n - output of function f(x) (float)\n \"\"\"\n return (e**(-1*x))/(1+(x-1)**2)\n\nlower_bound = 0\nupper_bound = 5\n\ndef crude_monte_carlo(num_samples=10000, lower_bound = 0, upper_bound = 5):\n \"\"\"\n This function performs the Crude Monte Carlo for our\n specific function f(x) on the range x=0 to x=5.\n Notice that this bound is sufficient because f(x)\n approaches 0 at around PI.\n Args:\n - num_samples (float) : number of samples\n Return:\n - Crude Monte Carlo estimation (float)\n \n \"\"\"\n sum_of_samples = 0\n for i in range(num_samples):\n x = get_rand_number(lower_bound, upper_bound)\n sum_of_samples += f_of_x(x)\n \n return (upper_bound - lower_bound) * float(sum_of_samples/num_samples)", "_____no_output_____" ], [ "display(Math(r'I \\approx {:.4f}, ~N = 10^4'.format(crude_monte_carlo())))", "_____no_output_____" ], [ "display(Math(r'\\left . f(a) \\right |_{a=0} \\approx '+r'{:.4f} '.format(f_of_x(lower_bound))))", "_____no_output_____" ], [ "display(Math(r'\\left . f(b) \\right |_{b=5} \\approx '+r'{:.4f} '.format(f_of_x(upper_bound))))", "_____no_output_____" ] ], [ [ "Why $b=5$?\n\n$ \\lim\\limits_{x \\rightarrow +\\infty} \\frac{e^{-x}}{(x-1)^2 + 1} \\rightarrow 0 $\n\nWe could consider $0.0004 ~\\approx~ 0$.", "_____no_output_____" ], [ "If $b = 10$?", "_____no_output_____" ] ], [ [ "upper_bound = 10\ndisplay(Math(r'\\left . f(b) \\right |_{b=5} \\approx '+r'{:.6f}'.format(f_of_x(upper_bound))+'= 10^{-6}'))", "_____no_output_____" ], [ "display(Math(r'I \\approx {:.4f}, ~N = 10^5 '.format(crude_monte_carlo(num_samples=100000, upper_bound = 10))))", "_____no_output_____" ], [ "plt.figure()\ndef func(x):\n return f_of_x(x)\n\na, b = 0, 5 # integral limits\nx = np.linspace(0, 6)\ny = func(x)\n\nfig, ax = plt.subplots()\nax.plot(x, y, 'r', linewidth=2)\nax.set_ylim(bottom=0)\n\n# Make the shaded region\nix = np.linspace(a, b)\niy = func(ix)\nverts = [(a, 0), *zip(ix, iy), (b, 0)]\npoly = Polygon(verts, facecolor='0.9', edgecolor='0.5')\nax.add_patch(poly)\n\nax.text(0.2 * (a + b), 0.05, r\"$\\int_a^b f(x)\\mathrm{d}x$\",\n horizontalalignment='center', fontsize=20)\n\nfig.text(0.9, 0.05, '$x$')\nfig.text(0.1, 0.9, '$y$')\n\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nax.xaxis.set_ticks_position('bottom')\n\nax.set_xticks((a, b))\nax.set_xticklabels(('$a$', '$b$'))\nax.set_yticks([])\n\nax.axhline(0.2*crude_monte_carlo(),color='b', xmin=0.051, xmax=0.81)\niy = iy*0+0.2*crude_monte_carlo()\nverts = [(a, 0), *zip(ix, iy), (b, 0)]\npoly = Polygon(verts, facecolor='0.94', edgecolor='0.99')\nax.add_patch(poly)\nax.text(5,0.2*crude_monte_carlo()+0.03 , r\"$\\hat{f}_{ab}$\",\n horizontalalignment='center', fontsize=20)\n\nplt.show()", "_____no_output_____" ] ], [ [ "Comparing with [Integration (scipy.integrate)](https://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html).", "_____no_output_____" ] ], [ [ "results = integrate.quad(lambda x: f_of_x(x), lower_bound, upper_bound)", "_____no_output_____" ], [ "tmp = (Decimal(results[1]).as_tuple().digits[0], Decimal(results[1]).as_tuple().exponent + len(Decimal(results[1]).as_tuple().digits) -1)\n\ndisplay(Math(r'I_{\\text{SciPy}} = '+r'{:.4f}, ~e \\approx {}'.format(results[0],tmp[0])+r'\\cdot 10^{'+'{}'.format(tmp[1])+r'}'))", "_____no_output_____" ], [ "diff = []\nfor _ in range(100):\n diff.append(crude_monte_carlo(num_samples=100000, upper_bound = 10)-results[0])", "_____no_output_____" ], [ "df = pd.DataFrame([abs(x) for x in diff], columns=['$I- I_{\\text{SciPy}}$'])\ndisplay(df.describe())\ndf.plot(grid = True)", "_____no_output_____" ], [ "df = pd.DataFrame([abs(x)/results[0] for x in diff], columns=['$(I- I_{\\text{SciPy}})/I_{\\text{SciPy}}$'])\ndisplay(df.describe())\ndf.plot(grid = True)", "_____no_output_____" ] ], [ [ "Confirm the estimated error with variance.", "_____no_output_____" ] ], [ [ "def get_crude_MC_variance(num_samples = 10000, upper_bound = 5):\n \"\"\"\n This function returns the variance fo the Crude Monte Carlo.\n Note that the inputed number of samples does not neccissarily\n need to correspond to number of samples used in the Monte\n Carlo Simulation.\n Args:\n - num_samples (int)\n Return:\n - Variance for Crude Monte Carlo approximation of f(x) (float)\n \"\"\"\n int_max = upper_bound # this is the max of our integration range\n \n # get the average of squares\n running_total = 0\n for i in range(num_samples):\n x = get_rand_number(0, int_max)\n running_total += f_of_x(x)**2\n sum_of_sqs = running_total*int_max / num_samples\n \n # get square of average\n running_total = 0\n for i in range(num_samples):\n x = get_rand_number(0, int_max)\n running_total = f_of_x(x)\n sq_ave = (int_max*running_total/num_samples)**2\n \n return sum_of_sqs - sq_ave", "_____no_output_____" ], [ "s1 = get_crude_MC_variance()\n\"{:.4f}\".format(s1)", "_____no_output_____" ], [ "s2 = get_crude_MC_variance(100000,10)\n\"{:.4f}\".format(s2)", "_____no_output_____" ], [ "math.sqrt(s1 / 10000)", "_____no_output_____" ], [ "df.describe().loc['mean'].to_list()[0]", "_____no_output_____" ] ], [ [ "### Importance Sampling", "_____no_output_____" ] ], [ [ "# this is the template of our weight function g(x)\ndef g_of_x(x, A, lamda):\n e = 2.71828\n return A*math.pow(e, -1*lamda*x)\n\ndef inverse_G_of_r(r, lamda):\n return (-1 * math.log(float(r)))/lamda\n\ndef get_IS_variance(lamda, num_samples):\n \"\"\"\n This function calculates the variance if a Monte Carlo\n using importance sampling.\n Args:\n - lamda (float) : lamdba value of g(x) being tested\n Return: \n - Variance\n \"\"\"\n A = lamda\n int_max = 5\n \n # get sum of squares\n running_total = 0\n for i in range(num_samples):\n x = get_rand_number(0, int_max)\n running_total += (f_of_x(x)/g_of_x(x, A, lamda))**2\n \n sum_of_sqs = running_total / num_samples\n \n # get squared average\n running_total = 0\n for i in range(num_samples):\n x = get_rand_number(0, int_max)\n running_total += f_of_x(x)/g_of_x(x, A, lamda)\n sq_ave = (running_total/num_samples)**2\n \n \n return sum_of_sqs - sq_ave\n\n# get variance as a function of lambda by testing many\n# different lambdas\n\ntest_lamdas = [i*0.05 for i in range(1, 61)]\nvariances = []\n\nfor i, lamda in enumerate(test_lamdas):\n print(f\"lambda {i+1}/{len(test_lamdas)}: {lamda}\")\n A = lamda\n variances.append(get_IS_variance(lamda, 10000))\n clear_output(wait=True)\n \noptimal_lamda = test_lamdas[np.argmin(np.asarray(variances))]\nIS_variance = variances[np.argmin(np.asarray(variances))]\n\nprint(f\"Optimal Lambda: {optimal_lamda}\")\nprint(f\"Optimal Variance: {IS_variance}\")\nprint(f\"Error: {(IS_variance/10000)**0.5}\")", "Optimal Lambda: 1.6500000000000001\nOptimal Variance: 0.04850338057561787\nError: 0.0022023483052328\n" ], [ "def importance_sampling_MC(lamda, num_samples):\n A = lamda\n \n running_total = 0\n for i in range(num_samples):\n r = get_rand_number(0,1)\n running_total += f_of_x(inverse_G_of_r(r, lamda=lamda))/g_of_x(inverse_G_of_r(r, lamda=lamda), A, lamda)\n approximation = float(running_total/num_samples)\n return approximation\n\n# run simulation\nnum_samples = 10000\napprox = importance_sampling_MC(optimal_lamda, num_samples)\nvariance = get_IS_variance(optimal_lamda, num_samples)\nerror = (variance/num_samples)**0.5\n\n# display results\nprint(f\"Importance Sampling Approximation: {approx}\")\nprint(f\"Variance: {variance}\")\nprint(f\"Error: {error}\")", "Importance Sampling Approximation: 0.6953260856002619\nVariance: 0.04570462290582866\nError: 0.0021378639551156817\n" ], [ "display(Math(r'(I_{IS} - I_{\\text{SciPy}})/I_{\\text{SciPy}} = '+'{:.4}\\%'.format(100*abs((approx-results[0])/results[0]))))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cb68ede5725cb27fb24a01ca9b5abad6b2bccc68
378,424
ipynb
Jupyter Notebook
experiments/Toy Colors.ipynb
dtak/rrr
d83a16ee4a989ba47ef1b1a43acc5f528a899b1f
[ "MIT" ]
44
2017-03-13T11:24:25.000Z
2022-01-27T20:11:10.000Z
experiments/Toy Colors.ipynb
dtak/rrr
d83a16ee4a989ba47ef1b1a43acc5f528a899b1f
[ "MIT" ]
5
2017-11-22T16:44:32.000Z
2020-08-18T11:33:31.000Z
experiments/Toy Colors.ipynb
dtak/rrr
d83a16ee4a989ba47ef1b1a43acc5f528a899b1f
[ "MIT" ]
12
2017-03-14T00:03:20.000Z
2021-05-21T09:55:44.000Z
396.67086
96,156
0.925652
[ [ [ "import sys; sys.path.append('../rrr')\nfrom multilayer_perceptron import *\nfrom figure_grid import *\nfrom local_linear_explanation import *\nfrom toy_colors import generate_dataset, imgshape, ignore_rule1, ignore_rule2, rule1_score, rule2_score\nimport lime\nimport lime.lime_tabular", "_____no_output_____" ] ], [ [ "# Toy Color Dataset\n\nThis is a simple, two-class image classification dataset with two independent ways a model could learn to distinguish between classes. The first is whether all four corner pixels are the same color, and the second is whether the top-middle three pixels are all different colors. Images in class 1 satisfy both conditions and images in class 2 satisfy neither. See `color_dataset_generator` for more details.\n\nWe will train a multilayer perceptron to classify these images, explore which rule(s) it implicitly learns, and constrain it to use only one rule (or neither).\n\nLet's first load our dataset:", "_____no_output_____" ] ], [ [ "X, Xt, y, yt = generate_dataset(cachefile='../data/toy-colors.npz')\nE1 = np.array([ignore_rule2 for _ in range(len(y))])\nE2 = np.array([ignore_rule1 for _ in range(len(y))])", "_____no_output_____" ], [ "print(X.shape, Xt.shape, y.shape, yt.shape, E1.shape, E2.shape)", "(20000, 75) (20000, 75) (20000,) (20000,) (20000, 75) (20000, 75)\n" ] ], [ [ "## Understanding the Dataset\n\nLet's just examine images from each class quickly and verify that in class 1, the corners are all the same color and the top-middle three pixels are all different (none of which should hold true in class 2):", "_____no_output_____" ] ], [ [ "plt.subplot(121)\nplt.title('Class 1')\nimage_grid(X[np.argwhere(y == 0)[:9]], (5,5,3), 3)\nplt.subplot(122)\nplt.title('Class 2')\nimage_grid(X[np.argwhere(y == 1)[:9]], (5,5,3), 3)\nplt.show()", "_____no_output_____" ] ], [ [ "Great.\n\n## Explaining and learning diverse classifiers\n\nNow let's see if we can train our model to implicitly learn each rule:", "_____no_output_____" ] ], [ [ "def explain(model, title='', length=4):\n plt.title(title)\n explanation_grid(model.grad_explain(Xt[:length*length]), imgshape, length)", "_____no_output_____" ], [ "# Train a model without any constraints\nmlp_plain = MultilayerPerceptron()\nmlp_plain.fit(X, y)\nmlp_plain.score(Xt, yt)", "_____no_output_____" ], [ "# Train a model constrained to use the first rule\nmlp_rule1 = MultilayerPerceptron(l2_grads=1000)\nmlp_rule1.fit(X, y, E1)\nmlp_rule1.score(Xt, yt)", "_____no_output_____" ], [ "# Train a model constrained to use the second rule\nmlp_rule2 = MultilayerPerceptron(l2_grads=1000)\nmlp_rule2.fit(X, y, E2)\nmlp_rule2.score(Xt, yt)", "_____no_output_____" ], [ "# Visualize largest weights\nwith figure_grid(1,3, rowwidth=8) as g:\n g.next()\n explain(mlp_plain, 'No annotations')\n g.next()\n explain(mlp_rule1, '$A$ penalizing top middle')\n g.next()\n explain(mlp_rule2, '$A$ penalizing corners')", "_____no_output_____" ] ], [ [ "Notice that when we explicitly penalize corners or the top middle, the model appears to learn the _other_ rule perfectly. We haven't identified the pixels it does treat as significant in any way, but they are significant, so the fact that they show up in the explanations means that the explanation is probably an accurate reflection of the model's implicit logic.\n\nWhen we don't have any annotations, the model does identify the top-middle pixels occasionally, suggesting it defaults to learning a heavily but not completely corner-weighted combination of the rules.\n\nWhat happens when we forbid it from using either rule?", "_____no_output_____" ] ], [ [ "mlp_neither = MultilayerPerceptron(l2_grads=1e6)\nmlp_neither.fit(X, y, E1 + E2)\nmlp_neither.score(Xt, yt)", "_____no_output_____" ], [ "explain(mlp_neither, '$A$ biased against all relevant features')\nplt.show()", "_____no_output_____" ] ], [ [ "As we might expect, accuracy goes down and we start identifying random pixels as significant.\n\n## Find-another-explanation\n\nLet's now pretend we have no knowledge of what $A$ _should_ be for this dataset. Can we still train models that use diverse rules just by examining explanations?", "_____no_output_____" ] ], [ [ "A1 = mlp_plain.largest_gradient_mask(X)\nmlp_fae1 = MultilayerPerceptron(l2_grads=1000)\nmlp_fae1.fit(X, y, A1)\nmlp_fae1.score(Xt, yt)", "_____no_output_____" ], [ "explain(mlp_fae1, '$A$ biased against first model')\nplt.show()", "_____no_output_____" ] ], [ [ "Excellent. When we train a model to have small gradients where the $A=0$ model has large ones, we reproduce the top middle rule, though in some cases we learn a hybrid of the two. Now let's train another model to be different from either one. Note: I'm going to iteratively increase the L2 penalty until I get explanation divergence. I'm doing this manually now but it could easily be automated.", "_____no_output_____" ] ], [ [ "A2 = mlp_fae1.largest_gradient_mask(X)\nmlp_fae2 = MultilayerPerceptron(l2_grads=1e6)\nmlp_fae2.fit(X, y, A1 + A2)\nmlp_fae2.score(Xt, yt)", "_____no_output_____" ], [ "explain(mlp_fae2, '$A$ biased against models 1 and 2')\nplt.show()", "_____no_output_____" ] ], [ [ "When we run this twice, we get low accuracy and random gradient placement. Let's visualize this all together:", "_____no_output_____" ] ], [ [ "gridsize = (2,3)\n\nplt.subplot2grid(gridsize, (0,0))\nexplain(mlp_plain, r'$M_{0.67}\\left[ f_X|\\theta_0 \\right]$', 4)\n\nplt.subplot2grid(gridsize, (0,1))\nexplain(mlp_fae1, r'$M_{0.67}\\left[ f_X|\\theta_1 \\right]$', 4)\n\nplt.subplot2grid(gridsize, (0,2))\nexplain(mlp_fae2, r'$M_{0.67}\\left[ f_X|\\theta_2 \\right]$', 4)\n\nplt.subplot2grid(gridsize, (1,0), colspan=3)\nplt.axhline(1, color='red', ls='--')\n\ntest_scores = [mlp_plain.score(Xt, yt), mlp_fae1.score(Xt, yt), mlp_fae2.score(Xt, yt)]\ntrain_scores = [mlp_plain.score(X, y), mlp_fae1.score(X, y), mlp_fae2.score(X, y)]\n\nplt.plot([0,1,2], train_scores, marker='^', label='Train', alpha=0.5, color='blue', markersize=10)\nplt.plot([0,1,2], test_scores, marker='o', label='Test', color='blue')\nplt.xlim(-0.5, 2.5)\nplt.ylim(0.4, 1.05)\nplt.ylabel(' Accuracy')\nplt.xlabel('Find-another-explanation iteration')\nplt.legend(loc='best', fontsize=10)\nplt.xticks([0,1,2])\nplt.show()", "_____no_output_____" ] ], [ [ "So this more or less demonstrates the find-another-explanation method on the toy color dataset.\n\n## Transitions between rules\n\nSeparately, I ran a script to train many MLPs on this dataset, all biased against using corners, but with varying numbers of annotations in $A$ and varying L2 penalties. Let's see if we can find any transition behavior between these two rules:", "_____no_output_____" ] ], [ [ "import pickle\nn_vals = pickle.load(open('../data/color_n_vals.pkl', 'rb'))\nn_mlps = pickle.load(open('../data/color_n_mlps.pkl', 'rb'))\nl2_vals = pickle.load(open('../data/color_l2_vals.pkl', 'rb'))\nl2_mlps = pickle.load(open('../data/color_l2_mlps.pkl', 'rb'))", "_____no_output_____" ], [ "def realize(mlp_params):\n return [MultilayerPerceptron.from_params(p) for p in mlp_params]\n\nl2_rule1_scores = [rule1_score(mlp, Xt[:1000]) for mlp in realize(l2_mlps)]\nl2_rule2_scores = [rule2_score(mlp, Xt[:1000]) for mlp in realize(l2_mlps)]\nl2_acc_scores = [mlp.score(Xt[:1000], yt[:1000]) for mlp in realize(l2_mlps)]\n\nn_rule1_scores = [rule1_score(mlp, Xt[:1000]) for mlp in realize(n_mlps)]\nn_rule2_scores = [rule2_score(mlp, Xt[:1000]) for mlp in realize(n_mlps)]\nn_acc_scores = [mlp.score(Xt[:1000], yt[:1000]) for mlp in realize(n_mlps)]", "_____no_output_____" ], [ "plt.figure(figsize=(8,4))\nplt.subplot(121)\nplt.plot(l2_vals, l2_rule1_scores, 'o', label='Corners', marker='^')\nplt.plot(l2_vals, l2_rule2_scores, 'o', label='Top mid.')\nplt.plot(l2_vals, l2_acc_scores, label='Accuracy')\nplt.title('Effect of $\\lambda_1$ on implicit rule (full $A$)')\nplt.ylabel(r'Mean % $M_{0.67}\\left[f_X\\right]$ in corners / top middle')\nplt.ylim(0,1.1)\nplt.xscale(\"log\")\nplt.yticks([])\nplt.xlim(0,1000)\nplt.legend(loc='best', fontsize=10)\nplt.xlabel(r'$\\lambda_1$ (explanation L2 penalty)')\n\nplt.subplot(122)\nplt.plot(n_vals, n_rule1_scores, 'o', label='Corners', marker='^')\nplt.plot(n_vals, n_rule2_scores, 'o', label='Top mid.')\nplt.plot(n_vals, n_acc_scores, label='Accuracy')\nplt.xscale('log')\nplt.ylim(0,1.1)\nplt.xlim(0,10000)\nplt.legend(loc='best', fontsize=10)\nplt.title('Effect of $A$ on implicit rule ($\\lambda_1=1000$)')\nplt.xlabel('Number of annotations (nonzero rows of $A$)')\n\nplt.tight_layout()\nplt.show()", "_____no_output_____" ] ], [ [ "Cool. So we can definitely see a clear transition effect between rules.\n\n## Comparison with LIME\n\nAlthough we have some pretty clear evidence that gradient explanations are descriptive for our MLP on this simple dataset, let's make sure LIME produces similar results. We'll also do a very basic benchmark to see how long each of the respective methods take.", "_____no_output_____" ] ], [ [ "explainer = lime.lime_tabular.LimeTabularExplainer(\n Xt,\n feature_names=list(range(len(Xt[0]))),\n class_names=[0,1])", "/Users/asross/.pyenv/versions/3.5.1/lib/python3.5/site-packages/sklearn/utils/validation.py:429: DataConversionWarning: Data with input dtype uint8 was converted to float64 by StandardScaler.\n warnings.warn(msg, _DataConversionWarning)\n" ], [ "import time\n\nt1 = time.clock()\n\nlime_explanations = [\n explainer.explain_instance(Xt[i], mlp_plain.predict_proba, top_labels=1)\n for i in range(25)\n]\n\nt2 = time.clock()\n\ninput_grads = mlp_plain.input_gradients(Xt[:25])\n\nt3 = time.clock()", "_____no_output_____" ], [ "print('LIME took {:.6f}s/example'.format((t2-t1)/25.))\nprint('grads took {:.6f}s/example, which is {:.0f}x faster'.format((t3-t2)/25., (t2-t1)/float(t3-t2)))", "LIME took 1.802372s/example\ngrads took 0.000049s/example, which is 37055x faster\n" ], [ "preds = mlp_plain.predict(Xt[:25])\nlime_exps = [LocalLinearExplanation.from_lime(Xt[i], preds[i], lime_explanations[i]) for i in range(25)]\ngrad_exps = [LocalLinearExplanation(Xt[i], preds[i], input_grads[i]) for i in range(25)]", "_____no_output_____" ], [ "plt.subplot(121)\nplt.title('LIME', fontsize=16)\nexplanation_grid(lime_exps, imgshape, 3)\nplt.subplot(122)\nplt.title(r'$M_{0.67}\\left[f_X\\right]$', fontsize=16)\nexplanation_grid(grad_exps, imgshape, 3)\nplt.show()", "_____no_output_____" ] ], [ [ "So our explanation methods agree somewhat closely, which is good to see. Also, gradients are significantly faster.\n\n## Learning from less data\n\nDo explanations allow our model to learn with less data? Separately, we trained many models on increasing fractions of the dataset with different annotations; some penalizing the corners/top-middle and some penalizing everything but the corners/top-middle. Let's see how each version of the model performs:", "_____no_output_____" ] ], [ [ "import pickle\n\ndata_counts = pickle.load(open('../data/color_data_counts.pkl', 'rb'))\nnormals_by_count = pickle.load(open('../data/color_normals_by_count.pkl', 'rb'))\npro_r1s_by_count = pickle.load(open('../data/color_pro_r1s_by_count.pkl', 'rb'))\npro_r2s_by_count = pickle.load(open('../data/color_pro_r2s_by_count.pkl', 'rb'))\nanti_r1s_by_count = pickle.load(open('../data/color_anti_r1s_by_count.pkl', 'rb'))\nanti_r2s_by_count = pickle.load(open('../data/color_anti_r2s_by_count.pkl', 'rb'))", "_____no_output_____" ], [ "def score_all(ms):\n return [m.score(Xt,yt) for m in realize(ms)]\n\ndef realize(mlp_params):\n return [MultilayerPerceptron.from_params(p) for p in mlp_params]\n\nsc_normal = score_all(normals_by_count)\nsc_pro_r1 = score_all(pro_r1s_by_count)\nsc_pro_r2 = score_all(pro_r2s_by_count)\nsc_anti_r1 = score_all(anti_r1s_by_count)\nsc_anti_r2 = score_all(anti_r2s_by_count)", "_____no_output_____" ], [ "from matplotlib import ticker\n\ndef plot_A(A):\n plt.gca().set_xticks([])\n plt.gca().set_yticks([])\n plt.imshow((A[0].reshape(5,5,3) * 255).astype(np.uint8), interpolation='none')\n for i in range(5):\n for j in range(5):\n if A[0].reshape(5,5,3)[i][j][0]:\n plt.text(j,i+0.025,'1',ha='center',va='center',fontsize=8)\n else:\n plt.text(j,i+0.025,'0',ha='center',va='center',color='white',fontsize=8)\n\ngridsize = (4,9)\nplt.figure(figsize=(10,5))\ncs=3\n\nplt.subplot2grid(gridsize, (0,2*cs))\nplt.title('Pro-Rule 1')\nplot_A(~E2)\n\nplt.subplot2grid(gridsize, (1,2*cs))\nplt.title('Pro-Rule 2')\nplot_A(~E1)\n\nplt.subplot2grid(gridsize, (2,2*cs))\nplt.title('Anti-Rule 1')\nplot_A(E2)\n\nplt.subplot2grid(gridsize, (3,2*cs))\nplt.title('Anti-Rule 2')\nplot_A(E1)\n\nplt.subplot2grid(gridsize, (0,0), rowspan=4, colspan=cs)\nplt.title('Learning Rule 1 with $A$')\nplt.errorbar(data_counts, sc_normal, label=r'Normal', lw=2)\nplt.errorbar(data_counts, sc_pro_r1, label=r'Pro-Rule 1', marker='H')\nplt.errorbar(data_counts, sc_anti_r2, label=r'Anti-Rule 2', marker='^')\nplt.xscale('log')\nplt.ylim(0.5,1)\nplt.ylabel('Test Accuracy')\nplt.xlabel('# Training Examples')\nplt.legend(loc='best', fontsize=10)\nplt.gca().xaxis.set_major_formatter(ticker.FormatStrFormatter(\"%d\"))\nplt.gca().set_xticks([10,100,1000])\n\nplt.subplot2grid(gridsize, (0,cs), rowspan=4, colspan=cs)\nplt.title('Learning Rule 2 with $A$')\nplt.gca().set_yticklabels([])\nplt.errorbar(data_counts, sc_normal, label=r'Normal', lw=2)\nplt.errorbar(data_counts, sc_pro_r2, label=r'Pro-Rule 2', marker='H')\nplt.errorbar(data_counts, sc_anti_r1, label=r'Anti-Rule 1', marker='^')\nplt.xscale('log')\nplt.ylim(0.5,1)\nplt.xlabel('# Training Examples')\nplt.legend(loc='best', fontsize=10)\nplt.gca().xaxis.set_major_formatter(ticker.FormatStrFormatter(\"%d\"))\n\nplt.show()", "_____no_output_____" ], [ "def improvement_over_normal(scores, cutoff):\n norm = data_counts[next(i for i,val in enumerate(sc_normal) if val > cutoff)]\n comp = data_counts[next(i for i,val in enumerate(scores) if val > cutoff)]\n return norm / float(comp)\n\ndef print_improvement(name, scores, cutoff):\n print('Extra data for normal model to reach {:.2f} accuracy vs. {}: {:.2f}'.format(\n cutoff, name, improvement_over_normal(scores, cutoff)))\n\nprint_improvement('Anti-Rule 2', sc_anti_r2, 0.8)\nprint_improvement('Anti-Rule 2', sc_anti_r2, 0.9)\nprint_improvement('Anti-Rule 2', sc_anti_r2, 0.95)\nprint_improvement('Anti-Rule 2', sc_anti_r2, 0.99)\nprint('')\nprint_improvement('Pro-Rule 1', sc_pro_r1, 0.8)\nprint_improvement('Pro-Rule 1', sc_pro_r1, 0.9)\nprint_improvement('Pro-Rule 1', sc_pro_r1, 0.95)\nprint_improvement('Pro-Rule 1', sc_pro_r1, 0.99)\nprint('')\nprint_improvement('Pro-Rule 2', sc_pro_r2, 0.9)\nprint_improvement('Pro-Rule 2', sc_pro_r2, 0.95)\nprint_improvement('Pro-Rule 2', sc_pro_r2, 0.97)\nprint('')\nprint_improvement('Anti-Rule 1', sc_anti_r1, 0.7)\nprint_improvement('Anti-Rule 1', sc_anti_r1, 0.8)\nprint_improvement('Anti-Rule 1', sc_anti_r1, 0.9)", "Extra data for normal model to reach 0.80 accuracy vs. Anti-Rule 2: 3.05\nExtra data for normal model to reach 0.90 accuracy vs. Anti-Rule 2: 1.95\nExtra data for normal model to reach 0.95 accuracy vs. Anti-Rule 2: 1.95\nExtra data for normal model to reach 0.99 accuracy vs. Anti-Rule 2: 3.05\n\nExtra data for normal model to reach 0.80 accuracy vs. Pro-Rule 1: 70.79\nExtra data for normal model to reach 0.90 accuracy vs. Pro-Rule 1: 28.62\nExtra data for normal model to reach 0.95 accuracy vs. Pro-Rule 1: 28.54\nExtra data for normal model to reach 0.99 accuracy vs. Pro-Rule 1: 5.95\n\nExtra data for normal model to reach 0.90 accuracy vs. Pro-Rule 2: 1.56\nExtra data for normal model to reach 0.95 accuracy vs. Pro-Rule 2: 2.44\nExtra data for normal model to reach 0.97 accuracy vs. Pro-Rule 2: 1.95\n\nExtra data for normal model to reach 0.70 accuracy vs. Anti-Rule 1: 0.33\nExtra data for normal model to reach 0.80 accuracy vs. Anti-Rule 1: 0.64\nExtra data for normal model to reach 0.90 accuracy vs. Anti-Rule 1: 0.64\n" ] ], [ [ "Generally, we learn better classifiers with less data using explanations (especially in the Pro-Rule 1 case, where we provide the most information). Biasing against the top-middle or against everything but the corners / top-middle tends to give us more accurate classifiers. Biasing against the corners, however, gives us _lower_ accuracy until we obtain more examples. This may be because it's an inherently harder rule to learn; there are only 4 ways that all corners can match, but $4*3*2=24$ ways the top-middle pixels can differ.\n\n## Investigating cutoffs \n\nWe chose a 0.67 cutoff for most of our training a bit arbitrarily, so let's just investigate that briefly:", "_____no_output_____" ] ], [ [ "def M(input_gradients, cutoff=0.67):\n return np.array([np.abs(e) > cutoff*np.abs(e).max() for e in input_gradients]).astype(int).ravel()\n\ngrads = mlp_plain.input_gradients(Xt)\ngrads2 = mlp_rule1.input_gradients(Xt)\n\ncutoffs = np.linspace(0,1,100)\ncutoff_pcts = np.array([M(grads, c).sum() / float(len(grads.ravel())) for c in cutoffs])\ncutoff_pcts2 = np.array([M(grads2, c).sum() / float(len(grads2.ravel())) for c in cutoffs])", "_____no_output_____" ], [ "plt.plot(cutoffs, cutoff_pcts, label='$A=0$')\nplt.plot(cutoffs, cutoff_pcts2, label='$A$ against corners')\nplt.legend(loc='best')\nplt.xlabel('Cutoff')\nplt.ylabel('Mean fraction of qualifying gradient entries')\nplt.yticks(np.linspace(0,1,21))\nplt.yscale('log')\nplt.axhline(0.06, ls='--', c='red')\nplt.axvline(0.67, ls='--', c='blue')\nplt.title('-- Toy color dataset- --\\n# qualifying entries falls exponentially\\n0.67 cutoff takes the top ~6%')\nplt.show()", "_____no_output_____" ] ], [ [ "On average, the number of elements we keep falls exponentially without any clear kink in the curve, so perhaps our arbitrariness is justified, though it's problematic that it exists in the first place.", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
cb690527a945db0c10e436c248928f622cd32210
95,496
ipynb
Jupyter Notebook
examples/Machine Learning/Algorithms/KNN/KNN_Example1.ipynb
mythreyad/Cerbo
ff8ef335ea6b146ef7b5314813b82632ed2b809b
[ "MIT" ]
16
2020-09-02T17:41:11.000Z
2021-09-11T16:40:41.000Z
examples/Machine Learning/Algorithms/KNN/KNN_Example1.ipynb
mythreyad/Cerbo
ff8ef335ea6b146ef7b5314813b82632ed2b809b
[ "MIT" ]
null
null
null
examples/Machine Learning/Algorithms/KNN/KNN_Example1.ipynb
mythreyad/Cerbo
ff8ef335ea6b146ef7b5314813b82632ed2b809b
[ "MIT" ]
10
2020-09-02T17:56:54.000Z
2022-02-17T22:22:36.000Z
628.263158
81,251
0.764639
[ [ [ "!pip install cerbo", "Collecting cerbo\n Downloading https://files.pythonhosted.org/packages/c0/c0/4d8c9dcda16bb3f701449b598431aba1aae780f0237aa13c1b0fefe2eb48/cerbo-0.0.1-py3-none-any.whl\nInstalling collected packages: cerbo\nSuccessfully installed cerbo-0.0.1\n" ], [ "from cerbo.preprocessing import *\nfrom cerbo.ML import KNN\nimport numpy as np\n(X_train, y_train), (X_test, y_test) = regression_data(X_min=-5, X_max=5, n_samples=2000, n_features=5, noise='low')\n\n# formatting to use the KNN() function!\nX = np.concatenate((X_train, X_test), axis=0)\nY = np.concatenate((y_train, y_test), axis=0)\ndata = {\n \"X\" : X,\n \"y\" : Y\n}\n\nknn, preds = KNN(\"regression\", 5, data, 0.3)", "/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning:\n\npandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n\n" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]