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
4a504ad080eb8f684b1aee7bac4d7340829dd0b0
97,717
ipynb
Jupyter Notebook
docs/tutorials/gs-gcnn-honeycomb.ipynb
NetKet/netket
96758e814fc3128e6821564d6cc2852bac40ecf2
[ "Apache-2.0" ]
null
null
null
docs/tutorials/gs-gcnn-honeycomb.ipynb
NetKet/netket
96758e814fc3128e6821564d6cc2852bac40ecf2
[ "Apache-2.0" ]
null
null
null
docs/tutorials/gs-gcnn-honeycomb.ipynb
NetKet/netket
96758e814fc3128e6821564d6cc2852bac40ecf2
[ "Apache-2.0" ]
null
null
null
97.134195
17,416
0.846618
[ [ [ "# Symmetries: Honeycomb Heisenberg model\n\nThe goal of this tutorial is to learn about group convolutional neural networks (G-CNNs), a useful tool for simulating lattices with high symmetry. \nThe G-CNN is a generalization to the convolutional neural network (CNN) to non-abelian symmetry groups (groups that contain at least one pair of non-commuting elements). \nG-CNNs are a natural fit for lattices that have both point group and translational symmetries, as rotations, reflections and translations don't commute with one-another.\nG-CNN can be used to study both the ground-state and excited-states.\n\nIn this tutorial we will learn the ground state of the antiferromagnetic Heisenberg model on the honeycomb lattice. The Heisenberg Hamiltonian is defined as follows:\n\n$$ H = \\sum_{i,j \\in \\langle \\rangle} \\vec{\\sigma}_{i} \\cdot \\vec{\\sigma}_{j},$$\n\nwhere $\\vec{\\sigma}_{i}$ are Pauli matrices and $<>$ denotes nearest neighbor interactions. \n\nFor this tutorial, many of the calculations will be much faster on a GPU. \nIf you don't have access to a GPU, you can open a [Google Colab](https://colab.research.google.com/) notebook, and set runtime type to GPU. \nTo launch this notebook on Colab simply press the rocket button on the top bar.\n\nThis tutorial wil be split into two parts:\n - First I'll provide a brief introduction to G-CNNs and describe what advantages they bring. \n - Second, we'll use NetKet to find the ground state of the antiferromagnetic Heisenberg model on the honeycomb lattice. First we will simulate a lattice with $N=18$ sites in order to compare with exact diagonalization. Then we will simulate a lattice with $N=72$ sites. ", "_____no_output_____" ], [ "## G-CNNs are generalizations of CNNs to non-abelian groups\n\nThe convolutional neural network (CNN) has revolutionized the field of computer vision. The CNN enforces translational invariance, which means that feeding a CNN translated copies of an image will produce the exact same output. This is important for recognizing objects, which may located differently in different images.\n\nThe hidden layers of a CNN contain a group of ${\\bf features}$, corresponding to translations of the image, where each feature is represented by a vector. At each layer, the CNN integrates over these features to produce a different set of features over the translation group:\n\n$$ C^i_{x,y} = \\sum_h {\\bf W}_{x'-x, y'-y} \\cdot {\\bf f}_{x,y} $$\n\nAs you can see, the index of the filter W is based on the displacement between the input feature {x',y'} and the output feature {x, y}. This is known as an equivariant operation, as displacements in the input are propagated as displacements in the output (equivariance is actually bit more general, we'll get to that in a moment). In the last layer, the CNN averages over these different features, forcing the output to be invariant to the input. \n\nTo generalize the CNN to the G-CNN, lets abstract away from the specifics of the convolution. Instead of indexing the features with translations, we will use elements from a general symmetry group which may contain non-commuting operations. In this case we must define a particular order of operations. For example, we could define an operation in the $p6m$ space group, as a translation, followed by a rotation and a reflection about the origin. Non-abelian groups still maintain associativity and a closed algebra. This is easy to see with lattice symmetry groups. If two successive symmetry operations leave the lattice unchanged, applying both must also leave the lattice unchanged and therefore be symmetry operation in the group. \n\nFor G-convolutions, the building blocks of the G-CNN, this algebra is all we need. The G-convolution also indexes the filters by looking at the \"difference\" between group elements, however this time there is an orientation to it. The G-convolution is defined as follows: \n\n$$ C^i_g = \\sum_h {\\bf W}_{g^{-1} h} \\cdot {\\bf f}_h $$\n\nThe filters are indexed by $g^{-1} h$, which describes the mapping from $g \\rightarrow h$ but not vice-versa. This causes the output to be an ${\\bf involution}$ of the input, meaning that the group elements are mapped to their respective inverses.\n\nG-convolutions are the most expressive linear transformation over a particular symmetry group. Therefore, if you want to define a linear-based model with a particular symmetry, G-CNNs maximize the number of parameters you can fit into a given memory profile. G-CNNs can be mapped down to other symmetry-averaged multi-layer linear models by masking filters (setting them to zero). On the Honeycomb lattice, the G-CNN (approximately) has a factor of 12 more parameters than a CNN averaged over $d_6$ and a factor of $12 N$ more parameters than a feedforward neural network averaged over $p6m$ (where N is the number of sites) under an identical memory constraint. \n\nIf you'd like to learn more about G-CNNs, check out the [original paper](http://proceedings.mlr.press/v48/cohenc16.pdf) by Cohen ${\\it et \\ al.}$ or [this paper](https://arxiv.org/pdf/2104.05085.pdf) by Roth ${\\it et \\ al.}$ that applies G-CNNs to quantum many-body systems.", "_____no_output_____" ] ], [ [ "%pip install --quiet netket", "\u001b[33mWARNING: You are using pip version 22.0.2; however, version 22.0.3 is available.\nYou should consider upgrading via the '/home/filippovicentini/Documents/pythonenvs/utils-jupuyterlab/bin/python -m pip install --upgrade pip' command.\u001b[0m\u001b[33m\n\u001b[0mNote: you may need to restart the kernel to use updated packages.\n" ], [ "import netket as nk\n\n# Import Json, this will be needed to examine log files\nimport json\n\n# Helper libraries\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## Defining the Hamiltonian\n\nWe begin by defining the Hamiltonian as a list of lattice points. NetKet will automatically convert these points into a graph with nearest neighbor connections. The honeycomb lattice is a triangular lattice with two sites per unit cell.", "_____no_output_____" ] ], [ [ "#Basis Vectors that define the positioning of the unit cell\nbasis_vectors = [[0,1],[np.sqrt(3)/2,-1/2]]\n\n#Locations of atoms within the unit cell\natom_positions = [[0,0],[np.sqrt(3)/6,1/2]]\n\n#Number of unit cells in each direction\ndimensions = [3,3]\n\n#Define the graph \ngraph = nk.graph.Lattice(basis_vectors=basis_vectors, \n atoms_coord = atom_positions, \n extent = dimensions\n )", "_____no_output_____" ] ], [ [ "Lets check to see if our graph looks as expected. Since we have two sites per unit cell, we should have $3 \\times 3 \\times 2 = 18$ sites. The coordination number of a hexagonal lattice is 3, so we should have $\\frac{18 \\times 3}{2} = 27$ edges. Finally we have p6m symmetry, which should give ue $3 \\times 3 \\times 12 = 108$ symmetry operations.", "_____no_output_____" ] ], [ [ "#Use Netket to find symmetries of the graph\nsymmetries = graph.automorphisms()\n\n#Check that graph info is correct\nprint(graph.n_nodes)\nprint(graph.n_edges)\nprint(len(symmetries))", "18\n27\n216\n" ] ], [ [ "Oops! It looks like we have twice as many symmetries elements as we thought. Luckily for us, the ground state is still symmetric with respect to this extra symmetry that is unique to the $3 \\times 3$ lattice. We use this graph to define our Hilbert space and Hamiltonian:", "_____no_output_____" ] ], [ [ "# Define the Hilbert space\nhi = nk.hilbert.Spin(s=1 / 2, N=graph.n_nodes, total_sz = 0)\n\n#Define the Hamiltonian\nha = nk.operator.Heisenberg(hilbert=hi, graph=graph, sign_rule=True)", "_____no_output_____" ] ], [ [ "Since the Hexagonal lattice is bipartite, we know the phases obey a Marshall-Peierls sign rule. Therefore, we can use a real valued NN and just learn the amplitudes of the wavefunction. \n\nFor models with a more complicated phase structure, its often better to learn the phases in an equal-amplitude configuration before training the amplitudes as detailed in [this paper](https://journals.aps.org/prresearch/pdf/10.1103/PhysRevResearch.2.033075). This can be implemented by first optimizing the weights on a modified model that sets $Re[log(\\psi)] = 0$ \n\nWe also optimize over states with total $S_z$ of zero since we know the ground state has spin 0.\n\n## Defining the GCNN\n\nWe can define a GCNN with an arbitrary number of layers and specify the feature dimension of each layer accordingly:", "_____no_output_____" ] ], [ [ "#Feature dimensions of hidden layers, from first to last\nfeature_dims = (8,8,8,8)\n\n#Number of layers\nnum_layers = 4\n\n#Define the GCNN \nma = nk.models.GCNN(symmetries = symmetries, layers = num_layers, features = feature_dims)", "_____no_output_____" ] ], [ [ "This a G-CNN with four layers, where each hidden layer contains a feature vector of length 8 for each element in p6m. This means that each hidden state has $8 \\times 192 = 768$ nodes. This is a huge model! But since we're not symmetry-averaging, we only need to compute one wavefunction for each ${\\bf \\sigma}$. \n\nFeel free to try different shaped models. By default, the GCNN weights are initialized with variance scaling, which ensures that the activations will be unit-normal throughout the model at the start of training. Additionally, GCNN defaults to a SELU non-linearity, which moves the activations in the direction of unit-normal, even when they start to deviate. These features ensure that our model will behave well, even when we stack a large number of layers. ", "_____no_output_____" ], [ "## Variational Monte Carlo\n\nIn order to perform VMC we need to define a sampler and an optimizer. We sample using Metropolis-Hastings, which uses the exchange rule to propose new states. The exchange rule swaps the spin of two neighbouring sites, keeping the magnetization fixed (in this case, 0). We optimize using stochastic reconfiguration, which uses curvature information to find the best direction of descent.", "_____no_output_____" ] ], [ [ "#Metropolis-Hastings with two spins flipped that are at most second nearest neighbors \nsa = nk.sampler.MetropolisExchange(hilbert = hi, graph=graph, d_max=2)\n\n#Stochastic reconfiguration \nop = nk.optimizer.Sgd(learning_rate=1e-2)\nsr = nk.optimizer.SR(diag_shift=0.01)\n\n#Define a variational state so we can keep the parameters if we like\nvstate = nk.variational.MCState(sampler=sa, model=ma, n_samples=100)\n\n#Define a driver that performs VMC\ngs = nk.driver.VMC(ha, op, sr=sr, variational_state=vstate)", "_____no_output_____" ] ], [ [ "Lets start by running for 100 iterations. This took about 15 seconds per iteration on my CPU and about 1 second per iteration on the Tesla P100 GPU (If you're using the free version of Colab you may get a Tesla K80 which is slightly slower). GPUs are fast! As you'll see later, the speedup is even more pronounced on larger lattices. ", "_____no_output_____" ] ], [ [ "#Run the optimization\ngs.run(n_iter=100, out='out')", "100%|██████████| 100/100 [01:06<00:00, 1.51it/s, Energy=-40.471 ± 0.046 [σ²=0.238, R̂=0.9744]]\n" ] ], [ [ "This should get us under 0.1% error. Lets see how the energy evolves as we train.", "_____no_output_____" ] ], [ [ "#Get data from log and \nenergy = []\ndata=json.load(open(\"out.log\"))\nfor en in data[\"Energy\"][\"Mean\"]:\n energy.append(en)\n \n#plot the energy during the optimization\nplt.xlabel(\"Number of Iterations\")\nplt.ylabel(\"Energy\")\n\nplt.plot(energy)", "_____no_output_____" ] ], [ [ "Looks like the first 40 iterations did most of the work! In order to get a more precise estimate, we can run 100 more iterations with a larger batch size. This will take about 15 minutes on the GPU (If you're using a CPU, I suggest you skip this section). We access the batch size via the variational state. ", "_____no_output_____" ] ], [ [ "#Change batch size\nvstate.n_samples = 1000\n\n#Driver uses new batch size\ngs = nk.driver.VMC(ha, op, sr=sr, variational_state=vstate)\n\n#Run for 100 more iterations\ngs.run(n_iter = 100,out = 'out')", "100%|██████████| 100/100 [10:43<00:00, 6.43s/it, Energy=-40.3884 ± 0.0045 [σ²=0.0207, R̂=1.0033]]\n" ] ], [ [ "You will notice that the variance continues to get even smaller, giving evidence that we are nearing an eigenstate. ", "_____no_output_____" ], [ "## Checking with ED\n\nIt seems likely that our ground state is correct, as we approached an eigenstate with low energy, but lets be safe and check our work. We can do Lanczos diagonalization for small lattices in NetKet. ", "_____no_output_____" ] ], [ [ "#Exact Diagonalization\nE_gs = nk.exact.lanczos_ed(ha, compute_eigenvectors=False)", "_____no_output_____" ] ], [ [ "Lets compare the VMC energy with the ED energy, by taking average energy over the last $20$ iterations", "_____no_output_____" ] ], [ [ "#Get data from larger batch size\nenergy = []\ndata=json.load(open(\"out.log\"))\nfor en in data[\"Energy\"][\"Mean\"]:\n energy.append(en)\n\nvmc_energy_18sites = np.mean(np.asarray(energy)[-20:])/18\n\nED_energy_18sites = E_gs[0]/18\n\nprint(vmc_energy_18sites)\nprint(ED_energy_18sites)\nprint((ED_energy_18sites- vmc_energy_18sites)/ED_energy_18sites)", "-2.2437762156893766\n-2.243814630334411\n1.7120240021148795e-05\n" ] ], [ [ "Looks like our model did a good job! If you just trained for the first 100 iterations the error should be less than $10^{-4}$ and if you trained with the larger batch size, the error should be close to $10^{-5}$", "_____no_output_____" ], [ "## Simulating A Larger Lattice\n\nLets see how the GCNN does on a larger lattice that cannot be simulated with exact diagonalization. We'll do a $6 \\times 6$ lattice which has $72$ sites. We need to redefine a few things:", "_____no_output_____" ] ], [ [ "#Redefine bigger graph\ndimensions = [6,6]\n\n#Define the graph \ngraph = nk.graph.Lattice(basis_vectors=basis_vectors, \n atoms_coord = atom_positions, \n extent = dimensions\n )\n# Redefine the Hilbert/Hamiltonian for larger lattice space\nhi = nk.hilbert.Spin(s=1 / 2, N=graph.n_nodes, total_sz = 0)\nha = nk.operator.Heisenberg(hilbert=hi, graph=graph, sign_rule=True)\n\n# Compute the symmetries for the bigger graph \nsymmetries = graph.automorphisms()\nprint(len(symmetries))\n\n#Redefine everything on bigger graph\nma = nk.models.GCNN(symmetries = symmetries, layers = num_layers, features = feature_dims)\nsa = nk.sampler.MetropolisExchange(hilbert = hi, graph=graph, d_max=2)\nvstate = nk.variational.MCState(sampler=sa, model=ma, n_samples=100, n_discard_per_chain=100)\ngs = nk.driver.VMC(ha, op, sr=sr, variational_state=vstate)", "432\n" ] ], [ [ "Looks like we have no extra symmetries this time, since $6 \\times 6 \\times 12 = 432$. Let's run this model for 100 iterations. You will see that we quickly get close to the ground state. This takes 15 minutes on a P100 GPU", "_____no_output_____" ] ], [ [ "energy = []\nvariance = []\n\ngs.run(n_iter=100,out=\"out\")\n\ndata = json.load(open(\"out.log\"))\n\nfor en in data[\"Energy\"][\"Mean\"]:\n energy.append(en)\nfor var in data[\"Energy\"][\"Variance\"]:\n variance.append(var)\n", "100%|██████████| 100/100 [14:53<00:00, 8.93s/it, Energy=-155.43 ± 0.53 [σ²=31.79, R̂=0.9946]]\n" ] ], [ [ "We can plot the energy and variance to see if we're approaching an eigenstate", "_____no_output_____" ] ], [ [ "plt.xlabel(\"Number of Iterations\")\nplt.ylabel(\"Energy\")\nplt.plot(energy)", "_____no_output_____" ], [ "plt.xlabel(\"Number of Iterations\")\nplt.ylabel(\"Variance\")\nplt.plot(variance)", "_____no_output_____" ] ], [ [ "It seems we are near an eigenstate. We can do a back-of-the-envelope calculation to see if this is a realistic ground state energy\n\n", "_____no_output_____" ] ], [ [ "print(ED_energy_18sites)\nprint(energy[-1]/graph.n_nodes)", "-2.243814630334411\n-2.158805247393738\n" ] ], [ [ "The energy for the bigger lattice is slightly less negative (as is typical for Heisenberg models with PBC) but they are pretty similar. It's clear we are approaching the ground state", "_____no_output_____" ], [ "We will benchmark how well our model is performing by tracking the relationship between the mean and variance of the energy over 400 more iterations. Then we will extrapolate this relationship to estimate the true ground state energy. This can tell us how our error evolves over time.", "_____no_output_____" ] ], [ [ "intervals = 20\n\nen_estimates = []\nvar_estimates = []\n\nfor interval in range(intervals):\n #run for 100 iterations\n gs.run(n_iter=20,out='out')\n\n #load data from iterations\n data = json.load(open(\"out.log\"))\n\n #append energies and variances to data\n for en in data[\"Energy\"][\"Mean\"]:\n energy.append(en)\n for var in data[\"Energy\"][\"Variance\"]:\n variance.append(var)\n\n en_est = np.mean(energy[-20:])\n var_est = np.mean(variance[-20:])\n en_estimates.append(en_est)\n var_estimates.append(var_est)\n\n print('\\n')\n print(en_est)\n print(var_est)", "100%|██████████| 20/20 [02:56<00:00, 8.81s/it, Energy=-157.22 ± 0.32 [σ²=11.34, R̂=0.9780]]" ] ], [ [ "Lets plot the energy vs. variance and draw a line of best fit", "_____no_output_____" ] ], [ [ "plt.xlabel(\"Variance\")\nplt.ylabel(\"Energy\")\nplt.scatter(var_estimates,en_estimates)\nfit = np.polyfit(var_estimates,en_estimates,2)\nx = np.arange(100)*np.max(var_estimates)/100\nplt.plot(x,fit[2] + fit[1]*x + fit[0]*np.square(x))", "_____no_output_____" ] ], [ [ "You can see that that the relationship between energy and variance is fairly well captured by a quadratic function. We can use this extrapolation to estimate the true ground state energy and the error in our wavefunction. Lets estimate the final energy of our Ansatz using our last 10,000 samples", "_____no_output_____" ] ], [ [ "final_en = np.mean(en_estimates[-5:])\nextrapolated_est = fit[2]\n\nprint((extrapolated_est-final_en)/extrapolated_est)", "0.0012942848437390558\n" ] ], [ [ "If everything went well your error should be around .1%!\n\nThis concludes the tutorial. Only an hour ago we knew nothing about the Heisenberg model on a Hexagonal lattice. Now we have an accurate approximation of the ground state wavefunction!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a5072f4cededd1a06e2bbe32716b516d146d9cb
141,354
ipynb
Jupyter Notebook
ipy/nuisance_real_data.ipynb
proj-nuisance/nuisance
7fd6e7e1765c57a7659d591389468fade9263a10
[ "Apache-2.0", "MIT" ]
null
null
null
ipy/nuisance_real_data.ipynb
proj-nuisance/nuisance
7fd6e7e1765c57a7659d591389468fade9263a10
[ "Apache-2.0", "MIT" ]
8
2020-06-29T13:01:22.000Z
2021-01-21T02:05:24.000Z
ipy/nuisance_real_data.ipynb
proj-nuisance/nuisance
7fd6e7e1765c57a7659d591389468fade9263a10
[ "Apache-2.0", "MIT" ]
1
2020-08-11T14:09:25.000Z
2020-08-11T14:09:25.000Z
105.409396
77,668
0.733874
[ [ [ "from nuisancelib import *\n%matplotlib inline", "_____no_output_____" ] ], [ [ "# Merge dataframes containing real MRI data and segmentation statistics", "_____no_output_____" ] ], [ [ "real_files = pd.read_csv('../output/real_output.csv')\nreal_df = pd.DataFrame(real_files,columns=['Date', 'sid', 'ses', 'snr_total', 'TxRefAmp', 'AcquisitionTime', 'SAR',\n 'RepetitionTime', 'Shim1', 'Shim2', 'Shim3', 'Shim4',\n 'Shim5', 'Shim6', 'Shim7', 'Shim8', 'IOPD1', 'IOPD2',\n 'IOPD3', 'IOPD4', 'IOPD5', 'IOPD6'])\n\nsegstats = pd.read_csv('../output/segstats-volume.csv')\nseg_df = pd.DataFrame(segstats,columns=['Date', 'sid', 'ses', 'Background', \"Left-Accumbens-area\", \n \"Left-Amygdala\", \"Left-Caudate\", \"Left-Hippocampus\", \"Left-Pallidum\",\n \"Left-Putamen\", \"Left-Thalamus-Proper\", \"Right-Accumbens-area\", \n \"Right-Amygdala\", \"Right-Caudate\", \"Right-Hippocampus\", \"Right-Pallidum\",\n \"Right-Putamen\", \"Right-Thalamus-Proper\", \"csf\", \"gray\", \"white\"])\nmerged_df = pd.merge(real_df, seg_df, on=['sid', 'ses'], how='outer')\nmerged_df['Date_x'] = pd.to_datetime(merged_df['Date_x'], format=\"%Y%m%d\")\nmerged_df.set_index('Date_x',inplace=True)\n# merged_df", "_____no_output_____" ] ], [ [ "# Interpolate time and merge with earlier dataframe", "_____no_output_____" ] ], [ [ "df3 = pd.read_csv('../data/extractions/anat.csv', parse_dates=['Date'])\ndf3.set_index('Date', inplace=True)\ndf_reindexed = df3.reindex(pd.date_range(start=df3.index.min(), end=df3.index.max(), freq='1D')) \ndf_reindexed.index.names = ['Date_x']\ninterpolated_df = df_reindexed.interpolate(method='time')\n# interpolated_df", "_____no_output_____" ], [ "super_df = pd.merge(merged_df, interpolated_df, left_index=True, right_index=True, suffixes = (\"_real\", \"_qa\"))\n# super_df", "_____no_output_____" ] ], [ [ "# get additional patient data i.e. subject id, session id, switch sex to binary, merge", "_____no_output_____" ] ], [ [ "demographic_df = pd.read_csv('../data/dbic/bids/participants.tsv', sep='\\t')\ndemographic_df = demographic_df.rename(index=str, columns={\"participant_id\": \"sid\"})\nfinal_df = super_df.join(demographic_df.set_index('sid'), on='sid', how='left')\n# final_df", "_____no_output_____" ], [ "# disable chained assignments\npd.options.mode.chained_assignment = None \n\nexpanded_df = pd.DataFrame(final_df,columns=['sid', 'ses', 'Background', \"Left-Accumbens-area\", \n \"Left-Amygdala\", \"Left-Caudate\", \"Left-Hippocampus\", \"Left-Pallidum\",\n \"Left-Putamen\", \"Left-Thalamus-Proper\", \"Right-Accumbens-area\", \n \"Right-Amygdala\", \"Right-Caudate\", \"Right-Hippocampus\", \"Right-Pallidum\",\n \"Right-Putamen\", \"Right-Thalamus-Proper\", \"csf\", \"gray\", \"white\", 'age', \n 'sex', 'snr_total_qa', 'IOPD1_real', 'IOPD2_real', 'IOPD3_real', \n 'IOPD4_real', 'IOPD5_real', 'IOPD6_real'])\nexpanded_df = expanded_df.reset_index()\nexpanded_df = expanded_df.rename(columns={'Date_x': 'Date'})\nexpanded_df['sex_male'] = [0 for item in range(len(expanded_df))]\nexpanded_df.sex_male[expanded_df.sex == 'M'] = int(1)\n# expanded_df", "_____no_output_____" ], [ "dicom_data = pd.read_csv('../output/dicom_data.csv')\ndicom_data = pd.DataFrame(dicom_data,columns=['sid', 'ses', 'PatientWeight'])\nJuly17_df = pd.merge(expanded_df, dicom_data, on=['sid', 'ses'], how='left')\n# July17_df", "_____no_output_____" ], [ "Oct14_df = pd.DataFrame(July17_df, columns=['Date', 'gray', 'age', 'snr_total_qa', 'IOPD1_real', 'IOPD2_real', 'IOPD3_real', \n 'IOPD4_real', 'IOPD5_real', 'IOPD6_real', 'sex_male', 'PatientWeight', \n 'Seasonal (sin)', 'Seasonal (cos)'])", "_____no_output_____" ] ], [ [ "# regress with both snr_total_qa and seasonal data", "_____no_output_____" ] ], [ [ "regress('gray', Oct14_df, real_data=True);", "Statistically significant variables: ['const', 'age', 'sex_male', 'PatientWeight', 'Seasonal (sin)', 'snr_total_qa', 'IOPD2_real']\nFDR-corrected p-values:\n age | Original p-value: 0.000777 | FDR-corrected p-value: 0.00233**\n sex_male | Original p-value: 0.00354 | FDR-corrected p-value: 0.00532**\n PatientWeight | Original p-value: 1.47e-07 | FDR-corrected p-value: 8.82e-07**\n snr_total_qa | Original p-value: 0.00157 | FDR-corrected p-value: 0.00315**\n IOPD | Original p-value: 0.0565 | FDR-corrected p-value: 0.0565\n Seasonal | Original p-value: 0.0293 | FDR-corrected p-value: 0.0352**\n\n\n OLS Regression Results \n==============================================================================\nDep. Variable: gray R-squared: 0.242\nModel: OLS Adj. R-squared: 0.206\nMethod: Least Squares F-statistic: 6.615\nDate: Tue, 16 Jun 2020 Prob (F-statistic): 2.92e-10\nTime: 08:03:56 Log-Likelihood: -3509.2\nNo. Observations: 261 AIC: 7044.\nDf Residuals: 248 BIC: 7091.\nDf Model: 12 \nCovariance Type: nonrobust \n==================================================================================\n coef std err t P>|t| [0.025 0.975]\n----------------------------------------------------------------------------------\nconst 8.117e+05 1.06e+04 76.498 0.000 7.91e+05 8.33e+05\nage -7035.8252 2067.497 -3.403 0.001 -1.11e+04 -2963.733\nsex_male 6.711e+04 2.28e+04 2.944 0.004 2.22e+04 1.12e+05\nPatientWeight 4875.2695 900.855 5.412 0.000 3100.967 6649.572\nSeasonal (sin) -3.643e+04 1.71e+04 -2.129 0.034 -7.01e+04 -2730.779\nSeasonal (cos) 2.373e+04 1.46e+04 1.621 0.106 -5107.551 5.26e+04\nsnr_total_qa -1.643e+04 5141.725 -3.196 0.002 -2.66e+04 -6306.590\nIOPD1_real 9.815e+04 2.66e+05 0.370 0.712 -4.25e+05 6.21e+05\nIOPD2_real 1.57e+06 6.54e+05 2.401 0.017 2.82e+05 2.86e+06\nIOPD3_real -5.839e+05 3.31e+05 -1.766 0.079 -1.23e+06 6.72e+04\nIOPD4_real -6.917e+04 2.83e+05 -0.244 0.807 -6.27e+05 4.89e+05\nIOPD5_real 1.341e+06 7.02e+06 0.191 0.849 -1.25e+07 1.52e+07\nIOPD6_real 9.499e+06 5.19e+06 1.829 0.069 -7.32e+05 1.97e+07\n==============================================================================\nOmnibus: 148.253 Durbin-Watson: 1.927\nProb(Omnibus): 0.000 Jarque-Bera (JB): 1063.636\nSkew: 2.214 Prob(JB): 1.08e-231\nKurtosis: 11.843 Cond. No. 7.80e+03\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n[2] The condition number is large, 7.8e+03. This might indicate that there are\nstrong multicollinearity or other numerical problems.\nAIC: 7044.423088423354\nBIC: 7090.761853718549\n" ] ], [ [ "# regress with only snr_total_qa", "_____no_output_____" ] ], [ [ "regress('gray', Oct14_df, add_qa=True, add_seasonal=False, real_data=True, plot=False)", "Statistically significant variables: ['const', 'age', 'sex_male', 'PatientWeight', 'snr_total_qa']\nFDR-corrected p-values:\n age | Original p-value: 0.000969 | FDR-corrected p-value: 0.00242**\n sex_male | Original p-value: 0.00421 | FDR-corrected p-value: 0.00701**\n PatientWeight | Original p-value: 2.42e-07 | FDR-corrected p-value: 1.21e-06**\n snr_total_qa | Original p-value: 0.0135 | FDR-corrected p-value: 0.0169**\n IOPD | Original p-value: 0.0851 | FDR-corrected p-value: 0.0851\n\n\n OLS Regression Results \n==============================================================================\nDep. Variable: gray R-squared: 0.207\nModel: OLS Adj. R-squared: 0.175\nMethod: Least Squares F-statistic: 6.514\nDate: Sat, 13 Jun 2020 Prob (F-statistic): 6.12e-09\nTime: 19:13:56 Log-Likelihood: -3515.2\nNo. Observations: 261 AIC: 7052.\nDf Residuals: 250 BIC: 7092.\nDf Model: 10 \nCovariance Type: nonrobust \n=================================================================================\n coef std err t P>|t| [0.025 0.975]\n---------------------------------------------------------------------------------\nconst 8.117e+05 1.08e+04 75.055 0.000 7.9e+05 8.33e+05\nage -7035.8252 2107.242 -3.339 0.001 -1.12e+04 -2885.615\nsex_male 6.711e+04 2.32e+04 2.889 0.004 2.14e+04 1.13e+05\nPatientWeight 4875.2695 918.173 5.310 0.000 3066.930 6683.609\nsnr_total_qa -1.238e+04 4976.210 -2.488 0.013 -2.22e+04 -2580.665\nIOPD1_real 1.049e+05 2.71e+05 0.387 0.699 -4.28e+05 6.38e+05\nIOPD2_real 1.286e+06 6.61e+05 1.946 0.053 -1.54e+04 2.59e+06\nIOPD3_real -6.578e+05 3.36e+05 -1.957 0.052 -1.32e+06 4360.066\nIOPD4_real -3.202e+04 2.88e+05 -0.111 0.912 -5.99e+05 5.35e+05\nIOPD5_real -4.112e+06 6.93e+06 -0.593 0.553 -1.78e+07 9.54e+06\nIOPD6_real 9.363e+06 5.29e+06 1.771 0.078 -1.05e+06 1.98e+07\n==============================================================================\nOmnibus: 177.074 Durbin-Watson: 1.843\nProb(Omnibus): 0.000 Jarque-Bera (JB): 1699.648\nSkew: 2.666 Prob(JB): 0.00\nKurtosis: 14.307 Cond. No. 7.55e+03\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n[2] The condition number is large, 7.55e+03. This might indicate that there are\nstrong multicollinearity or other numerical problems.\nAIC: 7052.459006874266\nBIC: 7091.668731354816\n" ] ], [ [ "# regress with only seasonal data", "_____no_output_____" ] ], [ [ "regress('gray', Oct14_df, add_qa=False, real_data=True, plot=False)", "Statistically significant variables: ['const', 'age', 'sex_male', 'PatientWeight', 'Seasonal (sin)', 'IOPD2_real']\nFDR-corrected p-values:\n age | Original p-value: 0.000982 | FDR-corrected p-value: 0.00246**\n sex_male | Original p-value: 0.00425 | FDR-corrected p-value: 0.00708**\n PatientWeight | Original p-value: 2.5e-07 | FDR-corrected p-value: 1.25e-06**\n IOPD | Original p-value: 0.0933 | FDR-corrected p-value: 0.0933\n Seasonal | Original p-value: 0.0336 | FDR-corrected p-value: 0.042**\n\n\n OLS Regression Results \n==============================================================================\nDep. Variable: gray R-squared: 0.208\nModel: OLS Adj. R-squared: 0.173\nMethod: Least Squares F-statistic: 5.951\nDate: Sat, 13 Jun 2020 Prob (F-statistic): 1.34e-08\nTime: 19:13:56 Log-Likelihood: -3515.0\nNo. Observations: 261 AIC: 7054.\nDf Residuals: 249 BIC: 7097.\nDf Model: 11 \nCovariance Type: nonrobust \n==================================================================================\n coef std err t P>|t| [0.025 0.975]\n----------------------------------------------------------------------------------\nconst 8.117e+05 1.08e+04 74.973 0.000 7.9e+05 8.33e+05\nage -7035.8252 2109.544 -3.335 0.001 -1.12e+04 -2881.001\nsex_male 6.711e+04 2.33e+04 2.886 0.004 2.13e+04 1.13e+05\nPatientWeight 4875.2695 919.176 5.304 0.000 3064.919 6685.620\nSeasonal (sin) -3.643e+04 1.75e+04 -2.087 0.038 -7.08e+04 -2046.088\nSeasonal (cos) 2.373e+04 1.49e+04 1.588 0.113 -5693.351 5.31e+04\nIOPD1_real 9.396e+04 2.71e+05 0.347 0.729 -4.4e+05 6.28e+05\nIOPD2_real 1.634e+06 6.67e+05 2.449 0.015 3.2e+05 2.95e+06\nIOPD3_real -4.912e+05 3.36e+05 -1.462 0.145 -1.15e+06 1.71e+05\nIOPD4_real -1.628e+04 2.89e+05 -0.056 0.955 -5.85e+05 5.52e+05\nIOPD5_real 2.776e+04 7.15e+06 0.004 0.997 -1.41e+07 1.41e+07\nIOPD6_real 8.758e+06 5.3e+06 1.654 0.099 -1.67e+06 1.92e+07\n==============================================================================\nOmnibus: 167.925 Durbin-Watson: 1.851\nProb(Omnibus): 0.000 Jarque-Bera (JB): 1452.925\nSkew: 2.524 Prob(JB): 0.00\nKurtosis: 13.398 Cond. No. 7.78e+03\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n[2] The condition number is large, 7.78e+03. This might indicate that there are\nstrong multicollinearity or other numerical problems.\nAIC: 7053.982710245573\nBIC: 7096.756955133445\n" ] ], [ [ "# regress with neither snr_total_qa and seasonal data", "_____no_output_____" ] ], [ [ "regress('gray', Oct14_df, add_qa=False, add_seasonal=False, real_data=True, plot=False)", "Statistically significant variables: ['const', 'age', 'sex_male', 'PatientWeight', 'IOPD2_real']\nFDR-corrected p-values:\n age | Original p-value: 0.0011 | FDR-corrected p-value: 0.00221**\n sex_male | Original p-value: 0.00465 | FDR-corrected p-value: 0.0062**\n PatientWeight | Original p-value: 3.26e-07 | FDR-corrected p-value: 1.3e-06**\n IOPD | Original p-value: 0.115 | FDR-corrected p-value: 0.115\n\n\n OLS Regression Results \n==============================================================================\nDep. Variable: gray R-squared: 0.185\nModel: OLS Adj. R-squared: 0.156\nMethod: Least Squares F-statistic: 6.331\nDate: Sat, 13 Jun 2020 Prob (F-statistic): 4.43e-08\nTime: 19:13:56 Log-Likelihood: -3518.8\nNo. Observations: 261 AIC: 7058.\nDf Residuals: 251 BIC: 7093.\nDf Model: 9 \nCovariance Type: nonrobust \n=================================================================================\n coef std err t P>|t| [0.025 0.975]\n---------------------------------------------------------------------------------\nconst 8.117e+05 1.09e+04 74.197 0.000 7.9e+05 8.33e+05\nage -7035.8252 2131.626 -3.301 0.001 -1.12e+04 -2837.672\nsex_male 6.711e+04 2.35e+04 2.856 0.005 2.08e+04 1.13e+05\nPatientWeight 4875.2695 928.797 5.249 0.000 3046.040 6704.499\nIOPD1_real 1.022e+05 2.74e+05 0.373 0.709 -4.37e+05 6.41e+05\nIOPD2_real 1.369e+06 6.68e+05 2.051 0.041 5.45e+04 2.68e+06\nIOPD3_real -5.678e+05 3.38e+05 -1.679 0.094 -1.23e+06 9.84e+04\nIOPD4_real -5010.5840 2.91e+05 -0.017 0.986 -5.78e+05 5.68e+05\nIOPD5_real -4.599e+06 7.01e+06 -0.656 0.512 -1.84e+07 9.2e+06\nIOPD6_real 8.91e+06 5.35e+06 1.667 0.097 -1.62e+06 1.94e+07\n==============================================================================\nOmnibus: 188.232 Durbin-Watson: 1.801\nProb(Omnibus): 0.000 Jarque-Bera (JB): 2006.763\nSkew: 2.856 Prob(JB): 0.00\nKurtosis: 15.325 Cond. No. 7.55e+03\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n[2] The condition number is large, 7.55e+03. This might indicate that there are\nstrong multicollinearity or other numerical problems.\nAIC: 7057.506596102941\nBIC: 7093.151800176168\n" ] ], [ [ "# get significance of snr_total_qa for all segmentation statistics", "_____no_output_____" ] ], [ [ "targets = ['Background', \"Left-Accumbens-area\", \"Left-Amygdala\", \"Left-Caudate\", \"Left-Hippocampus\", \"Left-Pallidum\",\n \"Left-Putamen\", \"Left-Thalamus-Proper\", \"Right-Accumbens-area\", \n \"Right-Amygdala\", \"Right-Caudate\", \"Right-Hippocampus\", \"Right-Pallidum\",\n \"Right-Putamen\", \"Right-Thalamus-Proper\", \"csf\", \"gray\", \"white\"]\nscrape_var_significance(targets, 'snr_total_qa', July17_df)", "FDR-corrected p-values:\n age | Original p-value: 0.114 | FDR-corrected p-value: 0.228\n sex_male | Original p-value: 1.11e-32 | FDR-corrected p-value: 6.63e-32**\n PatientWeight | Original p-value: 0.000339 | FDR-corrected p-value: 0.00102**\n snr_total_qa | Original p-value: 0.269 | FDR-corrected p-value: 0.323\n IOPD | Original p-value: 0.543 | FDR-corrected p-value: 0.543\n Seasonal | Original p-value: 0.182 | FDR-corrected p-value: 0.273\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.508 | FDR-corrected p-value: 0.762\n sex_male | Original p-value: 0.014 | FDR-corrected p-value: 0.0419**\n PatientWeight | Original p-value: 0.318 | FDR-corrected p-value: 0.636\n snr_total_qa | Original p-value: 0.981 | FDR-corrected p-value: 0.981\n IOPD | Original p-value: 0.00248 | FDR-corrected p-value: 0.0149**\n Seasonal | Original p-value: 0.879 | FDR-corrected p-value: 0.981\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.0011 | FDR-corrected p-value: 0.0033**\n sex_male | Original p-value: 6.4e-18 | FDR-corrected p-value: 3.84e-17**\n PatientWeight | Original p-value: 0.00367 | FDR-corrected p-value: 0.00733**\n snr_total_qa | Original p-value: 0.462 | FDR-corrected p-value: 0.555\n IOPD | Original p-value: 0.0445 | FDR-corrected p-value: 0.0668\n Seasonal | Original p-value: 0.638 | FDR-corrected p-value: 0.638\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.0912 | FDR-corrected p-value: 0.137\n sex_male | Original p-value: 2.16e-09 | FDR-corrected p-value: 1.29e-08**\n PatientWeight | Original p-value: 0.148 | FDR-corrected p-value: 0.177\n snr_total_qa | Original p-value: 0.0881 | FDR-corrected p-value: 0.137\n IOPD | Original p-value: 0.00191 | FDR-corrected p-value: 0.00572**\n Seasonal | Original p-value: 0.955 | FDR-corrected p-value: 0.955\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.0522 | FDR-corrected p-value: 0.104\n sex_male | Original p-value: 5.98e-10 | FDR-corrected p-value: 3.59e-09**\n PatientWeight | Original p-value: 0.00264 | FDR-corrected p-value: 0.00792**\n snr_total_qa | Original p-value: 0.464 | FDR-corrected p-value: 0.464\n IOPD | Original p-value: 0.114 | FDR-corrected p-value: 0.172\n Seasonal | Original p-value: 0.168 | FDR-corrected p-value: 0.202\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.00341 | FDR-corrected p-value: 0.0102**\n sex_male | Original p-value: 5e-38 | FDR-corrected p-value: 3e-37**\n PatientWeight | Original p-value: 0.178 | FDR-corrected p-value: 0.214\n snr_total_qa | Original p-value: 0.564 | FDR-corrected p-value: 0.564\n IOPD | Original p-value: 0.0127 | FDR-corrected p-value: 0.0254**\n Seasonal | Original p-value: 0.16 | FDR-corrected p-value: 0.214\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.772 | FDR-corrected p-value: 0.786\n sex_male | Original p-value: 2.31e-15 | FDR-corrected p-value: 1.39e-14**\n PatientWeight | Original p-value: 0.00626 | FDR-corrected p-value: 0.0188**\n snr_total_qa | Original p-value: 0.464 | FDR-corrected p-value: 0.697\n IOPD | Original p-value: 0.786 | FDR-corrected p-value: 0.786\n Seasonal | Original p-value: 0.0874 | FDR-corrected p-value: 0.175\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.116 | FDR-corrected p-value: 0.233\n sex_male | Original p-value: 4.58e-29 | FDR-corrected p-value: 2.75e-28**\n PatientWeight | Original p-value: 0.000205 | FDR-corrected p-value: 0.000614**\n snr_total_qa | Original p-value: 0.301 | FDR-corrected p-value: 0.361\n IOPD | Original p-value: 0.957 | FDR-corrected p-value: 0.957\n Seasonal | Original p-value: 0.214 | FDR-corrected p-value: 0.321\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.257 | FDR-corrected p-value: 0.385\n sex_male | Original p-value: 1.05e-06 | FDR-corrected p-value: 6.33e-06**\n PatientWeight | Original p-value: 0.724 | FDR-corrected p-value: 0.724\n snr_total_qa | Original p-value: 0.569 | FDR-corrected p-value: 0.683\n IOPD | Original p-value: 0.16 | FDR-corrected p-value: 0.321\n Seasonal | Original p-value: 0.0444 | FDR-corrected p-value: 0.133\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.00354 | FDR-corrected p-value: 0.0106**\n sex_male | Original p-value: 1.32e-19 | FDR-corrected p-value: 7.9e-19**\n PatientWeight | Original p-value: 0.0239 | FDR-corrected p-value: 0.0477**\n snr_total_qa | Original p-value: 0.748 | FDR-corrected p-value: 0.898\n IOPD | Original p-value: 0.0495 | FDR-corrected p-value: 0.0743\n Seasonal | Original p-value: 0.973 | FDR-corrected p-value: 0.973\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.645 | FDR-corrected p-value: 0.83\n sex_male | Original p-value: 3.76e-08 | FDR-corrected p-value: 2.26e-07**\n PatientWeight | Original p-value: 0.692 | FDR-corrected p-value: 0.83\n snr_total_qa | Original p-value: 0.0793 | FDR-corrected p-value: 0.159\n IOPD | Original p-value: 0.0483 | FDR-corrected p-value: 0.145\n Seasonal | Original p-value: 0.893 | FDR-corrected p-value: 0.893\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.00216 | FDR-corrected p-value: 0.00648**\n sex_male | Original p-value: 2.39e-16 | FDR-corrected p-value: 1.43e-15**\n PatientWeight | Original p-value: 0.00879 | FDR-corrected p-value: 0.0176**\n snr_total_qa | Original p-value: 0.277 | FDR-corrected p-value: 0.277\n IOPD | Original p-value: 0.0632 | FDR-corrected p-value: 0.0759\n Seasonal | Original p-value: 0.0546 | FDR-corrected p-value: 0.0759\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.00163 | FDR-corrected p-value: 0.00488**\n sex_male | Original p-value: 1.88e-41 | FDR-corrected p-value: 1.13e-40**\n PatientWeight | Original p-value: 0.0169 | FDR-corrected p-value: 0.0338**\n snr_total_qa | Original p-value: 0.453 | FDR-corrected p-value: 0.506\n IOPD | Original p-value: 0.506 | FDR-corrected p-value: 0.506\n Seasonal | Original p-value: 0.0814 | FDR-corrected p-value: 0.122\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.462 | FDR-corrected p-value: 0.693\n sex_male | Original p-value: 4.21e-18 | FDR-corrected p-value: 2.52e-17**\n PatientWeight | Original p-value: 0.00956 | FDR-corrected p-value: 0.0287**\n snr_total_qa | Original p-value: 0.602 | FDR-corrected p-value: 0.723\n IOPD | Original p-value: 0.791 | FDR-corrected p-value: 0.791\n Seasonal | Original p-value: 0.362 | FDR-corrected p-value: 0.693\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.362 | FDR-corrected p-value: 0.64\n sex_male | Original p-value: 1.27e-30 | FDR-corrected p-value: 7.61e-30**\n PatientWeight | Original p-value: 0.000994 | FDR-corrected p-value: 0.00298**\n snr_total_qa | Original p-value: 0.533 | FDR-corrected p-value: 0.64\n IOPD | Original p-value: 0.989 | FDR-corrected p-value: 0.989\n Seasonal | Original p-value: 0.48 | FDR-corrected p-value: 0.64\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.289 | FDR-corrected p-value: 0.304\n sex_male | Original p-value: 0.0231 | FDR-corrected p-value: 0.0617\n PatientWeight | Original p-value: 1.87e-05 | FDR-corrected p-value: 0.000112**\n snr_total_qa | Original p-value: 0.0308 | FDR-corrected p-value: 0.0617\n IOPD | Original p-value: 0.304 | FDR-corrected p-value: 0.304\n Seasonal | Original p-value: 0.0586 | FDR-corrected p-value: 0.0879\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.000777 | FDR-corrected p-value: 0.00233**\n sex_male | Original p-value: 0.00354 | FDR-corrected p-value: 0.00532**\n PatientWeight | Original p-value: 1.47e-07 | FDR-corrected p-value: 8.82e-07**\n snr_total_qa | Original p-value: 0.00157 | FDR-corrected p-value: 0.00315**\n IOPD | Original p-value: 0.0565 | FDR-corrected p-value: 0.0565\n Seasonal | Original p-value: 0.0293 | FDR-corrected p-value: 0.0352**\n\n\n" ] ], [ [ "# get significance of seasonal for all segmentation statistics", "_____no_output_____" ] ], [ [ "scrape_var_significance(targets, 'Seasonal', July17_df)", "FDR-corrected p-values:\n age | Original p-value: 0.114 | FDR-corrected p-value: 0.228\n sex_male | Original p-value: 1.11e-32 | FDR-corrected p-value: 6.63e-32**\n PatientWeight | Original p-value: 0.000339 | FDR-corrected p-value: 0.00102**\n snr_total_qa | Original p-value: 0.269 | FDR-corrected p-value: 0.323\n IOPD | Original p-value: 0.543 | FDR-corrected p-value: 0.543\n Seasonal | Original p-value: 0.182 | FDR-corrected p-value: 0.273\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.508 | FDR-corrected p-value: 0.762\n sex_male | Original p-value: 0.014 | FDR-corrected p-value: 0.0419**\n PatientWeight | Original p-value: 0.318 | FDR-corrected p-value: 0.636\n snr_total_qa | Original p-value: 0.981 | FDR-corrected p-value: 0.981\n IOPD | Original p-value: 0.00248 | FDR-corrected p-value: 0.0149**\n Seasonal | Original p-value: 0.879 | FDR-corrected p-value: 0.981\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.0011 | FDR-corrected p-value: 0.0033**\n sex_male | Original p-value: 6.4e-18 | FDR-corrected p-value: 3.84e-17**\n PatientWeight | Original p-value: 0.00367 | FDR-corrected p-value: 0.00733**\n snr_total_qa | Original p-value: 0.462 | FDR-corrected p-value: 0.555\n IOPD | Original p-value: 0.0445 | FDR-corrected p-value: 0.0668\n Seasonal | Original p-value: 0.638 | FDR-corrected p-value: 0.638\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.0912 | FDR-corrected p-value: 0.137\n sex_male | Original p-value: 2.16e-09 | FDR-corrected p-value: 1.29e-08**\n PatientWeight | Original p-value: 0.148 | FDR-corrected p-value: 0.177\n snr_total_qa | Original p-value: 0.0881 | FDR-corrected p-value: 0.137\n IOPD | Original p-value: 0.00191 | FDR-corrected p-value: 0.00572**\n Seasonal | Original p-value: 0.955 | FDR-corrected p-value: 0.955\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.0522 | FDR-corrected p-value: 0.104\n sex_male | Original p-value: 5.98e-10 | FDR-corrected p-value: 3.59e-09**\n PatientWeight | Original p-value: 0.00264 | FDR-corrected p-value: 0.00792**\n snr_total_qa | Original p-value: 0.464 | FDR-corrected p-value: 0.464\n IOPD | Original p-value: 0.114 | FDR-corrected p-value: 0.172\n Seasonal | Original p-value: 0.168 | FDR-corrected p-value: 0.202\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.00341 | FDR-corrected p-value: 0.0102**\n sex_male | Original p-value: 5e-38 | FDR-corrected p-value: 3e-37**\n PatientWeight | Original p-value: 0.178 | FDR-corrected p-value: 0.214\n snr_total_qa | Original p-value: 0.564 | FDR-corrected p-value: 0.564\n IOPD | Original p-value: 0.0127 | FDR-corrected p-value: 0.0254**\n Seasonal | Original p-value: 0.16 | FDR-corrected p-value: 0.214\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.772 | FDR-corrected p-value: 0.786\n sex_male | Original p-value: 2.31e-15 | FDR-corrected p-value: 1.39e-14**\n PatientWeight | Original p-value: 0.00626 | FDR-corrected p-value: 0.0188**\n snr_total_qa | Original p-value: 0.464 | FDR-corrected p-value: 0.697\n IOPD | Original p-value: 0.786 | FDR-corrected p-value: 0.786\n Seasonal | Original p-value: 0.0874 | FDR-corrected p-value: 0.175\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.116 | FDR-corrected p-value: 0.233\n sex_male | Original p-value: 4.58e-29 | FDR-corrected p-value: 2.75e-28**\n PatientWeight | Original p-value: 0.000205 | FDR-corrected p-value: 0.000614**\n snr_total_qa | Original p-value: 0.301 | FDR-corrected p-value: 0.361\n IOPD | Original p-value: 0.957 | FDR-corrected p-value: 0.957\n Seasonal | Original p-value: 0.214 | FDR-corrected p-value: 0.321\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.257 | FDR-corrected p-value: 0.385\n sex_male | Original p-value: 1.05e-06 | FDR-corrected p-value: 6.33e-06**\n PatientWeight | Original p-value: 0.724 | FDR-corrected p-value: 0.724\n snr_total_qa | Original p-value: 0.569 | FDR-corrected p-value: 0.683\n IOPD | Original p-value: 0.16 | FDR-corrected p-value: 0.321\n Seasonal | Original p-value: 0.0444 | FDR-corrected p-value: 0.133\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.00354 | FDR-corrected p-value: 0.0106**\n sex_male | Original p-value: 1.32e-19 | FDR-corrected p-value: 7.9e-19**\n PatientWeight | Original p-value: 0.0239 | FDR-corrected p-value: 0.0477**\n snr_total_qa | Original p-value: 0.748 | FDR-corrected p-value: 0.898\n IOPD | Original p-value: 0.0495 | FDR-corrected p-value: 0.0743\n Seasonal | Original p-value: 0.973 | FDR-corrected p-value: 0.973\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.645 | FDR-corrected p-value: 0.83\n sex_male | Original p-value: 3.76e-08 | FDR-corrected p-value: 2.26e-07**\n PatientWeight | Original p-value: 0.692 | FDR-corrected p-value: 0.83\n snr_total_qa | Original p-value: 0.0793 | FDR-corrected p-value: 0.159\n IOPD | Original p-value: 0.0483 | FDR-corrected p-value: 0.145\n Seasonal | Original p-value: 0.893 | FDR-corrected p-value: 0.893\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.00216 | FDR-corrected p-value: 0.00648**\n sex_male | Original p-value: 2.39e-16 | FDR-corrected p-value: 1.43e-15**\n PatientWeight | Original p-value: 0.00879 | FDR-corrected p-value: 0.0176**\n snr_total_qa | Original p-value: 0.277 | FDR-corrected p-value: 0.277\n IOPD | Original p-value: 0.0632 | FDR-corrected p-value: 0.0759\n Seasonal | Original p-value: 0.0546 | FDR-corrected p-value: 0.0759\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.00163 | FDR-corrected p-value: 0.00488**\n sex_male | Original p-value: 1.88e-41 | FDR-corrected p-value: 1.13e-40**\n PatientWeight | Original p-value: 0.0169 | FDR-corrected p-value: 0.0338**\n snr_total_qa | Original p-value: 0.453 | FDR-corrected p-value: 0.506\n IOPD | Original p-value: 0.506 | FDR-corrected p-value: 0.506\n Seasonal | Original p-value: 0.0814 | FDR-corrected p-value: 0.122\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.462 | FDR-corrected p-value: 0.693\n sex_male | Original p-value: 4.21e-18 | FDR-corrected p-value: 2.52e-17**\n PatientWeight | Original p-value: 0.00956 | FDR-corrected p-value: 0.0287**\n snr_total_qa | Original p-value: 0.602 | FDR-corrected p-value: 0.723\n IOPD | Original p-value: 0.791 | FDR-corrected p-value: 0.791\n Seasonal | Original p-value: 0.362 | FDR-corrected p-value: 0.693\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.362 | FDR-corrected p-value: 0.64\n sex_male | Original p-value: 1.27e-30 | FDR-corrected p-value: 7.61e-30**\n PatientWeight | Original p-value: 0.000994 | FDR-corrected p-value: 0.00298**\n snr_total_qa | Original p-value: 0.533 | FDR-corrected p-value: 0.64\n IOPD | Original p-value: 0.989 | FDR-corrected p-value: 0.989\n Seasonal | Original p-value: 0.48 | FDR-corrected p-value: 0.64\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.289 | FDR-corrected p-value: 0.304\n sex_male | Original p-value: 0.0231 | FDR-corrected p-value: 0.0617\n PatientWeight | Original p-value: 1.87e-05 | FDR-corrected p-value: 0.000112**\n snr_total_qa | Original p-value: 0.0308 | FDR-corrected p-value: 0.0617\n IOPD | Original p-value: 0.304 | FDR-corrected p-value: 0.304\n Seasonal | Original p-value: 0.0586 | FDR-corrected p-value: 0.0879\n\n\nFDR-corrected p-values:\n age | Original p-value: 0.000777 | FDR-corrected p-value: 0.00233**\n sex_male | Original p-value: 0.00354 | FDR-corrected p-value: 0.00532**\n PatientWeight | Original p-value: 1.47e-07 | FDR-corrected p-value: 8.82e-07**\n snr_total_qa | Original p-value: 0.00157 | FDR-corrected p-value: 0.00315**\n IOPD | Original p-value: 0.0565 | FDR-corrected p-value: 0.0565\n Seasonal | Original p-value: 0.0293 | FDR-corrected p-value: 0.0352**\n\n\n" ] ], [ [ "# versions used for this code", "_____no_output_____" ] ], [ [ "import pandas as pd, statsmodels as sm\npd.show_versions();\nprint(\"Statsmodels: \", sm.__version__)", "\nINSTALLED VERSIONS\n------------------\ncommit : None\npython : 3.6.4.final.0\npython-bits : 64\nOS : Darwin\nOS-release : 18.6.0\nmachine : x86_64\nprocessor : i386\nbyteorder : little\nLC_ALL : None\nLANG : en_US.UTF-8\nLOCALE : en_US.UTF-8\n\npandas : 1.0.4\nnumpy : 1.18.4\npytz : 2017.3\ndateutil : 2.6.1\npip : 20.1.1\nsetuptools : 38.4.0\nCython : 0.27.3\npytest : 3.3.2\nhypothesis : None\nsphinx : 1.6.6\nblosc : None\nfeather : None\nxlsxwriter : 1.0.2\nlxml.etree : 4.1.1\nhtml5lib : 1.0.1\npymysql : None\npsycopg2 : None\njinja2 : 2.10\nIPython : 6.2.1\npandas_datareader: None\nbs4 : 4.5.3\nbottleneck : 1.2.1\nfastparquet : None\ngcsfs : None\nlxml.etree : 4.1.1\nmatplotlib : 3.2.1\nnumexpr : 2.6.4\nodfpy : None\nopenpyxl : 2.4.10\npandas_gbq : None\npyarrow : None\npytables : None\npytest : 3.3.2\npyxlsb : None\ns3fs : None\nscipy : 1.1.0\nsqlalchemy : 1.2.1\ntables : 3.4.2\ntabulate : None\nxarray : 0.14.1\nxlrd : 1.0.0\nxlwt : 1.2.0\nxlsxwriter : 1.0.2\nnumba : 0.36.2\nStatsmodels: 0.9.0\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a507587c1de37ae942290925de1172b443c8456
2,305
ipynb
Jupyter Notebook
milestones/milestone4.ipynb
CSCI4850/S20-team4-project
89ff9a06b4bafcad2f1dedd8bcc6087f3d88a9e5
[ "MIT" ]
null
null
null
milestones/milestone4.ipynb
CSCI4850/S20-team4-project
89ff9a06b4bafcad2f1dedd8bcc6087f3d88a9e5
[ "MIT" ]
null
null
null
milestones/milestone4.ipynb
CSCI4850/S20-team4-project
89ff9a06b4bafcad2f1dedd8bcc6087f3d88a9e5
[ "MIT" ]
null
null
null
27.440476
145
0.540998
[ [ [ "Milestone 4", "_____no_output_____" ], [ "Deliverable Percent Complete Estimated Completion Date Percent Complete by Next Milestone\n\n Code 100% Apr 21 100%\n Paper 100% Apr 28 100%\n Demo 30% May 5 100%\n Presentation 0% May 7 100%", "_____no_output_____" ], [ "1. What deliverable goals established in the last milestone report were accomplished to the anticipated percentage?\n\nThe net is built and is sufficiently trained for our problem. The paper is completed and will be turned in, tonight.", "_____no_output_____" ], [ "2. What deliverable goals established in the last milestone report were were not accomplished to the anticipated percentage?\n\nWe have not gotten to start our presentation yet, though for all of our other goals we feel as though we are ahead of our initial schedule.", "_____no_output_____" ], [ "3. What are the main deliverable goals to meet before the next milestone report, and who is working on them?\nBefore the next milestone, our main goals are to:\n\n1) Complete the presentation\n\n2) Complete the demo\n\n3) Optimize the net\n\n\nPresentation: Jeffrey and Muhammad\n \nComplete the demo: Tristan and Robbie\n\nOptimize the net: Daniel and Darien", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4a50801db5405f6df58f1fa78c6ade87387efc41
28,574
ipynb
Jupyter Notebook
courses/udacity_intro_to_tensorflow_for_deep_learning/l07c01_saving_and_loading_models.ipynb
co0lster/examples
5982104ba67acf953147e76010b0eeba1051a99c
[ "Apache-2.0" ]
null
null
null
courses/udacity_intro_to_tensorflow_for_deep_learning/l07c01_saving_and_loading_models.ipynb
co0lster/examples
5982104ba67acf953147e76010b0eeba1051a99c
[ "Apache-2.0" ]
null
null
null
courses/udacity_intro_to_tensorflow_for_deep_learning/l07c01_saving_and_loading_models.ipynb
co0lster/examples
5982104ba67acf953147e76010b0eeba1051a99c
[ "Apache-2.0" ]
null
null
null
28.833502
681
0.509029
[ [ [ "##### Copyright 2019 The TensorFlow Authors.", "_____no_output_____" ] ], [ [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.", "_____no_output_____" ] ], [ [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l07c01_saving_and_loading_models.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l07c01_saving_and_loading_models.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n</table>", "_____no_output_____" ], [ "# Saving and Loading Models\n\nIn this tutorial we will learn how we can take a trained model, save it, and then load it back to keep training it or use it to perform inference. In particular, we will use transfer learning to train a classifier to classify images of cats and dogs, just like we did in the previous lesson. We will then take our trained model and save it as an HDF5 file, which is the format used by Keras. We will then load this model, use it to perform predictions, and then continue to train the model. Finally, we will save our trained model as a TensorFlow SavedModel and then we will download it to a local disk, so that it can later be used for deployment in different platforms.", "_____no_output_____" ], [ "\n\n## Concepts that will be covered in this Colab\n\n1. Saving models in HDF5 format for Keras\n2. Saving models in the TensorFlow SavedModel format\n3. Loading models\n4. Download models to Local Disk\n\nBefore starting this Colab, you should reset the Colab environment by selecting `Runtime -> Reset all runtimes...` from menu above.", "_____no_output_____" ], [ "# Imports\n\nIn this Colab we will use the TensorFlow 2.0 Beta version. ", "_____no_output_____" ] ], [ [ "try:\n # Use the %tensorflow_version magic if in colab.\n %tensorflow_version 2.x\nexcept Exception:\n !pip install -U \"tensorflow-gpu==2.0.0rc0\" ", "_____no_output_____" ], [ "!pip install -U tensorflow_hub\n!pip install -U tensorflow_datasets", "_____no_output_____" ] ], [ [ "Some normal imports we've seen before. ", "_____no_output_____" ] ], [ [ "from __future__ import absolute_import, division, print_function, unicode_literals", "_____no_output_____" ], [ "import time\nimport numpy as np\nimport matplotlib.pylab as plt\n\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport tensorflow_datasets as tfds\ntfds.disable_progress_bar()\n\nfrom tensorflow.keras import layers", "_____no_output_____" ] ], [ [ "# Part 1: Load the Cats vs. Dogs Dataset", "_____no_output_____" ], [ "We will use TensorFlow Datasets to load the Dogs vs Cats dataset. ", "_____no_output_____" ] ], [ [ "splits = tfds.Split.ALL.subsplit(weighted=(80, 20))\n\nsplits, info = tfds.load('cats_vs_dogs', with_info=True, as_supervised=True, split = splits)\n\n(train_examples, validation_examples) = splits", "_____no_output_____" ] ], [ [ "The images in the Dogs vs. Cats dataset are not all the same size. So, we need to reformat all images to the resolution expected by MobileNet (224, 224)", "_____no_output_____" ] ], [ [ "def format_image(image, label):\n # `hub` image modules exepct their data normalized to the [0,1] range.\n image = tf.image.resize(image, (IMAGE_RES, IMAGE_RES))/255.0\n return image, label\n\nnum_examples = info.splits['train'].num_examples\n\nBATCH_SIZE = 32\nIMAGE_RES = 224\n\ntrain_batches = train_examples.cache().shuffle(num_examples//4).map(format_image).batch(BATCH_SIZE).prefetch(1)\nvalidation_batches = validation_examples.cache().map(format_image).batch(BATCH_SIZE).prefetch(1)", "_____no_output_____" ] ], [ [ "# Part 2: Transfer Learning with TensorFlow Hub\n\nWe will now use TensorFlow Hub to do Transfer Learning.", "_____no_output_____" ] ], [ [ "URL = \"https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4\"\nfeature_extractor = hub.KerasLayer(URL,\n input_shape=(IMAGE_RES, IMAGE_RES,3))", "_____no_output_____" ] ], [ [ "Freeze the variables in the feature extractor layer, so that the training only modifies the final classifier layer.", "_____no_output_____" ] ], [ [ "feature_extractor.trainable = False", "_____no_output_____" ] ], [ [ "## Attach a classification head\n\nNow wrap the hub layer in a `tf.keras.Sequential` model, and add a new classification layer.", "_____no_output_____" ] ], [ [ "model = tf.keras.Sequential([\n feature_extractor,\n layers.Dense(2, activation='softmax')\n])\n\nmodel.summary()", "_____no_output_____" ] ], [ [ "## Train the model\n\nWe now train this model like any other, by first calling `compile` followed by `fit`.", "_____no_output_____" ] ], [ [ "model.compile(\n optimizer='adam', \n loss=tf.losses.SparseCategoricalCrossentropy(),\n metrics=['accuracy'])\n\nEPOCHS = 3\nhistory = model.fit(train_batches,\n epochs=EPOCHS,\n validation_data=validation_batches)", "_____no_output_____" ] ], [ [ "## Check the predictions\n\nGet the ordered list of class names.", "_____no_output_____" ] ], [ [ "class_names = np.array(info.features['label'].names)\nclass_names", "_____no_output_____" ] ], [ [ "Run an image batch through the model and convert the indices to class names.", "_____no_output_____" ] ], [ [ "image_batch, label_batch = next(iter(train_batches.take(1)))\nimage_batch = image_batch.numpy()\nlabel_batch = label_batch.numpy()\n\npredicted_batch = model.predict(image_batch)\npredicted_batch = tf.squeeze(predicted_batch).numpy()\npredicted_ids = np.argmax(predicted_batch, axis=-1)\npredicted_class_names = class_names[predicted_ids]\npredicted_class_names", "_____no_output_____" ] ], [ [ "Let's look at the true labels and predicted ones.", "_____no_output_____" ] ], [ [ "print(\"Labels: \", label_batch)\nprint(\"Predicted labels: \", predicted_ids)", "_____no_output_____" ], [ "plt.figure(figsize=(10,9))\nfor n in range(30):\n plt.subplot(6,5,n+1)\n plt.imshow(image_batch[n])\n color = \"blue\" if predicted_ids[n] == label_batch[n] else \"red\"\n plt.title(predicted_class_names[n].title(), color=color)\n plt.axis('off')\n_ = plt.suptitle(\"Model predictions (blue: correct, red: incorrect)\")", "_____no_output_____" ] ], [ [ "# Part 3: Save as Keras `.h5` model\n\nNow that we've trained the model, we can save it as an HDF5 file, which is the format used by Keras. Our HDF5 file will have the extension '.h5', and it's name will correpond to the current time stamp.", "_____no_output_____" ] ], [ [ "t = time.time()\n\nexport_path_keras = \"./{}.h5\".format(int(t))\nprint(export_path_keras)\n\nmodel.save(export_path_keras)", "_____no_output_____" ], [ "!ls", "_____no_output_____" ] ], [ [ " You can later recreate the same model from this file, even if you no longer have access to the code that created the model.\n\nThis file includes:\n\n- The model's architecture\n- The model's weight values (which were learned during training)\n- The model's training config (what you passed to `compile`), if any\n- The optimizer and its state, if any (this enables you to restart training where you left off)", "_____no_output_____" ], [ "# Part 4: Load the Keras `.h5` Model\n\nWe will now load the model we just saved into a new model called `reloaded`. We will need to provide the file path and the `custom_objects` parameter. This parameter tells keras how to load the `hub.KerasLayer` from the `feature_extractor` we used for transfer learning.", "_____no_output_____" ] ], [ [ "reloaded = tf.keras.models.load_model(\n export_path_keras, \n # `custom_objects` tells keras how to load a `hub.KerasLayer`\n custom_objects={'KerasLayer': hub.KerasLayer})\n\nreloaded.summary()", "_____no_output_____" ] ], [ [ "We can check that the reloaded model and the previous model give the same result", "_____no_output_____" ] ], [ [ "result_batch = model.predict(image_batch)\nreloaded_result_batch = reloaded.predict(image_batch)", "_____no_output_____" ] ], [ [ "The difference in output should be zero:", "_____no_output_____" ] ], [ [ "(abs(result_batch - reloaded_result_batch)).max()", "_____no_output_____" ] ], [ [ "As we can see, the reult is 0.0, which indicates that both models made the same predictions on the same batch of images.", "_____no_output_____" ], [ "# Keep Training\n\nBesides making predictions, we can also take our `reloaded` model and keep training it. To do this, you can just train the `reloaded` as usual, using the `.fit` method.", "_____no_output_____" ] ], [ [ "EPOCHS = 3\nhistory = reloaded.fit(train_batches,\n epochs=EPOCHS,\n validation_data=validation_batches)", "_____no_output_____" ] ], [ [ "# Part 5: Export as SavedModel\n\n", "_____no_output_____" ], [ "You can also export a whole model to the TensorFlow SavedModel format. SavedModel is a standalone serialization format for Tensorflow objects, supported by TensorFlow serving as well as TensorFlow implementations other than Python. A SavedModel contains a complete TensorFlow program, including weights and computation. It does not require the original model building code to run, which makes it useful for sharing or deploying (with TFLite, TensorFlow.js, TensorFlow Serving, or TFHub).\n\nThe SavedModel files that were created contain:\n\n* A TensorFlow checkpoint containing the model weights.\n* A SavedModel proto containing the underlying Tensorflow graph. Separate graphs are saved for prediction (serving), train, and evaluation. If the model wasn't compiled before, then only the inference graph gets exported.\n* The model's architecture config, if available.\n\n\nLet's save our original `model` as a TensorFlow SavedModel. To do this we will use the `tf.saved_model.save()` function. This functions takes in the model we want to save and the path to the folder where we want to save our model. \n\nThis function will create a folder where you will find an `assets` folder, a `variables` folder, and the `saved_model.pb` file. ", "_____no_output_____" ] ], [ [ "t = time.time()\n\nexport_path_sm = \"./{}\".format(int(t))\nprint(export_path_sm)\n\ntf.saved_model.save(model, export_path_sm)", "_____no_output_____" ], [ "!ls {export_path_sm}", "_____no_output_____" ] ], [ [ "# Part 6: Load SavedModel", "_____no_output_____" ], [ "Now, let's load our SavedModel and use it to make predictions. We use the `tf.saved_model.load()` function to load our SavedModels. The object returned by `tf.saved_model.load` is 100% independent of the code that created it.", "_____no_output_____" ] ], [ [ "reloaded_sm = tf.saved_model.load(export_path_sm)", "_____no_output_____" ] ], [ [ "Now, let's use the `reloaded_sm` (reloaded SavedModel) to make predictions on a batch of images.", "_____no_output_____" ] ], [ [ "reload_sm_result_batch = reloaded_sm(image_batch, training=False).numpy()", "_____no_output_____" ] ], [ [ "We can check that the reloaded SavedModel and the previous model give the same result.", "_____no_output_____" ] ], [ [ "(abs(result_batch - reload_sm_result_batch)).max()", "_____no_output_____" ] ], [ [ "As we can see, the result is 0.0, which indicates that both models made the same predictions on the same batch of images.", "_____no_output_____" ], [ "# Part 7: Loading the SavedModel as a Keras Model\n\nThe object returned by `tf.saved_model.load` is not a Keras object (i.e. doesn't have `.fit`, `.predict`, `.summary`, etc. methods). Therefore, you can't simply take your `reloaded_sm` model and keep training it by running `.fit`. To be able to get back a full keras model from the Tensorflow SavedModel format we must use the `tf.keras.models.load_model` function. This function will work the same as before, except now we pass the path to the folder containing our SavedModel.", "_____no_output_____" ] ], [ [ "t = time.time()\n\nexport_path_sm = \"./{}\".format(int(t))\nprint(export_path_sm)\ntf.saved_model.save(model, export_path_sm)", "_____no_output_____" ], [ "reload_sm_keras = tf.keras.models.load_model(\n export_path_sm,\n custom_objects={'KerasLayer': hub.KerasLayer})\n\nreload_sm_keras.summary()", "_____no_output_____" ] ], [ [ "Now, let's use the `reloaded_sm)keras` (reloaded Keras model from our SavedModel) to make predictions on a batch of images.", "_____no_output_____" ] ], [ [ "result_batch = model.predict(image_batch)\nreload_sm_keras_result_batch = reload_sm_keras.predict(image_batch)", "_____no_output_____" ] ], [ [ "We can check that the reloaded Keras model and the previous model give the same result.", "_____no_output_____" ] ], [ [ "(abs(result_batch - reload_sm_keras_result_batch)).max()", "_____no_output_____" ] ], [ [ "# Part 8: Download your model", "_____no_output_____" ], [ "You can download the SavedModel to your local disk by creating a zip file. We wil use the `-r` (recursice) option to zip all subfolders. ", "_____no_output_____" ] ], [ [ "!zip -r model.zip {export_path_sm}", "_____no_output_____" ] ], [ [ "The zip file is saved in the current working directory. You can see what the current working directory is by running:", "_____no_output_____" ] ], [ [ "!ls", "_____no_output_____" ] ], [ [ "Once the file is zipped, you can download it to your local disk. ", "_____no_output_____" ] ], [ [ "try:\n from google.colab import files\n files.download('./model.zip')\nexcept ImportError:\n pass", "_____no_output_____" ] ], [ [ "The `files.download` command will search for files in your current working directory. If the file you want to download is in a directory other than the current working directory, you have to include the path to the directory where the file is located.", "_____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" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a50920ba4c682bdcbf53b266ab6cbc9b5aa7792
218,246
ipynb
Jupyter Notebook
analysis/spheroid/20190719-co-culture/eda.ipynb
hammerlab/spheroid
cc6a6677595a3cf176a3b7d91d23d42d0e47e0bb
[ "Apache-2.0" ]
null
null
null
analysis/spheroid/20190719-co-culture/eda.ipynb
hammerlab/spheroid
cc6a6677595a3cf176a3b7d91d23d42d0e47e0bb
[ "Apache-2.0" ]
null
null
null
analysis/spheroid/20190719-co-culture/eda.ipynb
hammerlab/spheroid
cc6a6677595a3cf176a3b7d91d23d42d0e47e0bb
[ "Apache-2.0" ]
null
null
null
1,931.380531
216,116
0.962748
[ [ [ "import os.path as osp\nimport os\nfrom skimage import io\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "img = io.imread('/lab/data/spheroid/20190719-co-culture/raw/20mioTcells-nopeptide/XY02/1_XY02_00017_Z008_CH2.tif')\nimg.shape, img.dtype", "_____no_output_____" ], [ "np.apply_over_axes(np.max, img, [0, 1])", "_____no_output_____" ], [ "plt.imshow(img[..., 1])", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
4a5098eb21d267e134ef816dc77f1c919ef3a397
5,596
ipynb
Jupyter Notebook
006_Python_Sets_Methods/004_Python_Set_clear().ipynb
Maxc390/python-discrete-structures
f7bc7d7caed16f357cc712630b562182355e072b
[ "MIT" ]
175
2021-06-28T03:51:13.000Z
2022-03-25T06:29:14.000Z
006_Python_Sets_Methods/004_Python_Set_clear().ipynb
Wangcx225/02_Python_Datatypes
57828db90aa8d960c62612ed33bb985483442e8a
[ "MIT" ]
null
null
null
006_Python_Sets_Methods/004_Python_Set_clear().ipynb
Wangcx225/02_Python_Datatypes
57828db90aa8d960c62612ed33bb985483442e8a
[ "MIT" ]
164
2021-06-28T03:54:15.000Z
2022-03-25T08:08:53.000Z
26.027907
781
0.534846
[ [ [ "<small><small><i>\nAll the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/02_Python_Datatypes/tree/main/006_Python_Sets_Methods)**\n</i></small></small>", "_____no_output_____" ], [ "# Python Set `clear()`\n\nThe **`clear()`** method removes all elements from the set.\n\n**Syntax**:\n\n```python\nset.clear()\n```", "_____no_output_____" ], [ "## `clear()` Parameters\n\nThe **`clear()`** ethod doesn't take any parameters.", "_____no_output_____" ], [ "## Return Value from `clear()`\n\nThe **`clear()`** method doesn't return any value and returns **`None`**.", "_____no_output_____" ] ], [ [ "# Example 1: Remove all elements from a Python set using clear()\n\n# set of vowels\nvowels = {'a', 'e', 'i', 'o', 'u'}\nprint('Vowels (before clear):', vowels)\n\n# clearing vowels\nvowels.clear()\nprint('Vowels (after clear):', vowels)", "Vowels (before clear): {'u', 'e', 'i', 'o', 'a'}\nVowels (after clear): set()\n" ], [ "# Example 2: Remove all elements from a Python set using clear()\n\nset1 = {\"Welcome\", \"to\", \"Python\", \"course\"}\nset1.clear()\nprint(set1)", "set()\n" ] ], [ [ "### `del()`\n\nThe **[del()](https://github.com/milaan9/01_Python_Introduction/blob/main/Python_Keywords_List.ipynb)** keyword deletes the set.", "_____no_output_____" ] ], [ [ "# Example 1:\n\n#deleting a set\nset1 = {\"Welcome\", \"to\", \"Python\", \"course\"}\ndel set1\nprint(set1)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
4a50a497e3599a106ac609c862e122549176e2ef
96,221
ipynb
Jupyter Notebook
covid-plots-checkpoint.ipynb
SariKal/harjoitus3
0de09474b8c9f235751bb986e641f5870fb33c36
[ "CC0-1.0" ]
null
null
null
covid-plots-checkpoint.ipynb
SariKal/harjoitus3
0de09474b8c9f235751bb986e641f5870fb33c36
[ "CC0-1.0" ]
null
null
null
covid-plots-checkpoint.ipynb
SariKal/harjoitus3
0de09474b8c9f235751bb986e641f5870fb33c36
[ "CC0-1.0" ]
null
null
null
223.769767
28,500
0.894722
[ [ [ "# Covid dataa", "_____no_output_____" ], [ "Tutkitaan tässä harjoituksessa [Our world in data](https://ourworldindata.org/coronavirus)-sivuston dataa päivittäisistä Covid-tapauksista eri maissa.", "_____no_output_____" ] ], [ [ "# Tarvittavat paketit\n\nimport pandas as pd\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "# Luetaan datatiedosto ja katsotaan sisältö\n\ndatasetti = pd.read_csv(\"https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/jhu/biweekly_cases_per_million.csv\")\ndatasetti.head()", "_____no_output_____" ], [ "# Piirretään Suomen koronatapaukset\n\n# Plot-funktiolle voidaan antaa \"label\"-parametri, jos kuvaajan selite halutaan näkyviin.\nplt.plot(datasetti[\"date\"], datasetti[\"Finland\"], label=\"Finland\")\n\n# Näytetään selite\nplt.legend() \n\n# Näytetään kuvaaja\nplt.show()", "_____no_output_____" ] ], [ [ "Huomataan, että x-akseli tulee melko sotkuiseksi jos kaikki päivämäärät piirretään, kuten edellä on tehty. Onglema voidaan korjata käyttämällä Matplotlibin automaattista päivämääränsijoittelutyökalua (AutoDateLocator). Katso alta esimerkki, miten sitä voidaan käyttää.", "_____no_output_____" ] ], [ [ "# Tuodaan AutoDateLocator-työkalu matplotlibin dates-paketista\nfrom matplotlib.dates import AutoDateLocator\n\n# Luodaan uusi kuvaaja\nplt.figure()\n\n# Asetetaan x-akselille automaattinen päivämääräasettelu\nxtick_locator = AutoDateLocator()\nax = plt.gca()\nax.xaxis.set_major_locator(xtick_locator)\n\n# Piirretään kuvaaja\nplt.plot(datasetti[\"date\"], datasetti[\"Finland\"])\n\n# Käännetään x-akselin otsikoita\nplt.xticks(rotation=60)\n\nplt.show()", "_____no_output_____" ] ], [ [ "## Tehtävä:\n\nVertaile useamman eri maan koronatapauksia samassa kuvaajassa ja tee siisti kuvaaja otsikoineen päivineen. Kokeile, saatko päivämäärät siististi x-akselille!", "_____no_output_____" ] ], [ [ "# Piirretään Eestin koronatapaukset\n\n# Plot-funktiolle voidaan antaa \"label\"-parametri, jos kuvaajan selite halutaan näkyviin.\nplt.plot(datasetti[\"date\"], datasetti[\"Estonia\"], label=\"Estonia\")\n\n# Näytetään selite\nplt.legend() \n\n# Näytetään kuvaaja\nplt.show()", "_____no_output_____" ], [ "# Tuodaan AutoDateLocator-työkalu matplotlibin dates-paketista\nfrom matplotlib.dates import AutoDateLocator\n\n# Luodaan uusi kuvaaja\nplt.figure()\n\n# Asetetaan x-akselille automaattinen päivämääräasettelu\nxtick_locator = AutoDateLocator()\nax = plt.gca()\nax.xaxis.set_major_locator(xtick_locator)\n\n# Piirretään kuvaaja\nplt.plot(datasetti[\"date\"], datasetti[\"Finland\"])\nplt.plot(datasetti[\"date\"], datasetti[\"Estonia\"])\nplt.plot(datasetti[\"date\"], datasetti[\"Sweden\"])\n\n\n# Käännetään x-akselin otsikoita\nplt.xticks(rotation=60)\n\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4a50aa7c5bb91a6663ee47109f0e7f140e765855
7,233
ipynb
Jupyter Notebook
week_1/dataset_usage.ipynb
Zork777/ts_summer
f29e4a24a4df14d9a8af6d12eef400e8ddcb8cd2
[ "MIT" ]
2
2021-05-17T09:45:16.000Z
2021-08-11T11:58:09.000Z
week_1/dataset_usage.ipynb
Zork777/ts_summer
f29e4a24a4df14d9a8af6d12eef400e8ddcb8cd2
[ "MIT" ]
null
null
null
week_1/dataset_usage.ipynb
Zork777/ts_summer
f29e4a24a4df14d9a8af6d12eef400e8ddcb8cd2
[ "MIT" ]
2
2021-05-24T18:50:59.000Z
2021-05-30T19:30:56.000Z
22.673981
119
0.5103
[ [ [ "import sys\nfrom pathlib import Path\n\nsys.path.append(str(Path.cwd().parent))", "_____no_output_____" ], [ "from load_dataset import Dataset", "_____no_output_____" ], [ "# Dataset класс, принимающий на вход директорию, содержащую csv файлы формата index, value, позволяющий удобно\n# оперировать с большим количеством временных рядов.", "_____no_output_____" ], [ "dataset = Dataset('../data/dataset/')", "_____no_output_____" ], [ "# метод __repr__ (именно он вызывается, когда мы запускаем ячейку) показывает все ряды из датасета\ndataset", "_____no_output_____" ], [ "# чтобы достать временной ряд, можно просто использовать subscriptable нотацию \ndataset[\"day_2690.csv\"]", "_____no_output_____" ], [ "# dataset является iterable обьектом, на каждом шаге возвращается tuple из имени ряда (имя файла в папке)\n# и самого временного ряда, обьекта pd.Series()", "_____no_output_____" ], [ "for key, ts in dataset:\n print(key)", "day_2690.csv\nday_2135.csv\nday_1164.csv\nday_3015.csv\nday_1158.csv\nday_1776.csv\nday_1762.csv\nday_309.csv\nhour_376.csv\nday_321.csv\nday_335.csv\nday_2531.csv\nhour_1804.csv\nday_1574.csv\nday_1206.csv\nday_2069.csv\nday_3376.csv\nday_687.csv\nday_2915.csv\nday_2901.csv\nday_3148.csv\nday_2256.csv\nday_1039.csv\nday_446.csv\nday_1777.csv\nday_2281.csv\nday_1159.csv\nday_2450.csv\nday_2336.csv\nday_2493.csv\nhour_3380.csv\nday_724.csv\nday_718.csv\nday_2108.csv\nhour_2263.csv\nday_2685.csv\nday_2875.csv\nstl_example.csv\nday_915.csv\nday_929.csv\nday_1403.csv\nday_2888.csv\nhour_3625.csv\nday_1832.csv\nday_1173.csv\nday_2308.csv\nday_1601.csv\nday_1167.csv\nday_2334.csv\nday_493.csv\nday_2283.csv\nday_3610.csv\nday_1007.csv\nday_1761.csv\nday_478.csv\nhour_3553.csv\nhour_3426.csv\nhour_3618.csv\nhour_3387.csv\nhour_3594.csv\nhour_2098.csv\nhour_3621.csv\nhour_3192.csv\nhour_3019.csv\ndaily-min-temperatures.csv\ndow_jones_3.csv\ndow_jones_2.csv\ninternational-airline-passengers.csv\ndow_jones_0.csv\nstd_example.csv\ndow_jones_1.csv\nalcohol_sales.csv\n" ], [ "# чтобы выгрузить весь в оперативную память, можно использовать метод load", "_____no_output_____" ], [ "dataset.load()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a50b18e5d6c7e51d2454e2f2d8adab4d31ce03c
9,424
ipynb
Jupyter Notebook
content/05/04d_crossval.ipynb
emilyntaylor/ledatascifi-2021
7add3109b564a9821d1451461765d0bd0a546197
[ "MIT" ]
1
2021-05-28T17:24:51.000Z
2021-05-28T17:24:51.000Z
content/05/04d_crossval.ipynb
emilyntaylor/ledatascifi-2021
7add3109b564a9821d1451461765d0bd0a546197
[ "MIT" ]
15
2021-02-01T06:23:48.000Z
2021-04-26T12:40:41.000Z
content/05/04d_crossval.ipynb
emilyntaylor/ledatascifi-2021
7add3109b564a9821d1451461765d0bd0a546197
[ "MIT" ]
35
2021-02-01T17:41:34.000Z
2021-09-28T00:41:45.000Z
39.430962
530
0.619588
[ [ [ "# Cross-Validation\n\nCross-validation is a step where we take our training sample and further divide it in many folds, as in the illustration here:\n\n```{image} ./img/feature_5_fold_cv.jpg\n:alt: 5-fold\n:width: 400px\n:align: center\n```\n\nAs we talked about in the last chapter, cross-validation allows us to test our models outside the training data more often. This trick reduces the likelihood of overfitting and improves generalization: It _should_ improve our model's performance when we apply it outside the training data.\n\n```{warning}\nI say \"_should_\" because the exact manner in which you create the folds matters. \n```\n\n\n- **If your data has groups** (i.e. repeated observations for a given firm), you should use [group-wise cross-validation](https://scikit-learn.org/stable/modules/cross_validation.html#group-cv), like `GroupKFold` to make sure no group is in the training and validation partitions of the fold\n- **If your data and/or task is time dependent**, like predicting stock returns, you should use a [time-wise cross-validation](https://scikit-learn.org/stable/modules/cross_validation.html#timeseries-cv), like `TimeSeriesSplit` to ensure that the validation partitions are subsequent to the training sample\n\n```{margin}\nIllustration: If you emulate the simple folding method as depicted in the above graphic for stock return data, some folds will end up testing your model on data from _before_ the periods where the model was estimated!\n```\n\n---\n\n## CV in practice\n\nLike before, let's load the data. Notice I consolidated the import lines at the top. \n", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import Ridge\nfrom sklearn.model_selection import train_test_split\n\nurl = 'https://github.com/LeDataSciFi/ledatascifi-2021/blob/main/data/Fannie_Mae_Plus_Data.gzip?raw=true'\nfannie_mae = pd.read_csv(url,compression='gzip').dropna()\ny = fannie_mae.Original_Interest_Rate\nfannie_mae = (fannie_mae\n .assign(l_credscore = np.log(fannie_mae['Borrower_Credit_Score_at_Origination']),\n l_LTV = np.log(fannie_mae['Original_LTV_(OLTV)']),\n )\n .iloc[:,-11:] # limit to these vars for the sake of this example\n )\n", "_____no_output_____" ] ], [ [ "### **STEP 1:** Set up your test and train split samples", "_____no_output_____" ] ], [ [ "rng = np.random.RandomState(0) # this helps us control the randomness so we can reproduce results exactly\nX_train, X_test, y_train, y_test = train_test_split(fannie_mae, y, random_state=rng)", "_____no_output_____" ] ], [ [ "---\n\n**An important digression:** Now that we've introduced some of the conceptual issues with how you create folds for CV, let's revisit this `test_train_split` code above. [This page](https://scikit-learn.org/stable/modules/cross_validation.html#using-cross-validation-iterators-to-split-train-and-test) says `train_test_split` uses [ShuffleSplit](https://scikit-learn.org/stable/modules/cross_validation.html#random-permutations-cross-validation-a-k-a-shuffle-split). This method does not divide by time or any group type. \n\n```{dropdown} Q: Does this data need special attention to how we divide it up?\n\nA question to ponder, in class perhaps...\n\n```\n\nIf you want to use any other CV iterators to divide up your sample, you can:", "_____no_output_____" ], [ "```python\n# Just replace \"GroupShuffleSplit\" with your CV of choice,\n# and update the contents of split() as needed\n\ntrain_idx, test_idx = next(\n GroupShuffleSplit(random_state=7).split(X, y, groups)\n)\nX_train, X_test, y_train, y_test = X[train_idx], X[train_idx], y[test_idx], y[test_idx]\n```", "_____no_output_____" ], [ "---\n\nBack to our regularly scheduled \"CV in Practice\" programming. ", "_____no_output_____" ], [ "### **STEP 2:** Set up the CV\n\nSK-learn makes cross-validation pretty easy. The `cross_validate(\"estimator\",X_train,y_train,cv,scoring,...)` function ([documentation here](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_validate.html)) will \n1. Create folds in X_train and y_train using the method you put in the `cv` parameter. For each fold, it will create a smaller \"training partition\" and \"testing partition\" like in the figure at the top of this page. \n1. For each fold, \n 1. It will fit your \"estimator\" (as if you ran `estimator.fit(X_trainingpartition,y_trainingpartition)`) on the smaller training partition it creates. **Your estimator will be a \"pipeline\" object** ([covered in detail on the next page](04e_pipelines)) that tells sklearn to apply a series of steps to the data (preprocessing, etc.), culminating in a model.\n 1. Use that fitted estimator on the testing partition (as if you ran `estimator.predict(X_testingpartition)` will apply all of the data transformations in the pipeline and use the estimated model on it)\n 1. Score those predictions with the function(s) you put in `scoring`\n1. Output a dictionary object with performance data\n\nYou can even give it multiple scoring metrics to evaluate. \n\nSo, you need to set up\n\n1. Your preferred folding method (and number of folds)\n1. Your estimator \n1. Your scoring method (you can specify this inside the cross_validate function)\n", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import KFold, cross_validate\n\ncv = KFold(5) # set up fold method\nridge = Ridge(alpha=1.0) # set up model/estimator\ncross_validate(ridge,X_train,y_train,\n cv=cv, scoring='r2') # tell it the scoring method here", "_____no_output_____" ] ], [ [ "```{note} \nWow, that was easy! Just 3 lines of code (and an import)\n```\nAnd we can output test score statistics like:", "_____no_output_____" ] ], [ [ "scores = cross_validate(ridge,X_train,y_train,cv=cv, scoring='r2') \nprint(scores['test_score'].mean()) # scores is just a dictionary\nprint(scores['test_score'].std())", "0.9030537085469961\n0.003162930786979486\n" ] ], [ [ "## Next step: Pipelines\n\nThe model above \n- Only uses a few continuous variables: what if we want to include other variable types (like categorical)?\n- Uses the variables as given: ML algorithms often need you to transform your variables\n- Doesn't deal with any data problems (e.g. missing values or outliers)\n- Doesn't create any interaction terms or polynomial transformations\n- Uses every variable I give it: But if your input data had 400 variables, you'd be in danger of overfitting!\n\nAt this point, you are capable of solving all of these problems. (For example, you could clean the data in pandas.)\n\nBut for our models to be robust to evil monsters like \"data leakage\", we need the fixes to be done within pipelines. ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a50c24c23a473d29e1308245652612d4c48b626
19,294
ipynb
Jupyter Notebook
basics/platzi_data_live.ipynb
sgg10/ingeneria_de_datos_python
a7029302f57e0373fc65eb641bd4f71b9606680b
[ "MIT" ]
null
null
null
basics/platzi_data_live.ipynb
sgg10/ingeneria_de_datos_python
a7029302f57e0373fc65eb641bd4f71b9606680b
[ "MIT" ]
null
null
null
basics/platzi_data_live.ipynb
sgg10/ingeneria_de_datos_python
a7029302f57e0373fc65eb641bd4f71b9606680b
[ "MIT" ]
null
null
null
57.766467
2,772
0.640562
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4a50c51ad4a2c80a5f1e3f4d4cc48ae0f1f29ea0
13,023
ipynb
Jupyter Notebook
praktikum/Basic MNIST Preprocessing with Variational Quantum Circuits.ipynb
FelixBieswanger/masKIT
c649234f15e72050535106dc3d5636608668a6a3
[ "MIT" ]
null
null
null
praktikum/Basic MNIST Preprocessing with Variational Quantum Circuits.ipynb
FelixBieswanger/masKIT
c649234f15e72050535106dc3d5636608668a6a3
[ "MIT" ]
null
null
null
praktikum/Basic MNIST Preprocessing with Variational Quantum Circuits.ipynb
FelixBieswanger/masKIT
c649234f15e72050535106dc3d5636608668a6a3
[ "MIT" ]
null
null
null
30.356643
290
0.539584
[ [ [ "import random\nimport pennylane as qml\nfrom pennylane import numpy as np\nfrom myutils import Datasets\nfrom myutils import Preprocessing\nfrom myutils import Helpers\nimport os\nimport sys\nsys.path.insert(0,'..')\nfrom maskit.datasets import load_data\nfrom matplotlib import pyplot as plt\n\n#Magic Command, so changes in myutils module are reloaded\n%load_ext autoreload\n%autoreload 1\n%aimport myutils", "_____no_output_____" ], [ "# Setting seeds for reproducible results\nnp.random.seed(1337)\nrandom.seed(1337)", "_____no_output_____" ] ], [ [ "# Loading the data\n\nData of interest is MNIST data. As we want to go for reproducible results, we\nwill first go with the option `shuffle=False`. For the rest of the parameters,\nwe now go with the default options. This gives us data for two classes, the\nwritten numbers 6 and 9. We also only get a limited number of sampes, that is\n100 samples for training and 50 for testing. For further details see the\nappropriate docstring.", "_____no_output_____" ] ], [ [ "data= Datasets.get_preprocessed_datasets(\"Autoencoder_6Epochs\")[\"Autoencoder_6Epochs\"][\"6,9\"]", "_____no_output_____" ], [ "data= Datasets.get_preprocessed_datasets(\"PCA\")[\"PCA\"][\"6,9\"]\n\n#scale data 0, 2*np\ndata[\"x_train\"] = Preprocessing.minmax_scaler(data[\"x_train\"] , min = 0,max = 2 * np.pi)\ndata[\"x_test\"] = Preprocessing.minmax_scaler(data[\"x_test\"], min = 0,max = 2 * np.pi)\n\nfor type in [\"y_train_binary\",\"y_test_binary\"]:\n quantum_convert = []\n for i in range(len(data[type])):\n if data[type][i] == 0:\n quantum_convert.append(np.array([0,1]))\n else:\n quantum_convert.append(np.array([1,0]))\n\n data[type+\"_quantum\"] = np.array(quantum_convert)\n\nn = 200\nsplit = 0.75\ndata[\"x_train\"] = data[\"x_train\"][:int(n*split)]\ndata[\"y_train_binary_quantum\"] = data[\"y_train_binary_quantum\"][:int(n*split)]\ndata[\"x_test\"] = data[\"x_test\"][:int(n*(1-split))]\ndata[\"y_test_binary_quantum\"] = data[\"y_test_binary_quantum\"][:int(n*(1-split))]\n\nprint(\"train {}, test{}\".format(int(n*split),int(n*(1-split))))", "train 150, test50\n" ], [ "for type in [\"y_train_binary\",\"y_test_binary\"]:\n quantum_convert = []\n for i in range(len(data[type])):\n if data[type][i] == 0:\n quantum_convert.append(np.array([0,1]))\n else:\n quantum_convert.append(np.array([1,0]))\n\n data[type+\"_quantum\"] = np.array(quantum_convert)", "_____no_output_____" ], [ "n = 200\nsplit = 0.75\ndata[\"x_train\"] = data[\"x_train\"][:int(n*split)]\ndata[\"y_train_binary_quantum\"] = data[\"y_train_binary_quantum\"][:int(n*split)]\ndata[\"x_test\"] = data[\"x_test\"][:int(n*(1-split))]\ndata[\"y_test_binary_quantum\"] = data[\"y_test_binary_quantum\"][:int(n*(1-split))]\n\nprint(\"train {}, test{}\".format(int(n*split),int(n*(1-split))))", "train 150, test50\n" ] ], [ [ "# Setting up a Variational Quantum Circuit for training\n\nThere is an example on the [PennyLane website](https://pennylane.ai/qml/demos/tutorial_variational_classifier.html#iris-classification) for iris data showing a setup for a variational classifier. That is variational quantum circuits that can be trained from labelled (classical) data.", "_____no_output_____" ] ], [ [ "wires = 4\nlayers = 4\nepochs = 5\nparameters = np.random.uniform(low=-np.pi, high=np.pi, size=(layers, wires, 2))", "_____no_output_____" ], [ "def variational_circuit(params):\n for layer in range(layers):\n for wire in range(wires):\n qml.RX(params[layer][wire][0], wires=wire)\n qml.RY(params[layer][wire][1], wires=wire)\n for wire in range(0, wires - 1, 2):\n qml.CZ(wires=[wire, wire + 1])\n for wire in range(1, wires - 1, 2):\n qml.CZ(wires=[wire, wire + 1])\n return qml.expval(qml.PauliZ(0))", "_____no_output_____" ], [ "def variational_training_circuit(params, data):\n qml.templates.embeddings.AngleEmbedding(\n features=data, wires=range(wires), rotation=\"X\"\n )\n return variational_circuit(params)", "_____no_output_____" ], [ "dev = qml.device('default.qubit', wires=wires, shots=1000)\ncircuit = qml.QNode(func=variational_circuit, device=dev)\ntraining_circuit = qml.QNode(func=variational_training_circuit, device=dev)", "_____no_output_____" ], [ "circuit(parameters)", "_____no_output_____" ], [ "drawer = qml.draw(circuit)\nprint(drawer(parameters))", " 0: ──RX(-1.5)───RY(-2.14)───╭C───RX(1.46)────RY(-2.42)──────────────╭C───RX(1.85)───RY(-0.872)─────────────╭C───RX(-0.00221)──RY(-2.02)──────────────╭C──────┤ ⟨Z⟩ \n 1: ──RX(-1.39)──RY(-0.256)──╰Z──╭C───────────RX(-0.715)──RY(0.807)──╰Z──╭C──────────RX(-0.527)──RY(0.529)──╰Z──╭C─────────────RX(-0.546)──RY(-1.89)──╰Z──╭C──┤ \n 2: ──RX(-1.12)──RY(0.116)───╭C──╰Z───────────RX(-2.36)───RY(3.04)───╭C──╰Z──────────RX(1.63)────RY(-1.96)──╭C──╰Z─────────────RX(0.199)───RY(2.09)───╭C──╰Z──┤ \n 3: ──RX(-1.5)───RY(2.99)────╰Z───RX(-0.357)──RY(1.82)───────────────╰Z───RX(-1.33)──RY(1.07)───────────────╰Z───RX(-1.98)─────RY(2.87)───────────────╰Z──────┤ \n\n" ], [ "# some helpers\ndef correctly_classified(params, data, target):\n prediction = training_circuit(params, data)\n if prediction < 0 and target[0] > 0:\n return True\n elif prediction > 0 and target[1] > 0:\n return True\n return False\n\ndef overall_cost_and_correct(cost_fn, params, data, targets):\n cost = correct_count = 0\n for datum, target in zip(data, targets):\n cost += cost_fn(params, datum, target)\n correct_count += int(correctly_classified(params, datum, target))\n return cost, correct_count", "_____no_output_____" ], [ "# Playing with different cost functions\ndef crossentropy_cost(params, data, target):\n prediction = training_circuit(params, data)\n scaled_prediction = prediction + 1 / 2\n predictions = np.array([1 - scaled_prediction, scaled_prediction])\n return cross_entropy(predictions, target)\n\ndef distributed_cost(params, data, target):\n \"\"\"Cost function distributes probabilities to both classes.\"\"\"\n prediction = training_circuit(params, data)\n scaled_prediction = prediction + 1 / 2\n predictions = np.array([1 - scaled_prediction, scaled_prediction])\n return np.sum(np.abs(target - predictions))\n\ndef cost(params, data, target):\n \"\"\"Cost function penalizes choosing wrong class.\"\"\"\n prediction = training_circuit(params, data)\n predictions = np.array([0, prediction]) if prediction > 0 else np.array([prediction * -1, 0])\n return np.sum(np.abs(target - predictions))", "_____no_output_____" ], [ "optimizer = qml.AdamOptimizer()\ncost_fn = distributed_cost", "_____no_output_____" ], [ "start_cost, correct_count = overall_cost_and_correct(cost_fn, parameters, data[\"x_test\"], data[\"y_test_binary_quantum\"])\nprint(\"start cost: {}, with {}/{} correct samples\".format(start_cost,correct_count,len(data[\"y_test_binary_quantum\"])))", "start cost: 32.647999999999996, with 38/50 correct samples\n" ], [ "params = parameters.copy()\nfor _ in range(epochs):\n print(_)\n for datum, target in zip(data_new[\"x_train_pca\"], data_new[\"y_test_binary_quantum\"]):\n params = optimizer.step(lambda weights: cost_fn(weights, datum, target), params)\n\n cost, correct_count = overall_cost_and_correct(cost_fn, params, data_new[\"x_test_pca\"], data_new[\"y_test_binary_quantum\"])\n print(\"cost: {}, with {}/{} correct samples\".format(cost,correct_count,len(data_new[\"y_test_binary_quantum\"])))", "0\ncost: 40.616, with 2/30 correct samples\n1\ncost: 36.952000000000005, with 2/30 correct samples\n2\ncost: 33.104, with 9/30 correct samples\n3\ncost: 30.188000000000002, with 17/30 correct samples\n4\ncost: 29.412, with 17/30 correct samples\n" ], [ "final_cost, correct_count = overall_cost_and_correct(cost_fn, params, data.test_data, data.test_target)\nprint(f\"final cost: {final_cost}, with {co rrect_count}/{len(data.test_target)} correct samples\")", "final cost: 55.660000000000004, with 20/50 correct samples\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a50c84d1235b31a421e8e6289b17ca3ce701ab9
18,769
ipynb
Jupyter Notebook
Project_1B_ Project_Template.ipynb
PPP180000/Data-Engineering-Project_2
e5e79a746511ec615ae34829a46bee7cbd1468d0
[ "Apache-2.0" ]
null
null
null
Project_1B_ Project_Template.ipynb
PPP180000/Data-Engineering-Project_2
e5e79a746511ec615ae34829a46bee7cbd1468d0
[ "Apache-2.0" ]
null
null
null
Project_1B_ Project_Template.ipynb
PPP180000/Data-Engineering-Project_2
e5e79a746511ec615ae34829a46bee7cbd1468d0
[ "Apache-2.0" ]
null
null
null
30.819376
192
0.564921
[ [ [ "# Part I. ETL Pipeline for Pre-Processing the Files", "_____no_output_____" ], [ "## RUNNING THE FOLLOWING CODE FOR PRE-PROCESSING THE FILES", "_____no_output_____" ], [ "#### Import Python packages ", "_____no_output_____" ] ], [ [ "# Import Python packages \nimport pandas as pd\nimport cassandra\nimport re\nimport os\nimport glob\nimport numpy as np\nimport json\nimport csv", "_____no_output_____" ] ], [ [ "#### Creating list of filepaths to process original event csv data files", "_____no_output_____" ] ], [ [ "# checking your current working directory\nprint(os.getcwd())\n\n# Get your current folder and subfolder event data\nfilepath = os.getcwd() + '/event_data'\n\n# Create a for loop to create a list of files and collect each filepath\nfor root, dirs, files in os.walk(filepath):\n \n# join the file path and roots with the subdirectories using glob\n file_path_list = glob.glob(os.path.join(root,'*'))\n #print(file_path_list)", "/home/workspace\n" ] ], [ [ "#### Processing the files to create the data file csv that will be used for Apache Casssandra tables", "_____no_output_____" ] ], [ [ "# initiating an empty list of rows that will be generated from each file\nfull_data_rows_list = [] \n\n# for every filepath in the file path list \nfor f in file_path_list:\n print(f)\n# reading csv file \n with open(f, 'r', encoding = 'utf8', newline='') as csvfile: \n # creating a csv reader object \n csvreader = csv.reader(csvfile) \n next(csvreader)\n \n # extracting each data row one by one and append it \n for line in csvreader:\n #print(line)\n full_data_rows_list.append(line) \n \n# uncomment the code below if you would like to get total number of rows \n#print(len(full_data_rows_list))\n# uncomment the code below if you would like to check to see what the list of event data rows will look like\n#print(full_data_rows_list)\n\n# creating a smaller event data csv file called event_datafile_full csv that will be used to insert data into the \\\n# Apache Cassandra tables\ncsv.register_dialect('myDialect', quoting=csv.QUOTE_ALL, skipinitialspace=True)\n\nwith open('event_datafile_new.csv', 'w', encoding = 'utf8', newline='') as f:\n writer = csv.writer(f, dialect='myDialect')\n writer.writerow(['artist','firstName','gender','itemInSession','lastName','length',\\\n 'level','location','sessionId','song','userId'])\n for row in full_data_rows_list:\n if (row[0] == ''):\n continue\n writer.writerow((row[0], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[12], row[13], row[16]))\n\n \n#Try removing .ipynb_checkpoints to read all the csv files \n#rm -r .ipynb_checkpoints", "/home/workspace/event_data/2018-11-30-events.csv\n/home/workspace/event_data/2018-11-23-events.csv\n/home/workspace/event_data/2018-11-22-events.csv\n/home/workspace/event_data/2018-11-29-events.csv\n/home/workspace/event_data/2018-11-11-events.csv\n/home/workspace/event_data/2018-11-14-events.csv\n/home/workspace/event_data/2018-11-20-events.csv\n/home/workspace/event_data/2018-11-15-events.csv\n/home/workspace/event_data/2018-11-05-events.csv\n/home/workspace/event_data/2018-11-28-events.csv\n/home/workspace/event_data/2018-11-25-events.csv\n/home/workspace/event_data/2018-11-16-events.csv\n/home/workspace/event_data/2018-11-18-events.csv\n/home/workspace/event_data/2018-11-24-events.csv\n/home/workspace/event_data/2018-11-04-events.csv\n/home/workspace/event_data/2018-11-19-events.csv\n/home/workspace/event_data/2018-11-26-events.csv\n/home/workspace/event_data/2018-11-12-events.csv\n/home/workspace/event_data/2018-11-27-events.csv\n/home/workspace/event_data/2018-11-06-events.csv\n/home/workspace/event_data/2018-11-09-events.csv\n/home/workspace/event_data/2018-11-03-events.csv\n/home/workspace/event_data/2018-11-21-events.csv\n/home/workspace/event_data/2018-11-07-events.csv\n/home/workspace/event_data/2018-11-01-events.csv\n/home/workspace/event_data/2018-11-13-events.csv\n/home/workspace/event_data/2018-11-17-events.csv\n/home/workspace/event_data/2018-11-08-events.csv\n/home/workspace/event_data/2018-11-10-events.csv\n/home/workspace/event_data/2018-11-02-events.csv\n" ], [ "# check the number of rows in your csv file\nwith open('event_datafile_new.csv', 'r', encoding = 'utf8') as f:\n print(sum(1 for line in f))", "6821\n" ] ], [ [ "# Part II. The Apache Cassandra coding portion of the project. \n\n## Working with the CSV file titled <font color=red>event_datafile_new.csv</font>, located within the Workspace directory. The event_datafile_new.csv contains the following columns: \n- artist \n- firstName of user\n- gender of user\n- item number in session\n- last name of user\n- length of the song\n- level (paid or free song)\n- location of the user\n- sessionId\n- song title\n- userId\n\nThe image below is a screenshot of what the denormalized data should appear like in the <font color=red>**event_datafile_new.csv**</font> after the code above is run:<br>\n\n<img src=\"images/image_event_datafile_new.jpg\">", "_____no_output_____" ], [ "## Begin writing your Apache Cassandra code in the cells below", "_____no_output_____" ], [ "#### Creating a Cluster", "_____no_output_____" ] ], [ [ "# This should make a connection to a Cassandra instance your local machine \n# (127.0.0.1)\n\nfrom cassandra.cluster import Cluster\ncluster = Cluster()\n\n# To establish connection and begin executing queries, need a session\nsession = cluster.connect()", "_____no_output_____" ] ], [ [ "#### Create Keyspace", "_____no_output_____" ] ], [ [ "# Creating a Keyspace \ntry:\n session.execute(\"\"\"\n CREATE KEYSPACE IF NOT EXISTS udacity \n WITH REPLICATION = \n { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }\"\"\"\n)\n\nexcept Exception as e:\n print(e)", "_____no_output_____" ] ], [ [ "#### Set Keyspace", "_____no_output_____" ] ], [ [ "# Setting KEYSPACE to the keyspace specified above\ntry:\n session.set_keyspace('udacity')\nexcept Exception as e:\n print(e)", "_____no_output_____" ] ], [ [ "## Creating queries to ask the following three questions of the data\n\n### 1. Collecting the artist, song title and song's length in the music app history that was heard during sessionId = 338, and itemInSession = 4 \n\n### Here, we have used sessionId, itemInSession as a primary key because we are following the data having two key conditional column's \n\n\n### 2. Collecting only the following: name of artist, song (sorted by itemInSession) and user (first and last name) for userid = 10, sessionid = 182\n### Here, we have used userId, sessionId, as a primary key and itemInSession as a clustering key \n \n\n### 3. Collecting every user name (first and last) in my music app history who listened to the song 'All Hands Against His Own'\n\n### Here, we have used song, userId as a primary key, since userid is the key column we need in our data\n \n", "_____no_output_____" ], [ "## Query 1", "_____no_output_____" ] ], [ [ "## Query 1: Collecting the artist, song title and song's length in the music app history that was heard during \\\n## sessionId = 338, and itemInSession = 4\nquery = \"CREATE TABLE IF NOT EXISTS song_info\"\nquery = query + \"(sessionId int, itemInSession int, artist text, song text, length double, PRIMARY KEY(sessionId, itemInSession))\"\n\n\ntry:\n session.execute(query)\nexcept Exception as e:\n print(e)", "_____no_output_____" ], [ "# We have provided part of the code to set up the CSV file. Please complete the Apache Cassandra code below#\nfile = 'event_datafile_new.csv'\n\nwith open(file, encoding = 'utf8') as f:\n csvreader = csv.reader(f)\n next(csvreader) # skip header\n for line in csvreader:\n \n## Assigning the INSERT statements into the `query` variable\n## Assigning which column element should be assigned for each column in the INSERT statement.\n query = \"INSERT INTO song_info (sessionId, itemInSession, artist, song, length)\"\n query = query + \"VALUES (%s, %s, %s, %s, %s)\"\n \n ## For e.g., to INSERT artist_name and user first_name, you would change the code below to `line[0], line[1]`\n session.execute(query, (int(line[8]), int(line[3]), line[0], line[9], float(line[5])))\n ", "_____no_output_____" ], [ "## Adding in the SELECT statement to verify the data was entered into the table\nquery = \"SELECT artist, song, length FROM song_info WHERE sessionId=338 AND itemInSession=4 \" \ntry:\n rows = session.execute(query)\nexcept Exception as e:\n print(e)\n\nfor row in rows:\n print(row.artist, row.song, row.length)", "Faithless Music Matters (Mark Knight Dub) 495.3073\n" ] ], [ [ "## Query 2", "_____no_output_____" ] ], [ [ "## Query 2: Collecting only the following: name of artist, song (sorted by itemInSession) and user (first and last name)\\\n## for userid = 10, sessionid = 182\nquery = \"CREATE TABLE IF NOT EXISTS song_playlist_session \"\nquery = query + \"(userId int, sessionId int, itemInSession int, artist text, song text, firstName text, lastName text, \\\n PRIMARY KEY ((userId, sessionId), itemInSession))\"\ntry:\n session.execute(query)\nexcept Exception as e:\n print(e)", "_____no_output_____" ], [ "file = 'event_datafile_new.csv'\nwith open(file, encoding = 'utf8') as f:\n csvreader = csv.reader(f)\n next(csvreader) # skip header\n for line in csvreader:\n## Assigning the INSERT statements into the `query` variable\n query = \"INSERT INTO song_playlist_session (userId, sessionId, itemInSession, artist, song , firstName, lastName)\"\n query = query + \" VALUES (%s, %s, %s, %s, %s, %s, %s)\"\n ## Assigning which column element should be assigned for each column in the INSERT statement.\n ## For e.g., to INSERT artist_name and user first_name, you would change the code below to `line[0], line[1]`\n session.execute(query, (int(line[10]), int(line[8]), int(line[3]), line[0],line[9], line[1],line[4]))", "_____no_output_____" ], [ "query = \"SELECT artist, song, firstName, lastName FROM song_playlist_session WHERE userId=10 AND sessionId=182\"\n#selecting data from user table where userId=10 AND sessionId=182\ntry:\n rows = session.execute(query)\nexcept Exception as e:\n print(e)\n \nfor row in rows:\n print (row.artist, row.song, row.firstname, row.lastname)", "Down To The Bone Keep On Keepin' On Sylvie Cruz\nThree Drives Greece 2000 Sylvie Cruz\nSebastien Tellier Kilometer Sylvie Cruz\nLonnie Gordon Catch You Baby (Steve Pitron & Max Sanna Radio Edit) Sylvie Cruz\n" ] ], [ [ "## Query 3", "_____no_output_____" ] ], [ [ "## Query 3: Collecting every user name (first and last) in my music app history who listened to the song 'All Hands Against His Own'\nquery = \"CREATE TABLE IF NOT EXISTS user_name \"\nquery = query + \"(song text, userId int, firstName text, lastName text, \\\n PRIMARY KEY (song, userId))\"\ntry:\n session.execute(query)\nexcept Exception as e:\n print(e)\n\n ", "_____no_output_____" ], [ "file = 'event_datafile_new.csv'\nwith open(file, encoding = 'utf8') as f:\n csvreader = csv.reader(f)\n next(csvreader) # skip header\n for line in csvreader:\n## Assigning the INSERT statements into the `query` variable\n query = \"INSERT INTO user_name (song, userId, firstName, lastName)\"\n query = query + \" VALUES (%s, %s, %s, %s)\"\n ## Assigning which column element should be assigned for each column in the INSERT statement.\n ## For e.g., to INSERT artist_name and user first_name, you would change the code below to `line[0], line[1]`\n session.execute(query, (line[9], int(line[10]), line[1],line[4]))", "_____no_output_____" ], [ "query = \"SELECT firstName, lastName FROM user_name WHERE song = 'All Hands Against His Own'\"\ntry:\n rows = session.execute(query)\nexcept Exception as e:\n print(e)\n \nfor row in rows:\n print (row.firstname, row.lastname, row.song)", "Jacqueline Lynch All Hands Against His Own\nTegan Levine All Hands Against His Own\nSara Johnson All Hands Against His Own\n" ] ], [ [ "### Dropping the tables before closing out the sessions", "_____no_output_____" ] ], [ [ "## Dropping the table before closing out the sessions\nquery = \"drop table query1\"\ntry:\n rows = session.execute(query)\nexcept Exception as e:\n print(e)\n\nquery = \"drop table user\"\ntry:\n rows = session.execute(query)\nexcept Exception as e:\n print(e)\n \nquery = \"drop table user_name\"\ntry:\n rows = session.execute(query)\nexcept Exception as e:\n print(e)", "_____no_output_____" ] ], [ [ "### Closing the session and cluster connection¶", "_____no_output_____" ] ], [ [ "session.shutdown()\ncluster.shutdown()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a50d2efeb0b1b276c3bb2c70f7daed04f5e210f
68,921
ipynb
Jupyter Notebook
Notebooks/.ipynb_checkpoints/Project Euler -- R-checkpoint.ipynb
darkeclipz/jupyter-notebooks
5de784244ad9db12cfacbbec3053b11f10456d7e
[ "Unlicense" ]
1
2018-08-28T12:16:12.000Z
2018-08-28T12:16:12.000Z
Notebooks/.ipynb_checkpoints/Project Euler -- R-checkpoint.ipynb
darkeclipz/jupyter-notebooks
5de784244ad9db12cfacbbec3053b11f10456d7e
[ "Unlicense" ]
null
null
null
Notebooks/.ipynb_checkpoints/Project Euler -- R-checkpoint.ipynb
darkeclipz/jupyter-notebooks
5de784244ad9db12cfacbbec3053b11f10456d7e
[ "Unlicense" ]
null
null
null
51.820301
250
0.590821
[ [ [ "# Project Euler in R", "_____no_output_____" ], [ "## Number letter counts", "_____no_output_____" ], [ "If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.\n\nIf all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?\n\n\n**NOTE:** Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of \"and\" when writing out numbers is in compliance with British usage.", "_____no_output_____" ] ], [ [ "ones = c('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine')\ntens_ones = c('eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen')\ntens = c('ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety')\nhundreds = c('hundred')", "_____no_output_____" ], [ "split_number = function(x) {\n hundreds = (x - x %% 100) / 100\n tens = (x - x %% 10) / 10 - hundreds * 10\n ones = (x %% 10)\n return (c(hundreds, tens, ones)) \n}", "_____no_output_____" ], [ "split_number(543)", "_____no_output_____" ], [ "spell_number = function(x) {\n word = \"\"\n \n if (x[1] > 0) {\n word = paste(if(x[1] == 1) 'a' else ones[x[1]], \"hundred\")\n }\n \n if(x[1] > 0 && x[2] > 0) {\n word = paste(word, 'and')\n }\n \n if(x[2] == 1) {\n word = paste(word, tens_ones[x[3]])\n }\n\n if(x[2] > 1) {\n word = paste(word, tens[x[2]])\n \n if(x[3] > 0) {\n word = paste(word, \"-\", sep=\"\")\n }\n }\n \n if(x[3] > 0 && x[2] != 1) {\n if(x[1] > 0 && x[2] == 0 && x[3] != 0) {\n word = paste(word, 'and')\n }\n word = paste(word, ones[x[3]], sep=if(x[1] > 0 && x[2] == 0) \" \" else \"\")\n }\n \n if(x[2] == 1 && x[3] == 0) {\n word = paste(word, 'ten', sep='')\n }\n \n return (word)\n}", "_____no_output_____" ], [ "split_number(10)", "_____no_output_____" ], [ "spell_number(split_number(10))", "_____no_output_____" ], [ "spell_number(split_number(119))", "_____no_output_____" ], [ "count_words = function(x) lengths(gregexpr('[a-z]', x))", "_____no_output_____" ], [ "n = 1:1000", "_____no_output_____" ], [ "samples = sample(1000, 50, replace=TRUE)", "_____no_output_____" ], [ "total = 0\nfor (s in 100:999) {\n word = spell_number(split_number(s))\n count = count_words(word)\n total = total + count\n print(paste(s, word, 'letter_count:', count_words(word)))\n}\n\nprint(paste('Total letters:', total))", "[1] \"100 a hundred letter_count: 8\"\n[1] \"101 a hundred and one letter_count: 14\"\n[1] \"102 a hundred and two letter_count: 14\"\n[1] \"103 a hundred and three letter_count: 16\"\n[1] \"104 a hundred and four letter_count: 15\"\n[1] \"105 a hundred and five letter_count: 15\"\n[1] \"106 a hundred and six letter_count: 14\"\n[1] \"107 a hundred and seven letter_count: 16\"\n[1] \"108 a hundred and eight letter_count: 16\"\n[1] \"109 a hundred and nine letter_count: 15\"\n[1] \"110 a hundred and ten letter_count: 14\"\n[1] \"111 a hundred and eleven letter_count: 17\"\n[1] \"112 a hundred and twelve letter_count: 17\"\n[1] \"113 a hundred and thirteen letter_count: 19\"\n[1] \"114 a hundred and fourteen letter_count: 19\"\n[1] \"115 a hundred and fifteen letter_count: 18\"\n[1] \"116 a hundred and sixteen letter_count: 18\"\n[1] \"117 a hundred and seventeen letter_count: 20\"\n[1] \"118 a hundred and eighteen letter_count: 19\"\n[1] \"119 a hundred and nineteen letter_count: 19\"\n[1] \"120 a hundred and twenty letter_count: 17\"\n[1] \"121 a hundred and twenty-one letter_count: 20\"\n[1] \"122 a hundred and twenty-two letter_count: 20\"\n[1] \"123 a hundred and twenty-three letter_count: 22\"\n[1] \"124 a hundred and twenty-four letter_count: 21\"\n[1] \"125 a hundred and twenty-five letter_count: 21\"\n[1] \"126 a hundred and twenty-six letter_count: 20\"\n[1] \"127 a hundred and twenty-seven letter_count: 22\"\n[1] \"128 a hundred and twenty-eight letter_count: 22\"\n[1] \"129 a hundred and twenty-nine letter_count: 21\"\n[1] \"130 a hundred and thirty letter_count: 17\"\n[1] \"131 a hundred and thirty-one letter_count: 20\"\n[1] \"132 a hundred and thirty-two letter_count: 20\"\n[1] \"133 a hundred and thirty-three letter_count: 22\"\n[1] \"134 a hundred and thirty-four letter_count: 21\"\n[1] \"135 a hundred and thirty-five letter_count: 21\"\n[1] \"136 a hundred and thirty-six letter_count: 20\"\n[1] \"137 a hundred and thirty-seven letter_count: 22\"\n[1] \"138 a hundred and thirty-eight letter_count: 22\"\n[1] \"139 a hundred and thirty-nine letter_count: 21\"\n[1] \"140 a hundred and forty letter_count: 16\"\n[1] \"141 a hundred and forty-one letter_count: 19\"\n[1] \"142 a hundred and forty-two letter_count: 19\"\n[1] \"143 a hundred and forty-three letter_count: 21\"\n[1] \"144 a hundred and forty-four letter_count: 20\"\n[1] \"145 a hundred and forty-five letter_count: 20\"\n[1] \"146 a hundred and forty-six letter_count: 19\"\n[1] \"147 a hundred and forty-seven letter_count: 21\"\n[1] \"148 a hundred and forty-eight letter_count: 21\"\n[1] \"149 a hundred and forty-nine letter_count: 20\"\n[1] \"150 a hundred and fifty letter_count: 16\"\n[1] \"151 a hundred and fifty-one letter_count: 19\"\n[1] \"152 a hundred and fifty-two letter_count: 19\"\n[1] \"153 a hundred and fifty-three letter_count: 21\"\n[1] \"154 a hundred and fifty-four letter_count: 20\"\n[1] \"155 a hundred and fifty-five letter_count: 20\"\n[1] \"156 a hundred and fifty-six letter_count: 19\"\n[1] \"157 a hundred and fifty-seven letter_count: 21\"\n[1] \"158 a hundred and fifty-eight letter_count: 21\"\n[1] \"159 a hundred and fifty-nine letter_count: 20\"\n[1] \"160 a hundred and sixty letter_count: 16\"\n[1] \"161 a hundred and sixty-one letter_count: 19\"\n[1] \"162 a hundred and sixty-two letter_count: 19\"\n[1] \"163 a hundred and sixty-three letter_count: 21\"\n[1] \"164 a hundred and sixty-four letter_count: 20\"\n[1] \"165 a hundred and sixty-five letter_count: 20\"\n[1] \"166 a hundred and sixty-six letter_count: 19\"\n[1] \"167 a hundred and sixty-seven letter_count: 21\"\n[1] \"168 a hundred and sixty-eight letter_count: 21\"\n[1] \"169 a hundred and sixty-nine letter_count: 20\"\n[1] \"170 a hundred and seventy letter_count: 18\"\n[1] \"171 a hundred and seventy-one letter_count: 21\"\n[1] \"172 a hundred and seventy-two letter_count: 21\"\n[1] \"173 a hundred and seventy-three letter_count: 23\"\n[1] \"174 a hundred and seventy-four letter_count: 22\"\n[1] \"175 a hundred and seventy-five letter_count: 22\"\n[1] \"176 a hundred and seventy-six letter_count: 21\"\n[1] \"177 a hundred and seventy-seven letter_count: 23\"\n[1] \"178 a hundred and seventy-eight letter_count: 23\"\n[1] \"179 a hundred and seventy-nine letter_count: 22\"\n[1] \"180 a hundred and eighty letter_count: 17\"\n[1] \"181 a hundred and eighty-one letter_count: 20\"\n[1] \"182 a hundred and eighty-two letter_count: 20\"\n[1] \"183 a hundred and eighty-three letter_count: 22\"\n[1] \"184 a hundred and eighty-four letter_count: 21\"\n[1] \"185 a hundred and eighty-five letter_count: 21\"\n[1] \"186 a hundred and eighty-six letter_count: 20\"\n[1] \"187 a hundred and eighty-seven letter_count: 22\"\n[1] \"188 a hundred and eighty-eight letter_count: 22\"\n[1] \"189 a hundred and eighty-nine letter_count: 21\"\n[1] \"190 a hundred and ninety letter_count: 17\"\n[1] \"191 a hundred and ninety-one letter_count: 20\"\n[1] \"192 a hundred and ninety-two letter_count: 20\"\n[1] \"193 a hundred and ninety-three letter_count: 22\"\n[1] \"194 a hundred and ninety-four letter_count: 21\"\n[1] \"195 a hundred and ninety-five letter_count: 21\"\n[1] \"196 a hundred and ninety-six letter_count: 20\"\n[1] \"197 a hundred and ninety-seven letter_count: 22\"\n[1] \"198 a hundred and ninety-eight letter_count: 22\"\n[1] \"199 a hundred and ninety-nine letter_count: 21\"\n[1] \"200 two hundred letter_count: 10\"\n[1] \"201 two hundred and one letter_count: 16\"\n[1] \"202 two hundred and two letter_count: 16\"\n[1] \"203 two hundred and three letter_count: 18\"\n[1] \"204 two hundred and four letter_count: 17\"\n[1] \"205 two hundred and five letter_count: 17\"\n[1] \"206 two hundred and six letter_count: 16\"\n[1] \"207 two hundred and seven letter_count: 18\"\n[1] \"208 two hundred and eight letter_count: 18\"\n[1] \"209 two hundred and nine letter_count: 17\"\n[1] \"210 two hundred and ten letter_count: 16\"\n[1] \"211 two hundred and eleven letter_count: 19\"\n[1] \"212 two hundred and twelve letter_count: 19\"\n[1] \"213 two hundred and thirteen letter_count: 21\"\n[1] \"214 two hundred and fourteen letter_count: 21\"\n[1] \"215 two hundred and fifteen letter_count: 20\"\n[1] \"216 two hundred and sixteen letter_count: 20\"\n[1] \"217 two hundred and seventeen letter_count: 22\"\n[1] \"218 two hundred and eighteen letter_count: 21\"\n[1] \"219 two hundred and nineteen letter_count: 21\"\n[1] \"220 two hundred and twenty letter_count: 19\"\n[1] \"221 two hundred and twenty-one letter_count: 22\"\n[1] \"222 two hundred and twenty-two letter_count: 22\"\n[1] \"223 two hundred and twenty-three letter_count: 24\"\n[1] \"224 two hundred and twenty-four letter_count: 23\"\n[1] \"225 two hundred and twenty-five letter_count: 23\"\n[1] \"226 two hundred and twenty-six letter_count: 22\"\n[1] \"227 two hundred and twenty-seven letter_count: 24\"\n[1] \"228 two hundred and twenty-eight letter_count: 24\"\n[1] \"229 two hundred and twenty-nine letter_count: 23\"\n[1] \"230 two hundred and thirty letter_count: 19\"\n[1] \"231 two hundred and thirty-one letter_count: 22\"\n[1] \"232 two hundred and thirty-two letter_count: 22\"\n[1] \"233 two hundred and thirty-three letter_count: 24\"\n[1] \"234 two hundred and thirty-four letter_count: 23\"\n[1] \"235 two hundred and thirty-five letter_count: 23\"\n[1] \"236 two hundred and thirty-six letter_count: 22\"\n[1] \"237 two hundred and thirty-seven letter_count: 24\"\n[1] \"238 two hundred and thirty-eight letter_count: 24\"\n[1] \"239 two hundred and thirty-nine letter_count: 23\"\n[1] \"240 two hundred and forty letter_count: 18\"\n[1] \"241 two hundred and forty-one letter_count: 21\"\n[1] \"242 two hundred and forty-two letter_count: 21\"\n[1] \"243 two hundred and forty-three letter_count: 23\"\n[1] \"244 two hundred and forty-four letter_count: 22\"\n[1] \"245 two hundred and forty-five letter_count: 22\"\n[1] \"246 two hundred and forty-six letter_count: 21\"\n[1] \"247 two hundred and forty-seven letter_count: 23\"\n[1] \"248 two hundred and forty-eight letter_count: 23\"\n[1] \"249 two hundred and forty-nine letter_count: 22\"\n[1] \"250 two hundred and fifty letter_count: 18\"\n[1] \"251 two hundred and fifty-one letter_count: 21\"\n[1] \"252 two hundred and fifty-two letter_count: 21\"\n[1] \"253 two hundred and fifty-three letter_count: 23\"\n[1] \"254 two hundred and fifty-four letter_count: 22\"\n[1] \"255 two hundred and fifty-five letter_count: 22\"\n[1] \"256 two hundred and fifty-six letter_count: 21\"\n[1] \"257 two hundred and fifty-seven letter_count: 23\"\n[1] \"258 two hundred and fifty-eight letter_count: 23\"\n[1] \"259 two hundred and fifty-nine letter_count: 22\"\n[1] \"260 two hundred and sixty letter_count: 18\"\n[1] \"261 two hundred and sixty-one letter_count: 21\"\n[1] \"262 two hundred and sixty-two letter_count: 21\"\n[1] \"263 two hundred and sixty-three letter_count: 23\"\n[1] \"264 two hundred and sixty-four letter_count: 22\"\n[1] \"265 two hundred and sixty-five letter_count: 22\"\n[1] \"266 two hundred and sixty-six letter_count: 21\"\n[1] \"267 two hundred and sixty-seven letter_count: 23\"\n[1] \"268 two hundred and sixty-eight letter_count: 23\"\n[1] \"269 two hundred and sixty-nine letter_count: 22\"\n[1] \"270 two hundred and seventy letter_count: 20\"\n[1] \"271 two hundred and seventy-one letter_count: 23\"\n[1] \"272 two hundred and seventy-two letter_count: 23\"\n[1] \"273 two hundred and seventy-three letter_count: 25\"\n[1] \"274 two hundred and seventy-four letter_count: 24\"\n[1] \"275 two hundred and seventy-five letter_count: 24\"\n[1] \"276 two hundred and seventy-six letter_count: 23\"\n[1] \"277 two hundred and seventy-seven letter_count: 25\"\n[1] \"278 two hundred and seventy-eight letter_count: 25\"\n[1] \"279 two hundred and seventy-nine letter_count: 24\"\n[1] \"280 two hundred and eighty letter_count: 19\"\n[1] \"281 two hundred and eighty-one letter_count: 22\"\n[1] \"282 two hundred and eighty-two letter_count: 22\"\n[1] \"283 two hundred and eighty-three letter_count: 24\"\n[1] \"284 two hundred and eighty-four letter_count: 23\"\n[1] \"285 two hundred and eighty-five letter_count: 23\"\n[1] \"286 two hundred and eighty-six letter_count: 22\"\n[1] \"287 two hundred and eighty-seven letter_count: 24\"\n[1] \"288 two hundred and eighty-eight letter_count: 24\"\n[1] \"289 two hundred and eighty-nine letter_count: 23\"\n[1] \"290 two hundred and ninety letter_count: 19\"\n[1] \"291 two hundred and ninety-one letter_count: 22\"\n[1] \"292 two hundred and ninety-two letter_count: 22\"\n[1] \"293 two hundred and ninety-three letter_count: 24\"\n[1] \"294 two hundred and ninety-four letter_count: 23\"\n[1] \"295 two hundred and ninety-five letter_count: 23\"\n[1] \"296 two hundred and ninety-six letter_count: 22\"\n[1] \"297 two hundred and ninety-seven letter_count: 24\"\n[1] \"298 two hundred and ninety-eight letter_count: 24\"\n[1] \"299 two hundred and ninety-nine letter_count: 23\"\n[1] \"300 three hundred letter_count: 12\"\n[1] \"301 three hundred and one letter_count: 18\"\n[1] \"302 three hundred and two letter_count: 18\"\n[1] \"303 three hundred and three letter_count: 20\"\n[1] \"304 three hundred and four letter_count: 19\"\n[1] \"305 three hundred and five letter_count: 19\"\n[1] \"306 three hundred and six letter_count: 18\"\n[1] \"307 three hundred and seven letter_count: 20\"\n[1] \"308 three hundred and eight letter_count: 20\"\n[1] \"309 three hundred and nine letter_count: 19\"\n[1] \"310 three hundred and ten letter_count: 18\"\n[1] \"311 three hundred and eleven letter_count: 21\"\n[1] \"312 three hundred and twelve letter_count: 21\"\n[1] \"313 three hundred and thirteen letter_count: 23\"\n[1] \"314 three hundred and fourteen letter_count: 23\"\n[1] \"315 three hundred and fifteen letter_count: 22\"\n[1] \"316 three hundred and sixteen letter_count: 22\"\n[1] \"317 three hundred and seventeen letter_count: 24\"\n[1] \"318 three hundred and eighteen letter_count: 23\"\n[1] \"319 three hundred and nineteen letter_count: 23\"\n[1] \"320 three hundred and twenty letter_count: 21\"\n[1] \"321 three hundred and twenty-one letter_count: 24\"\n[1] \"322 three hundred and twenty-two letter_count: 24\"\n[1] \"323 three hundred and twenty-three letter_count: 26\"\n[1] \"324 three hundred and twenty-four letter_count: 25\"\n[1] \"325 three hundred and twenty-five letter_count: 25\"\n[1] \"326 three hundred and twenty-six letter_count: 24\"\n[1] \"327 three hundred and twenty-seven letter_count: 26\"\n[1] \"328 three hundred and twenty-eight letter_count: 26\"\n[1] \"329 three hundred and twenty-nine letter_count: 25\"\n[1] \"330 three hundred and thirty letter_count: 21\"\n[1] \"331 three hundred and thirty-one letter_count: 24\"\n[1] \"332 three hundred and thirty-two letter_count: 24\"\n[1] \"333 three hundred and thirty-three letter_count: 26\"\n[1] \"334 three hundred and thirty-four letter_count: 25\"\n[1] \"335 three hundred and thirty-five letter_count: 25\"\n[1] \"336 three hundred and thirty-six letter_count: 24\"\n[1] \"337 three hundred and thirty-seven letter_count: 26\"\n[1] \"338 three hundred and thirty-eight letter_count: 26\"\n[1] \"339 three hundred and thirty-nine letter_count: 25\"\n[1] \"340 three hundred and forty letter_count: 20\"\n[1] \"341 three hundred and forty-one letter_count: 23\"\n[1] \"342 three hundred and forty-two letter_count: 23\"\n[1] \"343 three hundred and forty-three letter_count: 25\"\n[1] \"344 three hundred and forty-four letter_count: 24\"\n[1] \"345 three hundred and forty-five letter_count: 24\"\n[1] \"346 three hundred and forty-six letter_count: 23\"\n[1] \"347 three hundred and forty-seven letter_count: 25\"\n[1] \"348 three hundred and forty-eight letter_count: 25\"\n[1] \"349 three hundred and forty-nine letter_count: 24\"\n[1] \"350 three hundred and fifty letter_count: 20\"\n[1] \"351 three hundred and fifty-one letter_count: 23\"\n[1] \"352 three hundred and fifty-two letter_count: 23\"\n[1] \"353 three hundred and fifty-three letter_count: 25\"\n[1] \"354 three hundred and fifty-four letter_count: 24\"\n[1] \"355 three hundred and fifty-five letter_count: 24\"\n[1] \"356 three hundred and fifty-six letter_count: 23\"\n[1] \"357 three hundred and fifty-seven letter_count: 25\"\n[1] \"358 three hundred and fifty-eight letter_count: 25\"\n[1] \"359 three hundred and fifty-nine letter_count: 24\"\n[1] \"360 three hundred and sixty letter_count: 20\"\n[1] \"361 three hundred and sixty-one letter_count: 23\"\n[1] \"362 three hundred and sixty-two letter_count: 23\"\n[1] \"363 three hundred and sixty-three letter_count: 25\"\n[1] \"364 three hundred and sixty-four letter_count: 24\"\n[1] \"365 three hundred and sixty-five letter_count: 24\"\n[1] \"366 three hundred and sixty-six letter_count: 23\"\n[1] \"367 three hundred and sixty-seven letter_count: 25\"\n[1] \"368 three hundred and sixty-eight letter_count: 25\"\n[1] \"369 three hundred and sixty-nine letter_count: 24\"\n[1] \"370 three hundred and seventy letter_count: 22\"\n[1] \"371 three hundred and seventy-one letter_count: 25\"\n[1] \"372 three hundred and seventy-two letter_count: 25\"\n[1] \"373 three hundred and seventy-three letter_count: 27\"\n[1] \"374 three hundred and seventy-four letter_count: 26\"\n[1] \"375 three hundred and seventy-five letter_count: 26\"\n[1] \"376 three hundred and seventy-six letter_count: 25\"\n[1] \"377 three hundred and seventy-seven letter_count: 27\"\n[1] \"378 three hundred and seventy-eight letter_count: 27\"\n[1] \"379 three hundred and seventy-nine letter_count: 26\"\n[1] \"380 three hundred and eighty letter_count: 21\"\n[1] \"381 three hundred and eighty-one letter_count: 24\"\n[1] \"382 three hundred and eighty-two letter_count: 24\"\n[1] \"383 three hundred and eighty-three letter_count: 26\"\n[1] \"384 three hundred and eighty-four letter_count: 25\"\n[1] \"385 three hundred and eighty-five letter_count: 25\"\n[1] \"386 three hundred and eighty-six letter_count: 24\"\n[1] \"387 three hundred and eighty-seven letter_count: 26\"\n[1] \"388 three hundred and eighty-eight letter_count: 26\"\n[1] \"389 three hundred and eighty-nine letter_count: 25\"\n[1] \"390 three hundred and ninety letter_count: 21\"\n[1] \"391 three hundred and ninety-one letter_count: 24\"\n[1] \"392 three hundred and ninety-two letter_count: 24\"\n[1] \"393 three hundred and ninety-three letter_count: 26\"\n[1] \"394 three hundred and ninety-four letter_count: 25\"\n[1] \"395 three hundred and ninety-five letter_count: 25\"\n[1] \"396 three hundred and ninety-six letter_count: 24\"\n[1] \"397 three hundred and ninety-seven letter_count: 26\"\n[1] \"398 three hundred and ninety-eight letter_count: 26\"\n[1] \"399 three hundred and ninety-nine letter_count: 25\"\n[1] \"400 four hundred letter_count: 11\"\n[1] \"401 four hundred and one letter_count: 17\"\n[1] \"402 four hundred and two letter_count: 17\"\n[1] \"403 four hundred and three letter_count: 19\"\n[1] \"404 four hundred and four letter_count: 18\"\n[1] \"405 four hundred and five letter_count: 18\"\n[1] \"406 four hundred and six letter_count: 17\"\n[1] \"407 four hundred and seven letter_count: 19\"\n[1] \"408 four hundred and eight letter_count: 19\"\n[1] \"409 four hundred and nine letter_count: 18\"\n[1] \"410 four hundred and ten letter_count: 17\"\n[1] \"411 four hundred and eleven letter_count: 20\"\n[1] \"412 four hundred and twelve letter_count: 20\"\n[1] \"413 four hundred and thirteen letter_count: 22\"\n[1] \"414 four hundred and fourteen letter_count: 22\"\n[1] \"415 four hundred and fifteen letter_count: 21\"\n[1] \"416 four hundred and sixteen letter_count: 21\"\n[1] \"417 four hundred and seventeen letter_count: 23\"\n[1] \"418 four hundred and eighteen letter_count: 22\"\n[1] \"419 four hundred and nineteen letter_count: 22\"\n[1] \"420 four hundred and twenty letter_count: 20\"\n[1] \"421 four hundred and twenty-one letter_count: 23\"\n[1] \"422 four hundred and twenty-two letter_count: 23\"\n[1] \"423 four hundred and twenty-three letter_count: 25\"\n[1] \"424 four hundred and twenty-four letter_count: 24\"\n[1] \"425 four hundred and twenty-five letter_count: 24\"\n[1] \"426 four hundred and twenty-six letter_count: 23\"\n[1] \"427 four hundred and twenty-seven letter_count: 25\"\n[1] \"428 four hundred and twenty-eight letter_count: 25\"\n[1] \"429 four hundred and twenty-nine letter_count: 24\"\n[1] \"430 four hundred and thirty letter_count: 20\"\n[1] \"431 four hundred and thirty-one letter_count: 23\"\n[1] \"432 four hundred and thirty-two letter_count: 23\"\n[1] \"433 four hundred and thirty-three letter_count: 25\"\n[1] \"434 four hundred and thirty-four letter_count: 24\"\n[1] \"435 four hundred and thirty-five letter_count: 24\"\n[1] \"436 four hundred and thirty-six letter_count: 23\"\n[1] \"437 four hundred and thirty-seven letter_count: 25\"\n[1] \"438 four hundred and thirty-eight letter_count: 25\"\n[1] \"439 four hundred and thirty-nine letter_count: 24\"\n[1] \"440 four hundred and forty letter_count: 19\"\n[1] \"441 four hundred and forty-one letter_count: 22\"\n[1] \"442 four hundred and forty-two letter_count: 22\"\n[1] \"443 four hundred and forty-three letter_count: 24\"\n[1] \"444 four hundred and forty-four letter_count: 23\"\n[1] \"445 four hundred and forty-five letter_count: 23\"\n[1] \"446 four hundred and forty-six letter_count: 22\"\n[1] \"447 four hundred and forty-seven letter_count: 24\"\n[1] \"448 four hundred and forty-eight letter_count: 24\"\n[1] \"449 four hundred and forty-nine letter_count: 23\"\n[1] \"450 four hundred and fifty letter_count: 19\"\n[1] \"451 four hundred and fifty-one letter_count: 22\"\n[1] \"452 four hundred and fifty-two letter_count: 22\"\n[1] \"453 four hundred and fifty-three letter_count: 24\"\n[1] \"454 four hundred and fifty-four letter_count: 23\"\n[1] \"455 four hundred and fifty-five letter_count: 23\"\n[1] \"456 four hundred and fifty-six letter_count: 22\"\n[1] \"457 four hundred and fifty-seven letter_count: 24\"\n[1] \"458 four hundred and fifty-eight letter_count: 24\"\n[1] \"459 four hundred and fifty-nine letter_count: 23\"\n[1] \"460 four hundred and sixty letter_count: 19\"\n[1] \"461 four hundred and sixty-one letter_count: 22\"\n[1] \"462 four hundred and sixty-two letter_count: 22\"\n[1] \"463 four hundred and sixty-three letter_count: 24\"\n[1] \"464 four hundred and sixty-four letter_count: 23\"\n[1] \"465 four hundred and sixty-five letter_count: 23\"\n[1] \"466 four hundred and sixty-six letter_count: 22\"\n[1] \"467 four hundred and sixty-seven letter_count: 24\"\n[1] \"468 four hundred and sixty-eight letter_count: 24\"\n[1] \"469 four hundred and sixty-nine letter_count: 23\"\n[1] \"470 four hundred and seventy letter_count: 21\"\n[1] \"471 four hundred and seventy-one letter_count: 24\"\n[1] \"472 four hundred and seventy-two letter_count: 24\"\n[1] \"473 four hundred and seventy-three letter_count: 26\"\n[1] \"474 four hundred and seventy-four letter_count: 25\"\n[1] \"475 four hundred and seventy-five letter_count: 25\"\n[1] \"476 four hundred and seventy-six letter_count: 24\"\n[1] \"477 four hundred and seventy-seven letter_count: 26\"\n[1] \"478 four hundred and seventy-eight letter_count: 26\"\n[1] \"479 four hundred and seventy-nine letter_count: 25\"\n[1] \"480 four hundred and eighty letter_count: 20\"\n[1] \"481 four hundred and eighty-one letter_count: 23\"\n[1] \"482 four hundred and eighty-two letter_count: 23\"\n[1] \"483 four hundred and eighty-three letter_count: 25\"\n[1] \"484 four hundred and eighty-four letter_count: 24\"\n[1] \"485 four hundred and eighty-five letter_count: 24\"\n[1] \"486 four hundred and eighty-six letter_count: 23\"\n[1] \"487 four hundred and eighty-seven letter_count: 25\"\n[1] \"488 four hundred and eighty-eight letter_count: 25\"\n[1] \"489 four hundred and eighty-nine letter_count: 24\"\n[1] \"490 four hundred and ninety letter_count: 20\"\n[1] \"491 four hundred and ninety-one letter_count: 23\"\n[1] \"492 four hundred and ninety-two letter_count: 23\"\n[1] \"493 four hundred and ninety-three letter_count: 25\"\n[1] \"494 four hundred and ninety-four letter_count: 24\"\n[1] \"495 four hundred and ninety-five letter_count: 24\"\n[1] \"496 four hundred and ninety-six letter_count: 23\"\n[1] \"497 four hundred and ninety-seven letter_count: 25\"\n[1] \"498 four hundred and ninety-eight letter_count: 25\"\n[1] \"499 four hundred and ninety-nine letter_count: 24\"\n[1] \"500 five hundred letter_count: 11\"\n[1] \"501 five hundred and one letter_count: 17\"\n[1] \"502 five hundred and two letter_count: 17\"\n[1] \"503 five hundred and three letter_count: 19\"\n[1] \"504 five hundred and four letter_count: 18\"\n[1] \"505 five hundred and five letter_count: 18\"\n[1] \"506 five hundred and six letter_count: 17\"\n[1] \"507 five hundred and seven letter_count: 19\"\n[1] \"508 five hundred and eight letter_count: 19\"\n[1] \"509 five hundred and nine letter_count: 18\"\n[1] \"510 five hundred and ten letter_count: 17\"\n[1] \"511 five hundred and eleven letter_count: 20\"\n[1] \"512 five hundred and twelve letter_count: 20\"\n[1] \"513 five hundred and thirteen letter_count: 22\"\n[1] \"514 five hundred and fourteen letter_count: 22\"\n[1] \"515 five hundred and fifteen letter_count: 21\"\n[1] \"516 five hundred and sixteen letter_count: 21\"\n[1] \"517 five hundred and seventeen letter_count: 23\"\n[1] \"518 five hundred and eighteen letter_count: 22\"\n[1] \"519 five hundred and nineteen letter_count: 22\"\n[1] \"520 five hundred and twenty letter_count: 20\"\n[1] \"521 five hundred and twenty-one letter_count: 23\"\n[1] \"522 five hundred and twenty-two letter_count: 23\"\n[1] \"523 five hundred and twenty-three letter_count: 25\"\n[1] \"524 five hundred and twenty-four letter_count: 24\"\n[1] \"525 five hundred and twenty-five letter_count: 24\"\n[1] \"526 five hundred and twenty-six letter_count: 23\"\n[1] \"527 five hundred and twenty-seven letter_count: 25\"\n[1] \"528 five hundred and twenty-eight letter_count: 25\"\n[1] \"529 five hundred and twenty-nine letter_count: 24\"\n[1] \"530 five hundred and thirty letter_count: 20\"\n[1] \"531 five hundred and thirty-one letter_count: 23\"\n[1] \"532 five hundred and thirty-two letter_count: 23\"\n[1] \"533 five hundred and thirty-three letter_count: 25\"\n[1] \"534 five hundred and thirty-four letter_count: 24\"\n[1] \"535 five hundred and thirty-five letter_count: 24\"\n[1] \"536 five hundred and thirty-six letter_count: 23\"\n[1] \"537 five hundred and thirty-seven letter_count: 25\"\n[1] \"538 five hundred and thirty-eight letter_count: 25\"\n[1] \"539 five hundred and thirty-nine letter_count: 24\"\n[1] \"540 five hundred and forty letter_count: 19\"\n[1] \"541 five hundred and forty-one letter_count: 22\"\n[1] \"542 five hundred and forty-two letter_count: 22\"\n[1] \"543 five hundred and forty-three letter_count: 24\"\n[1] \"544 five hundred and forty-four letter_count: 23\"\n[1] \"545 five hundred and forty-five letter_count: 23\"\n[1] \"546 five hundred and forty-six letter_count: 22\"\n[1] \"547 five hundred and forty-seven letter_count: 24\"\n[1] \"548 five hundred and forty-eight letter_count: 24\"\n[1] \"549 five hundred and forty-nine letter_count: 23\"\n[1] \"550 five hundred and fifty letter_count: 19\"\n[1] \"551 five hundred and fifty-one letter_count: 22\"\n[1] \"552 five hundred and fifty-two letter_count: 22\"\n[1] \"553 five hundred and fifty-three letter_count: 24\"\n[1] \"554 five hundred and fifty-four letter_count: 23\"\n[1] \"555 five hundred and fifty-five letter_count: 23\"\n[1] \"556 five hundred and fifty-six letter_count: 22\"\n[1] \"557 five hundred and fifty-seven letter_count: 24\"\n[1] \"558 five hundred and fifty-eight letter_count: 24\"\n[1] \"559 five hundred and fifty-nine letter_count: 23\"\n[1] \"560 five hundred and sixty letter_count: 19\"\n[1] \"561 five hundred and sixty-one letter_count: 22\"\n[1] \"562 five hundred and sixty-two letter_count: 22\"\n[1] \"563 five hundred and sixty-three letter_count: 24\"\n[1] \"564 five hundred and sixty-four letter_count: 23\"\n[1] \"565 five hundred and sixty-five letter_count: 23\"\n[1] \"566 five hundred and sixty-six letter_count: 22\"\n[1] \"567 five hundred and sixty-seven letter_count: 24\"\n[1] \"568 five hundred and sixty-eight letter_count: 24\"\n[1] \"569 five hundred and sixty-nine letter_count: 23\"\n[1] \"570 five hundred and seventy letter_count: 21\"\n[1] \"571 five hundred and seventy-one letter_count: 24\"\n[1] \"572 five hundred and seventy-two letter_count: 24\"\n[1] \"573 five hundred and seventy-three letter_count: 26\"\n[1] \"574 five hundred and seventy-four letter_count: 25\"\n[1] \"575 five hundred and seventy-five letter_count: 25\"\n[1] \"576 five hundred and seventy-six letter_count: 24\"\n[1] \"577 five hundred and seventy-seven letter_count: 26\"\n[1] \"578 five hundred and seventy-eight letter_count: 26\"\n[1] \"579 five hundred and seventy-nine letter_count: 25\"\n[1] \"580 five hundred and eighty letter_count: 20\"\n[1] \"581 five hundred and eighty-one letter_count: 23\"\n[1] \"582 five hundred and eighty-two letter_count: 23\"\n[1] \"583 five hundred and eighty-three letter_count: 25\"\n[1] \"584 five hundred and eighty-four letter_count: 24\"\n[1] \"585 five hundred and eighty-five letter_count: 24\"\n[1] \"586 five hundred and eighty-six letter_count: 23\"\n[1] \"587 five hundred and eighty-seven letter_count: 25\"\n[1] \"588 five hundred and eighty-eight letter_count: 25\"\n[1] \"589 five hundred and eighty-nine letter_count: 24\"\n[1] \"590 five hundred and ninety letter_count: 20\"\n[1] \"591 five hundred and ninety-one letter_count: 23\"\n[1] \"592 five hundred and ninety-two letter_count: 23\"\n[1] \"593 five hundred and ninety-three letter_count: 25\"\n[1] \"594 five hundred and ninety-four letter_count: 24\"\n[1] \"595 five hundred and ninety-five letter_count: 24\"\n[1] \"596 five hundred and ninety-six letter_count: 23\"\n[1] \"597 five hundred and ninety-seven letter_count: 25\"\n[1] \"598 five hundred and ninety-eight letter_count: 25\"\n[1] \"599 five hundred and ninety-nine letter_count: 24\"\n[1] \"600 six hundred letter_count: 10\"\n[1] \"601 six hundred and one letter_count: 16\"\n[1] \"602 six hundred and two letter_count: 16\"\n[1] \"603 six hundred and three letter_count: 18\"\n[1] \"604 six hundred and four letter_count: 17\"\n[1] \"605 six hundred and five letter_count: 17\"\n[1] \"606 six hundred and six letter_count: 16\"\n[1] \"607 six hundred and seven letter_count: 18\"\n[1] \"608 six hundred and eight letter_count: 18\"\n[1] \"609 six hundred and nine letter_count: 17\"\n[1] \"610 six hundred and ten letter_count: 16\"\n[1] \"611 six hundred and eleven letter_count: 19\"\n[1] \"612 six hundred and twelve letter_count: 19\"\n[1] \"613 six hundred and thirteen letter_count: 21\"\n[1] \"614 six hundred and fourteen letter_count: 21\"\n[1] \"615 six hundred and fifteen letter_count: 20\"\n[1] \"616 six hundred and sixteen letter_count: 20\"\n[1] \"617 six hundred and seventeen letter_count: 22\"\n[1] \"618 six hundred and eighteen letter_count: 21\"\n[1] \"619 six hundred and nineteen letter_count: 21\"\n[1] \"620 six hundred and twenty letter_count: 19\"\n[1] \"621 six hundred and twenty-one letter_count: 22\"\n[1] \"622 six hundred and twenty-two letter_count: 22\"\n[1] \"623 six hundred and twenty-three letter_count: 24\"\n[1] \"624 six hundred and twenty-four letter_count: 23\"\n[1] \"625 six hundred and twenty-five letter_count: 23\"\n[1] \"626 six hundred and twenty-six letter_count: 22\"\n[1] \"627 six hundred and twenty-seven letter_count: 24\"\n[1] \"628 six hundred and twenty-eight letter_count: 24\"\n[1] \"629 six hundred and twenty-nine letter_count: 23\"\n[1] \"630 six hundred and thirty letter_count: 19\"\n[1] \"631 six hundred and thirty-one letter_count: 22\"\n[1] \"632 six hundred and thirty-two letter_count: 22\"\n[1] \"633 six hundred and thirty-three letter_count: 24\"\n[1] \"634 six hundred and thirty-four letter_count: 23\"\n[1] \"635 six hundred and thirty-five letter_count: 23\"\n[1] \"636 six hundred and thirty-six letter_count: 22\"\n[1] \"637 six hundred and thirty-seven letter_count: 24\"\n[1] \"638 six hundred and thirty-eight letter_count: 24\"\n[1] \"639 six hundred and thirty-nine letter_count: 23\"\n[1] \"640 six hundred and forty letter_count: 18\"\n[1] \"641 six hundred and forty-one letter_count: 21\"\n[1] \"642 six hundred and forty-two letter_count: 21\"\n[1] \"643 six hundred and forty-three letter_count: 23\"\n[1] \"644 six hundred and forty-four letter_count: 22\"\n[1] \"645 six hundred and forty-five letter_count: 22\"\n[1] \"646 six hundred and forty-six letter_count: 21\"\n[1] \"647 six hundred and forty-seven letter_count: 23\"\n[1] \"648 six hundred and forty-eight letter_count: 23\"\n[1] \"649 six hundred and forty-nine letter_count: 22\"\n[1] \"650 six hundred and fifty letter_count: 18\"\n[1] \"651 six hundred and fifty-one letter_count: 21\"\n[1] \"652 six hundred and fifty-two letter_count: 21\"\n[1] \"653 six hundred and fifty-three letter_count: 23\"\n[1] \"654 six hundred and fifty-four letter_count: 22\"\n[1] \"655 six hundred and fifty-five letter_count: 22\"\n[1] \"656 six hundred and fifty-six letter_count: 21\"\n[1] \"657 six hundred and fifty-seven letter_count: 23\"\n[1] \"658 six hundred and fifty-eight letter_count: 23\"\n[1] \"659 six hundred and fifty-nine letter_count: 22\"\n[1] \"660 six hundred and sixty letter_count: 18\"\n[1] \"661 six hundred and sixty-one letter_count: 21\"\n[1] \"662 six hundred and sixty-two letter_count: 21\"\n[1] \"663 six hundred and sixty-three letter_count: 23\"\n[1] \"664 six hundred and sixty-four letter_count: 22\"\n[1] \"665 six hundred and sixty-five letter_count: 22\"\n[1] \"666 six hundred and sixty-six letter_count: 21\"\n[1] \"667 six hundred and sixty-seven letter_count: 23\"\n[1] \"668 six hundred and sixty-eight letter_count: 23\"\n[1] \"669 six hundred and sixty-nine letter_count: 22\"\n[1] \"670 six hundred and seventy letter_count: 20\"\n[1] \"671 six hundred and seventy-one letter_count: 23\"\n[1] \"672 six hundred and seventy-two letter_count: 23\"\n[1] \"673 six hundred and seventy-three letter_count: 25\"\n[1] \"674 six hundred and seventy-four letter_count: 24\"\n[1] \"675 six hundred and seventy-five letter_count: 24\"\n[1] \"676 six hundred and seventy-six letter_count: 23\"\n[1] \"677 six hundred and seventy-seven letter_count: 25\"\n[1] \"678 six hundred and seventy-eight letter_count: 25\"\n[1] \"679 six hundred and seventy-nine letter_count: 24\"\n[1] \"680 six hundred and eighty letter_count: 19\"\n[1] \"681 six hundred and eighty-one letter_count: 22\"\n[1] \"682 six hundred and eighty-two letter_count: 22\"\n[1] \"683 six hundred and eighty-three letter_count: 24\"\n[1] \"684 six hundred and eighty-four letter_count: 23\"\n[1] \"685 six hundred and eighty-five letter_count: 23\"\n[1] \"686 six hundred and eighty-six letter_count: 22\"\n[1] \"687 six hundred and eighty-seven letter_count: 24\"\n[1] \"688 six hundred and eighty-eight letter_count: 24\"\n[1] \"689 six hundred and eighty-nine letter_count: 23\"\n[1] \"690 six hundred and ninety letter_count: 19\"\n[1] \"691 six hundred and ninety-one letter_count: 22\"\n[1] \"692 six hundred and ninety-two letter_count: 22\"\n[1] \"693 six hundred and ninety-three letter_count: 24\"\n[1] \"694 six hundred and ninety-four letter_count: 23\"\n[1] \"695 six hundred and ninety-five letter_count: 23\"\n[1] \"696 six hundred and ninety-six letter_count: 22\"\n[1] \"697 six hundred and ninety-seven letter_count: 24\"\n[1] \"698 six hundred and ninety-eight letter_count: 24\"\n[1] \"699 six hundred and ninety-nine letter_count: 23\"\n[1] \"700 seven hundred letter_count: 12\"\n[1] \"701 seven hundred and one letter_count: 18\"\n[1] \"702 seven hundred and two letter_count: 18\"\n[1] \"703 seven hundred and three letter_count: 20\"\n[1] \"704 seven hundred and four letter_count: 19\"\n[1] \"705 seven hundred and five letter_count: 19\"\n[1] \"706 seven hundred and six letter_count: 18\"\n[1] \"707 seven hundred and seven letter_count: 20\"\n[1] \"708 seven hundred and eight letter_count: 20\"\n[1] \"709 seven hundred and nine letter_count: 19\"\n[1] \"710 seven hundred and ten letter_count: 18\"\n[1] \"711 seven hundred and eleven letter_count: 21\"\n[1] \"712 seven hundred and twelve letter_count: 21\"\n[1] \"713 seven hundred and thirteen letter_count: 23\"\n[1] \"714 seven hundred and fourteen letter_count: 23\"\n[1] \"715 seven hundred and fifteen letter_count: 22\"\n[1] \"716 seven hundred and sixteen letter_count: 22\"\n[1] \"717 seven hundred and seventeen letter_count: 24\"\n[1] \"718 seven hundred and eighteen letter_count: 23\"\n[1] \"719 seven hundred and nineteen letter_count: 23\"\n[1] \"720 seven hundred and twenty letter_count: 21\"\n[1] \"721 seven hundred and twenty-one letter_count: 24\"\n[1] \"722 seven hundred and twenty-two letter_count: 24\"\n[1] \"723 seven hundred and twenty-three letter_count: 26\"\n[1] \"724 seven hundred and twenty-four letter_count: 25\"\n[1] \"725 seven hundred and twenty-five letter_count: 25\"\n[1] \"726 seven hundred and twenty-six letter_count: 24\"\n[1] \"727 seven hundred and twenty-seven letter_count: 26\"\n[1] \"728 seven hundred and twenty-eight letter_count: 26\"\n[1] \"729 seven hundred and twenty-nine letter_count: 25\"\n[1] \"730 seven hundred and thirty letter_count: 21\"\n[1] \"731 seven hundred and thirty-one letter_count: 24\"\n[1] \"732 seven hundred and thirty-two letter_count: 24\"\n[1] \"733 seven hundred and thirty-three letter_count: 26\"\n[1] \"734 seven hundred and thirty-four letter_count: 25\"\n[1] \"735 seven hundred and thirty-five letter_count: 25\"\n[1] \"736 seven hundred and thirty-six letter_count: 24\"\n[1] \"737 seven hundred and thirty-seven letter_count: 26\"\n[1] \"738 seven hundred and thirty-eight letter_count: 26\"\n[1] \"739 seven hundred and thirty-nine letter_count: 25\"\n[1] \"740 seven hundred and forty letter_count: 20\"\n[1] \"741 seven hundred and forty-one letter_count: 23\"\n[1] \"742 seven hundred and forty-two letter_count: 23\"\n[1] \"743 seven hundred and forty-three letter_count: 25\"\n[1] \"744 seven hundred and forty-four letter_count: 24\"\n[1] \"745 seven hundred and forty-five letter_count: 24\"\n[1] \"746 seven hundred and forty-six letter_count: 23\"\n[1] \"747 seven hundred and forty-seven letter_count: 25\"\n[1] \"748 seven hundred and forty-eight letter_count: 25\"\n[1] \"749 seven hundred and forty-nine letter_count: 24\"\n[1] \"750 seven hundred and fifty letter_count: 20\"\n[1] \"751 seven hundred and fifty-one letter_count: 23\"\n[1] \"752 seven hundred and fifty-two letter_count: 23\"\n[1] \"753 seven hundred and fifty-three letter_count: 25\"\n[1] \"754 seven hundred and fifty-four letter_count: 24\"\n[1] \"755 seven hundred and fifty-five letter_count: 24\"\n[1] \"756 seven hundred and fifty-six letter_count: 23\"\n[1] \"757 seven hundred and fifty-seven letter_count: 25\"\n[1] \"758 seven hundred and fifty-eight letter_count: 25\"\n[1] \"759 seven hundred and fifty-nine letter_count: 24\"\n[1] \"760 seven hundred and sixty letter_count: 20\"\n[1] \"761 seven hundred and sixty-one letter_count: 23\"\n[1] \"762 seven hundred and sixty-two letter_count: 23\"\n[1] \"763 seven hundred and sixty-three letter_count: 25\"\n[1] \"764 seven hundred and sixty-four letter_count: 24\"\n[1] \"765 seven hundred and sixty-five letter_count: 24\"\n[1] \"766 seven hundred and sixty-six letter_count: 23\"\n[1] \"767 seven hundred and sixty-seven letter_count: 25\"\n[1] \"768 seven hundred and sixty-eight letter_count: 25\"\n[1] \"769 seven hundred and sixty-nine letter_count: 24\"\n[1] \"770 seven hundred and seventy letter_count: 22\"\n[1] \"771 seven hundred and seventy-one letter_count: 25\"\n[1] \"772 seven hundred and seventy-two letter_count: 25\"\n[1] \"773 seven hundred and seventy-three letter_count: 27\"\n[1] \"774 seven hundred and seventy-four letter_count: 26\"\n[1] \"775 seven hundred and seventy-five letter_count: 26\"\n[1] \"776 seven hundred and seventy-six letter_count: 25\"\n[1] \"777 seven hundred and seventy-seven letter_count: 27\"\n[1] \"778 seven hundred and seventy-eight letter_count: 27\"\n[1] \"779 seven hundred and seventy-nine letter_count: 26\"\n[1] \"780 seven hundred and eighty letter_count: 21\"\n[1] \"781 seven hundred and eighty-one letter_count: 24\"\n[1] \"782 seven hundred and eighty-two letter_count: 24\"\n[1] \"783 seven hundred and eighty-three letter_count: 26\"\n[1] \"784 seven hundred and eighty-four letter_count: 25\"\n[1] \"785 seven hundred and eighty-five letter_count: 25\"\n[1] \"786 seven hundred and eighty-six letter_count: 24\"\n[1] \"787 seven hundred and eighty-seven letter_count: 26\"\n[1] \"788 seven hundred and eighty-eight letter_count: 26\"\n[1] \"789 seven hundred and eighty-nine letter_count: 25\"\n[1] \"790 seven hundred and ninety letter_count: 21\"\n[1] \"791 seven hundred and ninety-one letter_count: 24\"\n[1] \"792 seven hundred and ninety-two letter_count: 24\"\n[1] \"793 seven hundred and ninety-three letter_count: 26\"\n[1] \"794 seven hundred and ninety-four letter_count: 25\"\n[1] \"795 seven hundred and ninety-five letter_count: 25\"\n[1] \"796 seven hundred and ninety-six letter_count: 24\"\n[1] \"797 seven hundred and ninety-seven letter_count: 26\"\n[1] \"798 seven hundred and ninety-eight letter_count: 26\"\n[1] \"799 seven hundred and ninety-nine letter_count: 25\"\n[1] \"800 eight hundred letter_count: 12\"\n[1] \"801 eight hundred and one letter_count: 18\"\n[1] \"802 eight hundred and two letter_count: 18\"\n[1] \"803 eight hundred and three letter_count: 20\"\n[1] \"804 eight hundred and four letter_count: 19\"\n[1] \"805 eight hundred and five letter_count: 19\"\n[1] \"806 eight hundred and six letter_count: 18\"\n[1] \"807 eight hundred and seven letter_count: 20\"\n[1] \"808 eight hundred and eight letter_count: 20\"\n[1] \"809 eight hundred and nine letter_count: 19\"\n[1] \"810 eight hundred and ten letter_count: 18\"\n[1] \"811 eight hundred and eleven letter_count: 21\"\n[1] \"812 eight hundred and twelve letter_count: 21\"\n[1] \"813 eight hundred and thirteen letter_count: 23\"\n[1] \"814 eight hundred and fourteen letter_count: 23\"\n[1] \"815 eight hundred and fifteen letter_count: 22\"\n[1] \"816 eight hundred and sixteen letter_count: 22\"\n[1] \"817 eight hundred and seventeen letter_count: 24\"\n[1] \"818 eight hundred and eighteen letter_count: 23\"\n[1] \"819 eight hundred and nineteen letter_count: 23\"\n[1] \"820 eight hundred and twenty letter_count: 21\"\n[1] \"821 eight hundred and twenty-one letter_count: 24\"\n[1] \"822 eight hundred and twenty-two letter_count: 24\"\n[1] \"823 eight hundred and twenty-three letter_count: 26\"\n[1] \"824 eight hundred and twenty-four letter_count: 25\"\n[1] \"825 eight hundred and twenty-five letter_count: 25\"\n[1] \"826 eight hundred and twenty-six letter_count: 24\"\n[1] \"827 eight hundred and twenty-seven letter_count: 26\"\n[1] \"828 eight hundred and twenty-eight letter_count: 26\"\n[1] \"829 eight hundred and twenty-nine letter_count: 25\"\n[1] \"830 eight hundred and thirty letter_count: 21\"\n[1] \"831 eight hundred and thirty-one letter_count: 24\"\n[1] \"832 eight hundred and thirty-two letter_count: 24\"\n[1] \"833 eight hundred and thirty-three letter_count: 26\"\n[1] \"834 eight hundred and thirty-four letter_count: 25\"\n[1] \"835 eight hundred and thirty-five letter_count: 25\"\n[1] \"836 eight hundred and thirty-six letter_count: 24\"\n[1] \"837 eight hundred and thirty-seven letter_count: 26\"\n[1] \"838 eight hundred and thirty-eight letter_count: 26\"\n[1] \"839 eight hundred and thirty-nine letter_count: 25\"\n[1] \"840 eight hundred and forty letter_count: 20\"\n[1] \"841 eight hundred and forty-one letter_count: 23\"\n[1] \"842 eight hundred and forty-two letter_count: 23\"\n[1] \"843 eight hundred and forty-three letter_count: 25\"\n[1] \"844 eight hundred and forty-four letter_count: 24\"\n[1] \"845 eight hundred and forty-five letter_count: 24\"\n[1] \"846 eight hundred and forty-six letter_count: 23\"\n[1] \"847 eight hundred and forty-seven letter_count: 25\"\n[1] \"848 eight hundred and forty-eight letter_count: 25\"\n[1] \"849 eight hundred and forty-nine letter_count: 24\"\n[1] \"850 eight hundred and fifty letter_count: 20\"\n[1] \"851 eight hundred and fifty-one letter_count: 23\"\n[1] \"852 eight hundred and fifty-two letter_count: 23\"\n[1] \"853 eight hundred and fifty-three letter_count: 25\"\n[1] \"854 eight hundred and fifty-four letter_count: 24\"\n[1] \"855 eight hundred and fifty-five letter_count: 24\"\n[1] \"856 eight hundred and fifty-six letter_count: 23\"\n[1] \"857 eight hundred and fifty-seven letter_count: 25\"\n[1] \"858 eight hundred and fifty-eight letter_count: 25\"\n[1] \"859 eight hundred and fifty-nine letter_count: 24\"\n[1] \"860 eight hundred and sixty letter_count: 20\"\n[1] \"861 eight hundred and sixty-one letter_count: 23\"\n[1] \"862 eight hundred and sixty-two letter_count: 23\"\n[1] \"863 eight hundred and sixty-three letter_count: 25\"\n[1] \"864 eight hundred and sixty-four letter_count: 24\"\n[1] \"865 eight hundred and sixty-five letter_count: 24\"\n[1] \"866 eight hundred and sixty-six letter_count: 23\"\n[1] \"867 eight hundred and sixty-seven letter_count: 25\"\n[1] \"868 eight hundred and sixty-eight letter_count: 25\"\n[1] \"869 eight hundred and sixty-nine letter_count: 24\"\n[1] \"870 eight hundred and seventy letter_count: 22\"\n[1] \"871 eight hundred and seventy-one letter_count: 25\"\n[1] \"872 eight hundred and seventy-two letter_count: 25\"\n[1] \"873 eight hundred and seventy-three letter_count: 27\"\n[1] \"874 eight hundred and seventy-four letter_count: 26\"\n[1] \"875 eight hundred and seventy-five letter_count: 26\"\n[1] \"876 eight hundred and seventy-six letter_count: 25\"\n[1] \"877 eight hundred and seventy-seven letter_count: 27\"\n[1] \"878 eight hundred and seventy-eight letter_count: 27\"\n[1] \"879 eight hundred and seventy-nine letter_count: 26\"\n[1] \"880 eight hundred and eighty letter_count: 21\"\n[1] \"881 eight hundred and eighty-one letter_count: 24\"\n[1] \"882 eight hundred and eighty-two letter_count: 24\"\n[1] \"883 eight hundred and eighty-three letter_count: 26\"\n[1] \"884 eight hundred and eighty-four letter_count: 25\"\n[1] \"885 eight hundred and eighty-five letter_count: 25\"\n[1] \"886 eight hundred and eighty-six letter_count: 24\"\n[1] \"887 eight hundred and eighty-seven letter_count: 26\"\n[1] \"888 eight hundred and eighty-eight letter_count: 26\"\n[1] \"889 eight hundred and eighty-nine letter_count: 25\"\n[1] \"890 eight hundred and ninety letter_count: 21\"\n[1] \"891 eight hundred and ninety-one letter_count: 24\"\n[1] \"892 eight hundred and ninety-two letter_count: 24\"\n[1] \"893 eight hundred and ninety-three letter_count: 26\"\n[1] \"894 eight hundred and ninety-four letter_count: 25\"\n[1] \"895 eight hundred and ninety-five letter_count: 25\"\n[1] \"896 eight hundred and ninety-six letter_count: 24\"\n[1] \"897 eight hundred and ninety-seven letter_count: 26\"\n[1] \"898 eight hundred and ninety-eight letter_count: 26\"\n[1] \"899 eight hundred and ninety-nine letter_count: 25\"\n[1] \"900 nine hundred letter_count: 11\"\n[1] \"901 nine hundred and one letter_count: 17\"\n[1] \"902 nine hundred and two letter_count: 17\"\n[1] \"903 nine hundred and three letter_count: 19\"\n[1] \"904 nine hundred and four letter_count: 18\"\n[1] \"905 nine hundred and five letter_count: 18\"\n[1] \"906 nine hundred and six letter_count: 17\"\n[1] \"907 nine hundred and seven letter_count: 19\"\n[1] \"908 nine hundred and eight letter_count: 19\"\n[1] \"909 nine hundred and nine letter_count: 18\"\n[1] \"910 nine hundred and ten letter_count: 17\"\n[1] \"911 nine hundred and eleven letter_count: 20\"\n[1] \"912 nine hundred and twelve letter_count: 20\"\n[1] \"913 nine hundred and thirteen letter_count: 22\"\n[1] \"914 nine hundred and fourteen letter_count: 22\"\n[1] \"915 nine hundred and fifteen letter_count: 21\"\n[1] \"916 nine hundred and sixteen letter_count: 21\"\n[1] \"917 nine hundred and seventeen letter_count: 23\"\n[1] \"918 nine hundred and eighteen letter_count: 22\"\n[1] \"919 nine hundred and nineteen letter_count: 22\"\n[1] \"920 nine hundred and twenty letter_count: 20\"\n[1] \"921 nine hundred and twenty-one letter_count: 23\"\n[1] \"922 nine hundred and twenty-two letter_count: 23\"\n[1] \"923 nine hundred and twenty-three letter_count: 25\"\n[1] \"924 nine hundred and twenty-four letter_count: 24\"\n[1] \"925 nine hundred and twenty-five letter_count: 24\"\n[1] \"926 nine hundred and twenty-six letter_count: 23\"\n[1] \"927 nine hundred and twenty-seven letter_count: 25\"\n[1] \"928 nine hundred and twenty-eight letter_count: 25\"\n[1] \"929 nine hundred and twenty-nine letter_count: 24\"\n[1] \"930 nine hundred and thirty letter_count: 20\"\n[1] \"931 nine hundred and thirty-one letter_count: 23\"\n[1] \"932 nine hundred and thirty-two letter_count: 23\"\n[1] \"933 nine hundred and thirty-three letter_count: 25\"\n[1] \"934 nine hundred and thirty-four letter_count: 24\"\n[1] \"935 nine hundred and thirty-five letter_count: 24\"\n[1] \"936 nine hundred and thirty-six letter_count: 23\"\n[1] \"937 nine hundred and thirty-seven letter_count: 25\"\n[1] \"938 nine hundred and thirty-eight letter_count: 25\"\n[1] \"939 nine hundred and thirty-nine letter_count: 24\"\n[1] \"940 nine hundred and forty letter_count: 19\"\n[1] \"941 nine hundred and forty-one letter_count: 22\"\n[1] \"942 nine hundred and forty-two letter_count: 22\"\n[1] \"943 nine hundred and forty-three letter_count: 24\"\n[1] \"944 nine hundred and forty-four letter_count: 23\"\n[1] \"945 nine hundred and forty-five letter_count: 23\"\n[1] \"946 nine hundred and forty-six letter_count: 22\"\n[1] \"947 nine hundred and forty-seven letter_count: 24\"\n[1] \"948 nine hundred and forty-eight letter_count: 24\"\n[1] \"949 nine hundred and forty-nine letter_count: 23\"\n[1] \"950 nine hundred and fifty letter_count: 19\"\n[1] \"951 nine hundred and fifty-one letter_count: 22\"\n[1] \"952 nine hundred and fifty-two letter_count: 22\"\n[1] \"953 nine hundred and fifty-three letter_count: 24\"\n[1] \"954 nine hundred and fifty-four letter_count: 23\"\n[1] \"955 nine hundred and fifty-five letter_count: 23\"\n[1] \"956 nine hundred and fifty-six letter_count: 22\"\n[1] \"957 nine hundred and fifty-seven letter_count: 24\"\n[1] \"958 nine hundred and fifty-eight letter_count: 24\"\n[1] \"959 nine hundred and fifty-nine letter_count: 23\"\n[1] \"960 nine hundred and sixty letter_count: 19\"\n[1] \"961 nine hundred and sixty-one letter_count: 22\"\n[1] \"962 nine hundred and sixty-two letter_count: 22\"\n[1] \"963 nine hundred and sixty-three letter_count: 24\"\n[1] \"964 nine hundred and sixty-four letter_count: 23\"\n[1] \"965 nine hundred and sixty-five letter_count: 23\"\n[1] \"966 nine hundred and sixty-six letter_count: 22\"\n[1] \"967 nine hundred and sixty-seven letter_count: 24\"\n[1] \"968 nine hundred and sixty-eight letter_count: 24\"\n[1] \"969 nine hundred and sixty-nine letter_count: 23\"\n[1] \"970 nine hundred and seventy letter_count: 21\"\n[1] \"971 nine hundred and seventy-one letter_count: 24\"\n[1] \"972 nine hundred and seventy-two letter_count: 24\"\n[1] \"973 nine hundred and seventy-three letter_count: 26\"\n[1] \"974 nine hundred and seventy-four letter_count: 25\"\n[1] \"975 nine hundred and seventy-five letter_count: 25\"\n[1] \"976 nine hundred and seventy-six letter_count: 24\"\n[1] \"977 nine hundred and seventy-seven letter_count: 26\"\n[1] \"978 nine hundred and seventy-eight letter_count: 26\"\n[1] \"979 nine hundred and seventy-nine letter_count: 25\"\n[1] \"980 nine hundred and eighty letter_count: 20\"\n[1] \"981 nine hundred and eighty-one letter_count: 23\"\n[1] \"982 nine hundred and eighty-two letter_count: 23\"\n[1] \"983 nine hundred and eighty-three letter_count: 25\"\n[1] \"984 nine hundred and eighty-four letter_count: 24\"\n[1] \"985 nine hundred and eighty-five letter_count: 24\"\n[1] \"986 nine hundred and eighty-six letter_count: 23\"\n[1] \"987 nine hundred and eighty-seven letter_count: 25\"\n[1] \"988 nine hundred and eighty-eight letter_count: 25\"\n[1] \"989 nine hundred and eighty-nine letter_count: 24\"\n[1] \"990 nine hundred and ninety letter_count: 20\"\n[1] \"991 nine hundred and ninety-one letter_count: 23\"\n[1] \"992 nine hundred and ninety-two letter_count: 23\"\n[1] \"993 nine hundred and ninety-three letter_count: 25\"\n[1] \"994 nine hundred and ninety-four letter_count: 24\"\n[1] \"995 nine hundred and ninety-five letter_count: 24\"\n[1] \"996 nine hundred and ninety-six letter_count: 23\"\n[1] \"997 nine hundred and ninety-seven letter_count: 25\"\n[1] \"998 nine hundred and ninety-eight letter_count: 25\"\n[1] \"999 nine hundred and ninety-nine letter_count: 24\"\n" ], [ "20913 + count_words('a thousand')", "_____no_output_____" ], [ "has_letters = function(x) {\n \n split = split_number(x)\n word = spell_number(split)\n count = count_words(word)\n\n print(paste(x, word, count))\n \n return (count)\n}", "_____no_output_____" ], [ "has_letters(115)", "[1] \"115 a hundred and fifteen 18\"\n" ], [ "count_words('a thousand')", "_____no_output_____" ] ], [ [ "Fuck this shit.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
4a50d4f77567ea902b589a735fd6b0bc21a7363d
65,671
ipynb
Jupyter Notebook
5-ResearchDissemination.ipynb
tishamentnech/2018-reproducible-science
d7f253fcd582d5a2f59665d7a6759570adb8a893
[ "MIT" ]
3
2018-11-13T16:43:47.000Z
2019-03-14T18:02:26.000Z
5-ResearchDissemination.ipynb
tishamentnech/2018-reproducible-science
d7f253fcd582d5a2f59665d7a6759570adb8a893
[ "MIT" ]
null
null
null
5-ResearchDissemination.ipynb
tishamentnech/2018-reproducible-science
d7f253fcd582d5a2f59665d7a6759570adb8a893
[ "MIT" ]
null
null
null
181.411602
54,109
0.901083
[ [ [ "# Module 5: Research Dissemination (30 minutes)\nFrom \"[Piled Higher and Deeper](http://phdcomics.com/comics/archive.php?comicid=1174)\" by Jorge Cham\n<img src=\"http://www.phdcomics.com/comics/archive/phd051809s.gif\" />\n\n## Take a moment to read these University policies \n\n### Openness in Research\nIn Section 2.2 of the [Research Handbook](http://osp.utah.edu/policies/handbook/conduct-standards/openness.php)\n\n### Ownership of Copyrightable Works and Related Works\nIn [Policy 7-003](http://regulations.utah.edu/research/7-003.php) ", "_____no_output_____" ], [ "### Copyright and Creative Commons Licensing \n<center><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/Creative_commons_license_spectrum.svg/600px-Creative_commons_license_spectrum.svg.png\" width=\"500px\" /></center>", "_____no_output_____" ], [ "### Exercise: Reading publisher contracts\n\n* [PLOS ONE](http://journals.plos.org/plosone/s/licenses-and-copyright) \n* [New England Journal of Medicine](http://www.nejm.org/page/author-center/manuscript-submission)\n* [Journal of Biomedical Informatics](https://www.elsevier.com/journals/journal-of-biomedical-informatics/1532-0464/guide-for-authors)\n* Find copyright information for a journal you're planning to publish in. ", "_____no_output_____" ], [ "### Author Rights\n* [SPARC Author Addendum](https://sparcopen.org/our-work/author-rights/)", "_____no_output_____" ], [ "## Reporting Guidelines and Writing Support\n<table>\n<tr>\n<td><a href=\"http://www.icmje.org/recommendations/browse/manuscript-preparation/preparing-for-submission.html\"><img src=\"http://www.icmje.org/images/icmje_logo.gif\" width=\"450px\" /></a></td>\n<td><a href=\"http://www.equator-network.org/\"><img src=\"http://www.equator-network.org/wp-content/themes/equator/images/equator_logo.png\" width=\"300px\" /></a></td>\n</tr>\n</table>\n\n### At The University\n* [University Writing Center](http://writingcenter.utah.edu/)\n* [Dissertation Writing Boot Camp](http://gradschool.utah.edu/thesis/dissertation-writing-boot-camps/)", "_____no_output_____" ], [ "## Peer Review\n<table>\n<tr>\n<td><a href=\"https://peerreviewweek.wordpress.com/\"><img src=\"https://peerreviewweek.files.wordpress.com/2018/05/peerreviewweek_logo_2018_v1.jpg\" width=\"300px\" /></a></td>\n<td><a href=\"https://publons.com/\"><img src=\"https://static1.squarespace.com/static/576fcda2e4fcb5ab5152b4d8/58404af86a496371af54f1b2/58404b30b3db2b7f14442eed/1480608562794/light_blue_alt.png?format=300w\" /></a></td>\n</tr>\n</table>\n\n* single-blind\n* double-blind\n* open\n* post-publication\n\nRead more about it [here](http://www.editage.com/insights/what-are-the-types-of-peer-review).", "_____no_output_____" ], [ "## Choosing a journal\n* [Ulrichsweb](http://ulrichsweb.serialssolutions.com/)\n* [Directory of Open Access Journals](http://www.doaj.org/)\n* [Questions to evaluate a journal](http://thinkchecksubmit.org/check/)\n\n### Based on certain factors\n* [Journal Citation Reports](https://login.ezproxy.lib.utah.edu/login?url=http://jcr.incites.thomsonreuters.com)\n* [Scopus Compare Journals](https://login.ezproxy.lib.utah.edu/login?url=http://www.scopus.com/source/eval.url)\n* [Cofactor Journal Selector](http://cofactorscience.com/journal-selector) \n\n### Based on your abstract\n* [Journal/Author Name Estimator](http://jane.biosemantics.org/) ", "_____no_output_____" ], [ "## Publishing Models: Traditional vs Open Access \nMore information about open access at <a href=\"http://www.openaccessweek.org/\">OpenAccessWeek.org</a>\n\n<img src=\"http://api.ning.com/files/j2M1I3T7jzmpxqaCOjCDmPPu-MUwscmeVKPZjQGk6mqdKfYeq3rZzvgZJ6AcltgJTWQwtgnOUxbTMKzHsh3syLN-7pXZlVeY/OpenAccessWeek_logo.jpg\" />", "_____no_output_____" ] ], [ [ "from IPython.display import YouTubeVideo\nYouTubeVideo(\"L5rVH1KGBCY\", width=600, height=350)", "_____no_output_____" ] ], [ [ "### How Open Is It? \nFrom [SPARC](https://sparcopen.org/our-work/howopenisit/)\n<img src=\"https://sparcopen.org/wp-content/uploads/2015/12/HowOpenIsIt_English_001.png\" width=\"1200px\" />", "_____no_output_____" ], [ "### Green Open Access\nFrom CSU Fullerton's [Open Access guide](http://libraryguides.fullerton.edu/open-access/GreenOAPolicy)\n<img src=\"https://s3.amazonaws.com/libapps/customers/114/images/green-access-infographic-web.png\" width=\"500px\" />", "_____no_output_____" ], [ "## How does \"public access\" fit in? \n\n<table>\n<tr>\n<td><a href=\"https://www.nsf.gov/pubs/2017/nsf17060/nsf17060.jsp\"><img src=\"https://www.nsf.gov/images/nsf_logo.png\" width=\"400px\" /></a></td>\n<td><a href=\"https://publicaccess.nih.gov/\"><img src=\"https://www.nih.gov/sites/all/themes/nih/images/nih-logo-color.png\" width=\"400px\" /></a></td>\n</tr>\n</table>", "_____no_output_____" ], [ "## Archiving your paper (aka practicing green open access)\n### Does your publisher allow you to post a preprint/postprint?\n* [SHERPA/RoMEO](http://www.sherpa.ac.uk/romeo/index.php)\n\n### Where can you post it? \n* [PubMed Central](https://www.ncbi.nlm.nih.gov/pmc/)\n* [bioRxiv](http://www.biorxiv.org/)\n* [OSF Preprints](https://cos.io/our-products/osf-preprints/) \n* [OpenDOAR](http://www.opendoar.org/) \n* [USpace](http://www.lib.utah.edu/digital-scholarship/uspace-uscholar.php) \n* Your own website (but consider discoverability)", "_____no_output_____" ], [ "### Finding a \"free\" copy of a paper (legally)\n* [Unpaywall](http://unpaywall.org/) \n* Unpaywall which is a plug in for your browser just recieved an 850,000 dollar grant from he Arcadia Fund, to build a website where *everyone* can find, read, and understand the research literature. Sign up now for early access [unpaywall](http://gettheresearch.org) \n* [Open Access Button](https://openaccessbutton.org/)\n* Author's personal or academic social networking website (ResearchGate, Academia.edu)", "_____no_output_____" ], [ "## Other publication types/models \n\n* [The Journal of Irreproducible Results](http://www.jir.com/) \n* [MedEdPortal](https://www.mededportal.org)\n* [Data journals](http://campusguides.lib.utah.edu/c.php?g=160788&p=1051837)\n* [Protocols.io](https://www.protocols.io/welcome)\n* [Registered Reports](https://osf.io/8mpji/wiki/home/)\n", "_____no_output_____" ], [ "## Tracking research impact\n\n### Citation counts & h-index\n* [Scopus](http://ezproxy.lib.utah.edu/login?url=http://www.scopus.com/home.url)\n* [Web of Science](https://login.ezproxy.lib.utah.edu/login?url=http://www.webofknowledge.com/)\n* [Google Scholar](http://scholar.google.com/)", "_____no_output_____" ], [ "### Altmetrics\n<table>\n<tr>\n<td><img src=\"http://www.springersource.com/wp-content/uploads/2015/08/Altmetric-Donut1.png\" width=\"600px\" /></td>\n</tr>\n</table>\n**Resources**\n* [Altmetric](https://www.altmetric.com/) and the [bookmarklet](https://www.altmetric.com/products/free-tools/bookmarklet/)", "_____no_output_____" ], [ "### Scholarly impact \n<table>\n<tr>\n<td><img src=\"https://orcid.org/sites/all/themes/orcidResponsiveNoto/img/orcid-logo.png\" width=\"300px\" /></td>\n<td><img src=\"https://profiles.impactstory.org/static/img/impactstory-logo-sideways.png\" width=\"300px\" /></td>\n</tr>\n</table>\n### Exercise \nSet up your [ORCID](https://orcid.org/) and sign up for [Impact Story](https://profiles.impactstory.org/).\n\n### Impact Story examples\n\n* [Vicky Steeves](https://profiles.impactstory.org/u/0000-0003-4298-168X)\n* [Wendy Chapman](https://profiles.impactstory.org/u/0000-0001-8702-4483)\n* Of note, Dr. Chapman's impact story was autogenerated and might be missing data", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4a50d5e189acccff0a6e84fed71b1ece9d50764c
36,983
ipynb
Jupyter Notebook
notebooks/what_if_4_project_packaging.ipynb
slbrooks/whatif_slb
9b953a18449fbdbdbd56eff7dae432dade4e80ba
[ "FTL", "RSA-MD" ]
null
null
null
notebooks/what_if_4_project_packaging.ipynb
slbrooks/whatif_slb
9b953a18449fbdbdbd56eff7dae432dade4e80ba
[ "FTL", "RSA-MD" ]
null
null
null
notebooks/what_if_4_project_packaging.ipynb
slbrooks/whatif_slb
9b953a18449fbdbdbd56eff7dae432dade4e80ba
[ "FTL", "RSA-MD" ]
null
null
null
52.30976
751
0.644864
[ [ [ "## Excel \"What if?\" analysis with Python - Part 4: Project management and packaging\n", "_____no_output_____" ], [ "In the first three notebooks, we've developed some Python approaches to typical Excel \"what if?\" analyses. \nAlong the way we explored some slightly more advanced Python topics (for relative newcomers to Python) such as:\n\n* List comprehensions,\n* Basic OO programming, creating our own classes and using things like `setattr` and `getattr`,\n* Leveraging scikit-learn's `ParameterGrid` class,\n* Faceted plots using Seaborn and matplotlib,\n* Tuple unpacking, zip, and itertools,\n* Safely copying objects,\n* Root finding with, and without, `scipy.optimize`,\n* Partial function freezing and lambda functions,\n* Using `numpy.random` to generate random variates from various probability distributions,\n* Using `scipy.stats` to compute probabilities and percentiles,\n* Importing our `data_table`, `goal_seek` and `simulate` functions from a module.\n", "_____no_output_____" ], [ "Now that we've got a critical mass of \"proof of concept\" code, let's figure out how to structure our project and create a deployable package. In addition, let's rethink our OO design and add some much needed documentation to the code.\n\n### Python packaging basics\n\nWhat is a Python module? What is a Python package? A simple way to think about it is that a module is a Python file containing code and a package is a folder containing Python files and perhaps subfolders that also contain Python files (yes, there are many more details). \n\nThere are tools for turning such a folder into packages that can be uploaded to places like PyPI (Python Package Index) or conda-forge (if you've used R, think CRAN) from which people can download and install them with package installers like [pip](https://pypi.org/project/pip/) or [conda](https://docs.conda.io/en/latest/).\n\nIf you are new to the world of Python modules and packages, a great place to start is the tutorial done by Real Python - [Python Modules and Packages - An Introduction](https://realpython.com/python-modules-packages/). After going through the tutorial you'll have some familiarity with concepts needed in our tutorial:\n\n* Python modules and how Python finds modules on your system,\n* the different ways of importing modules,\n* exploring the contents of modules,\n* executing modules as scripts and reloading modules,\n* Python packages, the `__init__.py` file, importing from packages, and subpackages.\n\nAnother good high level introduction to modules, packages and project structure is [The Hitchhikers Guide to Python: Structuring Your Project](https://docs.python-guide.org/writing/structure/). Of course, one should also visit the official [Python Packaging User Guide](https://packaging.python.org/) (start with the [Overview](https://packaging.python.org/overview/)), especially with the ever evolving nature of this topic. See this recent series of posts on the [State of Python Packaging](https://www.bernat.tech/pep-517-and-python-packaging/) for an \"exhausting (hopefully still kinda high level) overview of the subject\".\n\nWith a basic and limited understanding of Python packages, let's get to turning `whatif.py` into a package.\n\n![python_package](./images/python_package.png)\n", "_____no_output_____" ], [ "## Creating a new project using a cookiecutter\n\nBack in Module 2, we learned about cookiecutters and used a simple cookiecutter for a data analyis project. \nThat cookiecutter really isn't appropriate for a project in which we intend to create a Python package from our source code. Instead, we'll use another cookiecutter I've created called ``cookiecutter-datascience-aap``. Let's check out the [GitHub page for this cookiecutter](https://github.com/misken/cookiecutter-datascience-aap) and note the differences between it and the simple cookiecutter template we used in Module 2.\n\nOk, let's create new project called `whatif`. To start a new project, run from the directory in which you want your new project to live:\n\n cookiecutter https://github.com/misken/cookiecutter-datascience-aap\n \nYou'll get prompted with a series of questions and then your project will get created. \n", "_____no_output_____" ], [ "### Overview of cookiecutter-datascience-aap project structure\n\nWe won't get into all the details now, but there's a few things about the folder structure that we should discuss. Here's the structure:\n\n```\n├── whatif\n ├── LICENSE\n ├── README.md <- The top-level README for developers using this project.\n ├── data\n │   ├── external <- Data from third party sources.\n │   ├── interim <- Intermediate data that has been transformed.\n │   ├── processed <- The final, canonical data sets for modeling.\n │   └── raw <- The original, immutable data dump.\n │\n ├── docs <- A default Sphinx project; see sphinx-doc.org for details\n │\n ├── models <- Trained and serialized models, model predictions, or model summaries\n │\n ├── notebooks <- Jupyter notebooks. Naming convention is a number (for ordering),\n │ the creator's initials, and a short `-` delimited description, e.g.\n │ `1.0-jqp-initial-data-exploration`.\n │\n ├── references <- Data dictionaries, manuals, and all other explanatory materials.\n │\n ├── reports <- Generated analysis as HTML, PDF, LaTeX, etc.\n │   └── figures <- Generated graphics and figures to be used in reporting\n │\n ├── requirements.txt <- The requirements file for reproducing the analysis environment, e.g.\n │ generated with `pip freeze > requirements.txt`\n │\n ├── setup.py <- makes project pip installable (pip install -e .) so whatif can be imported\n ├── src <- Source code for use in this project.\n │   ├── whatif <- Main package folder\n │   │   └── __init__.py <- Marks as package\n │   │   └── whatif.py <- Python source code file\n │\n └── tox.ini <- tox file with settings for running tox; see tox.readthedocs.io\n```\n\nA few things to note:\n\n1. The top level `whatif` folder will be called the *project folder*.\n1. A whole bunch of folders and files are created.\n1. You can delete folders and add folders depending on the project. \n1. This project uses what is known as a \"src/ layout\". Within the `src` folder is the main package folder, `whatif`.\n1. Within the `whatif` package folder, is an `__init__.py` file. We'll talk more about this later in the notebook, but for now, think of it as a marker signifying that `whatif` is a Python package.\n1. Also within the `whatif` folder, is an empty Python source code file named `whatif.py`. We can replace this with our current `whatif.py` file, or add code to this file, or delete this file. There is no requirement that we have a `.py` file with the same name as the `package`. We often do, but that's just a convention.\n\nThe whole \"should you use a `src/` folder within which the main package folder lives?\" is quite a point of discussion in the Python community. Recently, it seems like using this `src/` based layout is gaining favor. If you want to dive down this rabbit hole, here's a few links to get you going:\n\n* https://blog.ionelmc.ro/2014/05/25/python-packaging/#the-structure\n* https://github.com/pypa/packaging.python.org/issues/320", "_____no_output_____" ], [ "### Adding files to our new project\n\nSince we've got some work in process in the form of a few Jupyter notebooks and an early version of `whatif.py`, we can add them to our project. I've included these in the downloads folder for this module.\n\n> In fact, I've included my entire `whatif` project folder. You can find all files referenced below, in that folder. \n\nWe also have this notebook in which I'm typing right now (feeling very self-referential). Put the notebooks relating to the first three parts of this series into the `examples` folder along with a few other examples.\n\n```\n├── examples\n│   │   ├── BookstoreModel.py\n│   │   ├── new_car_simulation.ipynb\n│   │   ├── what_if_1_model_datatable.ipynb\n│   │   ├── what_if_2_goalseek.ipynb\n│   │   └── what_if_3_simulation.ipynb\n\n```\n\nWithin the `notebooks` folder, put this notebook along with some notes in a markdown file.\n\n```\n├── notebooks\n│   │   ├── testing_cookiecutter_structures.md\n│   │   └── what_if_4_project_packaging.ipynb\n\n```\n\nFinally, replace the placeholder `whatif.py` file in the `src/whatif/` folder with the working version upon which this project will be built - you can find this file in the downloads file as well in the `src/whatif/` folder.", "_____no_output_____" ], [ "## Version control\n\nThe very first thing we should do after getting our project initialized is to put it under version control. \n\nGet a shell open in the main project folder created by the cookiecutter. Then we can initialize the project folder as a git repo:\n\n```bash\ngit init\ngit add .\ngit commit -m 'initial commit'\n```\n\nThen go to your GitHub site and create a brand new repo named `whatif`. Since we already have an existing local repo that we will be pushing up to a new remote at GitHub, we do the following:\n\n```bash\ngit remote add origin https://github.com/<your github user name>/whatif.git\ngit branch -M main\ngit push -u origin main\n```\n\nNow you've got a new GitHub repo at `https://github.com/<your github user name>/whatif`.", "_____no_output_____" ], [ "## Source code editing\nI would suggest using either PyCharm or VSCode to do any code editing to `whatif.py`. Of course, you could simply use a text editor. It's up to you. I'm going to use PyCharm and in the following screencast I demo setting up this project in PyCharm.\n\n* [SCREENCAST: Setting up whatif project in PyCharm](https://youtu.be/QJ-qrSZSwV4) (4:30)", "_____no_output_____" ], [ "## The whatif.py module - initial design\nAfter completing Part 3 of this series, we had an example model class, `BookstoreModel`, and three functions that took such a model as one of the arguments and one utility function that was used to extract a Pandas `DataFrame` from the simulationoutput object (a list of dictionaries).\n\n* `data_table` - a generalized version of Excel's Data Table tool,\n* `goal_seek` - very similar in purpose to Excel's Goal Seek tool,\n* `simulate` - basic Monte-Carlo simulation capabilities,\n* `get_sim_results_df` - converts output of `simulate` to a pandas dataframe.\n\nAll of these were copied and pasted from their respective Jupyter notebooks and consolidated in the `whatif.py` file. This module can be imported and its functions used. While this is workable, let's try to generalize things a bit and improve the design. ", "_____no_output_____" ] ], [ [ "%load_ext autoreload\n%autoreload 2", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns", "_____no_output_____" ], [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "## Creating a `Model` base class\n\nEverything we've done so far has used the one specific model class we created - `BookstoreModel`. In order to create a new model, we'd probably copy the code from this class and make the changes specific to the new model in terms of its variables (class attributes) and formulas (class methods). However, every model class (as we've conceived it so far) also needs to have an `update` method that takes a dictionary of model variable names (the keys) and their new values. Rather than the modeler having to remember to do this, it makes more sense to create a generic `Model` *base class* from which our specific model classes will *inherit* things like an `update` method. I also moved the `__str__` function into our new `Model` base class.\n\nAll three of the analysis functions we created (`data_table`, `goal_seek` and `simulate`) rely on this specific implementation of `update` and require a model object as an input argument. Given that, it makes sense to move these functions from their current place as *module level* functions to class methods of the new base class, `Model`. You can find this new `Model` base class within `whatif.py` both in the downloads file for this module or at the [whatif project GitHub site](https://github.com/misken/whatif).\n\nIf you are new to OOP, check out this [tutorial which discusses inheritance](https://www.python-course.eu/python3_inheritance.php).\n\n", "_____no_output_____" ], [ "## Adding new methods to `BookstoreModel` \nAnyone who builds spreadsheet models knows that it's usually better to decompose large formulas into smaller pieces. Not only does this help with model debugging and readability, it provides an easy way to analyze components of composite quantities. For example, `sales_revenue` is based on the number of units sold and the selling price per unit. Our original implemenation buried the computation of number sold into the `sales_revenue` function. This makes it tough to do things like sensitivity analysis on number sold. So, we'll rework the class a bit to add some new methods. Notice, I've also added basic docstrings - more on documentation in a subsequent notebook.", "_____no_output_____" ], [ "Here's our updated `BookstoreModel` class. A few additional things to note beyond the new methods added:\n\n* it includes the `Model` base class within the parentheses in the class declaration,\n* it no longer has an `update` method,\n* it no longer has a `__str__` method.\n\n`BookstoreModel` will inherit `update` from the `Model` class. It also inherits `__str__`, but we could certainly include an `__str__` method in `BookstoreModel` if we wanted some custom string representation or just didn't like the one in the `Model` base class. This is called *method overriding*.", "_____no_output_____" ] ], [ [ "class BookstoreModel(Model):\n \"\"\"Bookstore model\n\n This example is based on the \"Walton Bookstore\" problem in *Business Analytics: Data Analysis and Decision Making* (Albright and Winston) in the chapter on Monte-Carlo simulation. Here's the basic problem (with a few modifications):\n\n * we have to place an order for a perishable product (e.g. a calendar),\n * there's a known unit cost for each one ordered,\n * we have a known selling price,\n * demand is uncertain but we can model it with some simple probability distribution,\n * for each unsold item, we can get a partial refund of our unit cost,\n * we need to select the order quantity for our one order for the year; orders can only be in multiples of 25.\n\n Attributes\n ----------\n unit_cost: float or array-like of float, optional\n Cost for each item ordered (default 7.50)\n selling_price : float or array-like of float, optional\n Selling price for each item (default 10.00)\n unit_refund : float or array-like of float, optional\n For each unsold item we receive a refund in this amount (default 2.50)\n order_quantity : float or array-like of float, optional\n Number of items ordered in the one time we get to order (default 200)\n demand : float or array-like of float, optional\n Number of items demanded by customers (default 193)\n \"\"\"\n def __init__(self, unit_cost=7.50, selling_price=10.00, unit_refund=2.50,\n order_quantity=200, demand=193):\n self.unit_cost = unit_cost\n self.selling_price = selling_price\n self.unit_refund = unit_refund\n self.order_quantity = order_quantity\n self.demand = demand\n\n def order_cost(self):\n \"\"\"Compute total order cost\"\"\"\n return self.unit_cost * self.order_quantity\n\n def num_sold(self):\n \"\"\"Compute number of items sold\n\n Assumes demand in excess of order quantity is lost.\n \"\"\"\n return np.minimum(self.order_quantity, self.demand)\n\n def sales_revenue(self):\n \"\"\"Compute total sales revenue based on number sold and selling price\"\"\"\n return self.num_sold() * self.selling_price\n\n def num_unsold(self):\n \"\"\"Compute number of items ordered but not sold\n\n Demand was less than order quantity\n \"\"\"\n return np.maximum(0, self.order_quantity - self.demand)\n\n def refund_revenue(self):\n \"\"\"Compute total sales revenue based on number unsold and unit refund\"\"\"\n return self.num_unsold() * self.unit_refund\n\n def total_revenue(self):\n \"\"\"Compute total revenue from sales and refunds\"\"\"\n return self.sales_revenue() + self.refund_revenue()\n\n def profit(self):\n \"\"\"Compute profit based on revenue and cost\"\"\"\n profit = self.sales_revenue() + self.refund_revenue() - self.order_cost()\n return profit\n", "_____no_output_____" ] ], [ [ "To help visualize the class structure, here is a simple UML diagram.\n\n![uml diagram](./images/class_diagram.png)", "_____no_output_____" ], [ "## Using the Bookstore Model\nGreat, we've made some improvements both to `BookstoreModel` class as well as to the underlyng `Model` base class (which didn't exist before). However, if we try to create a new instance of `BookstoreModel` we quickly run into trouble. In fact, if we try to execute the cell above which defines the `BookstoreModel` class, we get an error saying that the `Model` class does not exist. Where is it? It's in the `whatif.py` module (which is **not** in the same folder as this notebook). Can't we just import it like we did in the Monte-Carlo simulation notebook?", "_____no_output_____" ] ], [ [ "from whatif import Model", "_____no_output_____" ] ], [ [ "Nope. So, where does Python go to look for modules like `whatif`? It examines something known as `sys.path`.", "_____no_output_____" ] ], [ [ "import sys\nprint('\\n'.join(sys.path))", "C:\\Users\\slbro\\Documents\\Oakland University\\2020-2021\\Summer 2021\\MIS 6900 - Advanced Analytics with Python\\Module 3\\downloads_whatif_packaging\\whatif_slb\\notebooks\nC:\\Users\\slbro\\anaconda3\\envs\\aap\\python37.zip\nC:\\Users\\slbro\\anaconda3\\envs\\aap\\DLLs\nC:\\Users\\slbro\\anaconda3\\envs\\aap\\lib\nC:\\Users\\slbro\\anaconda3\\envs\\aap\n\nC:\\Users\\slbro\\anaconda3\\envs\\aap\\lib\\site-packages\nC:\\Users\\slbro\\anaconda3\\envs\\aap\\lib\\site-packages\\win32\nC:\\Users\\slbro\\anaconda3\\envs\\aap\\lib\\site-packages\\win32\\lib\nC:\\Users\\slbro\\anaconda3\\envs\\aap\\lib\\site-packages\\Pythonwin\nC:\\Users\\slbro\\anaconda3\\envs\\aap\\lib\\site-packages\\IPython\\extensions\nC:\\Users\\slbro\\.ipython\n" ] ], [ [ "A couple things to take away from the `sys.path` list:\n\n* Python first looks in the current working directory,\n* from the remaining paths, we see that we are working in a conda virtual environment named `aap`.\n\nSince the import of `whatif` failed, we can conclude that not only is `whatif.py` not in the current working directory, it also has not been installed in the conda `aap` virtual environment (that I created).\n\nOf course, the whole point of this exercise is to turn `whatif` into an installable package so that we can use it from notebooks like this. Let's learn how to do that.", "_____no_output_____" ], [ "## Creating the whatif package\n\nYou can find a [tutorial on packaging a simple Python project here](https://packaging.python.org/tutorials/packaging-projects/). Our example is pretty similar and certainly is simple. There are two critical files which we have yet to discuss - `__init__.py` and `setup.py`. Both of these were created by our cookiecutter and plopped into our project.", "_____no_output_____" ], [ "### The __init__.py file\nWell, this got more confusing after Python 3.3 was release in that now there are [regular packages and namespace packages](https://docs.python.org/3/reference/import.html#regular-packages). For our purposes, we will just be considering *regular packages* and discuss a standard purpose and use of `__init__.py`. **This file, which is often blank, when placed into a folder, marks this folder as a regular package.** When this folder is imported, any code in `__init__.py` is executed. Here is the `__init__.py` file for the `whatif` package.\n\n```python\nfrom whatif.whatif import Model\nfrom whatif.whatif import get_sim_results_df\n```\n\nJust focus on the first line. That first `whatif` is the package (the folder) and that second `whatif` is referring to the module (the file) `whatif.py`. We know that the class definition for `Model` is in that file. After we install the `whatif` package (which we'll get to shortly), we could always import it for use in a Jupyter notebook with the statements like those above. However, by including them in the `__init__.py` file, we have imported them at the *package level* and can use these shorter versions in a notebook.\n\n```python\nfrom whatif import Model\nfrom whatif import get_sim_results_df\n```\n\nAs the developer, we are including the lines in `__init__.py` to make it easier on our users by exposing commonly used objects at the package level. \n\nThings can get way more confusing when we start to develop subpackages and have complex dependencies between packages, but for now, this is enough. For a good discussion of `__init__.py`, check out [this StackOverflow post](https://stackoverflow.com/questions/448271/what-is-init-py-for).", "_____no_output_____" ], [ "### Installing our package and learning about that setup.py file\nFinally, we are ready to create our `whatif` package and then \"deploy\" it by installing it into a new conda virtual environment. Wider deployment such as publishing our package to PyPI will wait. Since our project is in a public GitHub repo, others can clone our project and install it themselves in the same way we are about to install it. If we really aren't ready to share our project with the world in any way, we could simply make the GitHub repo private. Even free GitHub accounts get some limited number of private repos.\n\nLike everything, it seems, in the world of Python packaging there are all kinds of potential complications and frustrations. We'll be trying to keep things as simple as possible.\n\nThe primary role of the `setup.py` file is to act as a configuration file for your project. At a minimum, this file will contain a call to the `setup` function which is part of the [setuptools](https://setuptools.readthedocs.io/en/latest/setuptools.html) package, the primary way Python code is packaged for distribution. The `setup` function has numerous arguments but we will only use a small number of them. \n\n```python\n# setup.py\n\nfrom setuptools import find_packages, setup\n\nsetup(\n name='whatif',\n packages=find_packages(\"src\"),\n package_dir={\"\": \"src\"},\n install_requires=['numpy', 'pandas'],\n version='0.1.0',\n description='What if analysis in Python',\n author='misken',\n license='MIT',\n)\n\n```", "_____no_output_____" ], [ "Most of the options are actually pretty self-explanatory. However, given our folder structure, two of these lines are particularly important.\n\n```python\npackages=find_packages(\"src\"),\npackage_dir={\"\": \"src\"},\n```\n\nThe `find_packages` function is part of `setuptools` and we are telling `setup` that it can find our package folders inside of the `src` folder. See the following two links if you are interested in more technical details on these options and broader issues in the Python packaging world.\n\n* https://hynek.me/articles/testing-packaging/\n* https://docs.python.org/3/distutils/setupscript.\n* https://www.python.org/dev/peps/pep-0517/", "_____no_output_____" ], [ "Now we are ready to install our package. For that we will use a tool called pip - which stands for \"pip installs packages\". Backing up for a second, since we are using the Anaconda Python distribution, we usually use conda for installing packages. However, to install packages that are not in conda's repositories, we can actually use pip to install packages into conda virtual environments. To learn more about the relationship between conda and pip:\n\n* https://www.anaconda.com/blog/understanding-conda-and-pip\n* https://www.anaconda.com/blog/using-pip-in-a-conda-environment\n\nHere's a short screencast that demos the following install process:\n\n* [SCREENCAST: pip installing whatif](https://youtu.be/n4wHIX0c4QE) (3:51)\n\nSince we have not published our package to PyPI, we **are going to install it from our local project folder**. Open a shell and navigate to your project folder (it contains `setup.py`). Make sure you activate the `aap` virtual environment before installing your package. For example, we saw earlier in this notebook that my active conda virtual environment is called `aap`. ", "_____no_output_____" ], [ "<div class=\"alert alert-info\">\n <b>For development projects, I usually create a new conda environment to act as a sort of sandbox for trying out new packages. Typically I just clone my <code>aap</code> environment. However, we are just going to install <code>whatif</code> directly into our <code>aap</code> conda virtual environment.</b>\n</div>", "_____no_output_____" ], [ "With the `aap` environment activated, you can install the `whatif` package with:\n\n```bash\npip install .\n```\n\nThe \"dot\" means, install from the current directory (the one with `setup.py` in it).\n\nYou can actually leave this notebook running while you do the install. Okay, let's see if we can import from our new `whatif` package.", "_____no_output_____" ] ], [ [ "from whatif.whatif import Model", "_____no_output_____" ] ], [ [ "Yep, we can. If we rerun the code cell in which the `BookstoreClass` is defined, then we can create a default model just to show that things are working.", "_____no_output_____" ] ], [ [ "model = BookstoreModel()\nprint(model)\nprint(model.profit())", "{'unit_cost': 7.5, 'selling_price': 10.0, 'unit_refund': 2.5, 'order_quantity': 200, 'demand': 193}\n447.5\n" ] ], [ [ "Well, looks like we forgot to include a `__str__` method in the `Model` base class. Of course, we won't know what attributes are in the actual derived class (e.g. `BookstoreModel`), so we can add something generic like this:\n\n```python\n def __str__(self):\n \"\"\"\n Print dictionary of object attributes that don't include an underscore as first char\n \"\"\"\n return str({key: val for (key, val) in vars(self).items() if key[0] != '_'})\n```\n\nLet's go do this in our `whatif.py` file and then figure out how to update our installed package.\n\nHere's a short screencast that demos this change:\n\n* [SCREENCAST: Adding code to whatif.py and committing changes](https://youtu.be/BEhnH3th-uI) (13:39)\n\nOf course, after making this code change to `whatif.py`, we should stage and commit those changes in git and push our code to GitHub. The screencast above also demos this.", "_____no_output_____" ], [ "### What happens when we make changes to whatif.py?\nOur `whatif` package is under active development and we will make changes. What happens then? Similarly, what happens when we add additional files to the `whatif` package?\n\n**Option 1: Reinstall the package**\n\nWe can redo a `pip install .` and away we go. Now, if we are using a Jupyter notebook to \"test\" our new code, we can avoid having to restart the notebook by using a little Jupyter cell magic. Including the following at the top of your notebook and running them first thing will [cause all import statements to automatically reload](https://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html?highlight=autoreload) if they detect changes in the underlying imported modules.\n\n```bash\n%load_ext autoreload\n%autoreload 2\n```\n\n**Option 2: Do an \"editable\" install**\n\nIf you do a pip install with the `-e` flag, you do what is known as an *editable install* or *installing in development mode*. \n\n```bash\npip install -e .\n```\n\nThis is a common strategy during active development. By doing this, your import is actually using the code under development - pip is creating links to your source code instead of installing source files into some `site-packages` folder. Doing this along with the autoreload cell magic above provides an easy way to do simple package development in Jupyter notebooks. You can also make use of packages that were installed in this manner when using IDEs such as PyCharm. See https://packaging.python.org/guides/distributing-packages-using-setuptools/#working-in-development-mode for more info.", "_____no_output_____" ], [ "## Concluding thoughts and next steps\n\nWe have gone over some basic concepts and techniques for:\n\n* creating a good Python project structure using a cookiecutter,\n* putting your project under version control,\n* improving on our original OO design by implementing a base class,\n* created an installable package for our growing, `whatif` library.\n\nWhile we've certainly glossed over a bunch of details, we can revisit these topics later as we progress in our learning. In addition, there are numerous related topics that we will get to later in the course. For a preview of some these, I highly recommend the tutorial by MolSSI - [Python Packages Best Practices](https://education.molssi.org/python-package-best-practices/). For example, we still need to address:\n\n* writing documentation (see the `docs/` folder),\n* testing using tools like pytest,\n* continuous integration (automated testing),\n* uploading packages to PyPI.\n\nWith this current version of whatif, we can begin to try to port other spreadsheet models to Python. I've already done this with a typical multi-period cash flow model which revealed a number of interesting modeling challenges - see the `new_car_simulation.ipynb` notebook in the `examples/` folder available from https://github.com/misken/whatif.\n\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
4a50d978df6b2df9221fdb23ffa4a37ac4cf13fc
5,428
ipynb
Jupyter Notebook
Allinone py/tuple.ipynb
whoafridi/Python
4fea6f81ebfd94730b36b4d95669adcadacae5df
[ "MIT" ]
null
null
null
Allinone py/tuple.ipynb
whoafridi/Python
4fea6f81ebfd94730b36b4d95669adcadacae5df
[ "MIT" ]
null
null
null
Allinone py/tuple.ipynb
whoafridi/Python
4fea6f81ebfd94730b36b4d95669adcadacae5df
[ "MIT" ]
1
2019-07-09T06:34:29.000Z
2019-07-09T06:34:29.000Z
16.202985
58
0.431282
[ [ [ "# Tuple", "_____no_output_____" ] ], [ [ "()", "_____no_output_____" ], [ "type(())", "_____no_output_____" ], [ "t = 1,3\nprint(t)", "(1, 3)\n" ], [ "1,2", "_____no_output_____" ], [ "type((1,2))", "_____no_output_____" ] ], [ [ "* Checking time for list & tuple operation", "_____no_output_____" ] ], [ [ "import timeit\nli = timeit.timeit(stmt='[1,2,3]',number=1000000)\ntu = timeit.timeit(stmt='(1,2,3)',number=1000000)\n\nprint(\"list time \",li)\nprint(\"tuple time \",tu)", "list time 0.08501901399722556\ntuple time 0.012194160997751169\n" ] ], [ [ "* Assignment operation ", "_____no_output_____" ] ], [ [ "( x , y) = ( 3 , 6)", "_____no_output_____" ], [ "y", "_____no_output_____" ], [ "x", "_____no_output_____" ], [ "(4,1,2) == (x,y)", "_____no_output_____" ], [ "(1,2,3) < (3,4)", "_____no_output_____" ], [ "('afridi', 'hello') < ('we' , 'lol')", "_____no_output_____" ], [ "('jones' , 'sally', 'lol') > ('po','pol')", "_____no_output_____" ], [ "survey2 = (21,\"Bangladesh\",False)\nage , country , knows_python = survey2 \n", "_____no_output_____" ], [ "print(\"age =\",age)\nprint(\"country =\", country)\nprint(\"Know ? = \",knows_python)", "age = 21\ncountry = Bangladesh\nKnow ? = False\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a50dbf6803aa6519edbdff6226f75e9d709e32c
13,829
ipynb
Jupyter Notebook
examples/Basic functionality.ipynb
adozier/pymatgen
f1cc4d8db24ec11063be2fd84b4ea911f006eeb7
[ "MIT" ]
1
2015-05-18T14:31:20.000Z
2015-05-18T14:31:20.000Z
examples/Basic functionality.ipynb
rousseab/pymatgen
ecfba4a576a21f31c222be8fd20ce2ddaa77495a
[ "MIT" ]
null
null
null
examples/Basic functionality.ipynb
rousseab/pymatgen
ecfba4a576a21f31c222be8fd20ce2ddaa77495a
[ "MIT" ]
null
null
null
28.63147
451
0.577988
[ [ [ "## Introduction", "_____no_output_____" ], [ "This notebook demostrates the core functionality of pymatgen, including the core objects representing Elements, Species, Lattices, and Structures. \n\nBy convention, we import pymatgen as mg.", "_____no_output_____" ] ], [ [ "import pymatgen as mg", "_____no_output_____" ] ], [ [ "## Basic Element, Specie and Composition objects", "_____no_output_____" ], [ "Pymatgen contains a set of core classes to represent an Element, Specie and Composition. These objects contains useful properties such as atomic mass, ionic radii, etc. These core classes are loaded by default with pymatgen. An Element can be created as follows:", "_____no_output_____" ] ], [ [ "si = mg.Element(\"Si\")\nprint(\"Atomic mass of Si is {}\".format(si.atomic_mass))\nprint(\"Si has a melting point of {}\".format(si.melting_point))\nprint(\"Ionic radii for Si: {}\".format(si.ionic_radii))", "Atomic mass of Si is 28.0855 amu\nSi has a melting point of 1687 K\nIonic radii for Si: {4: 0.54}\n" ] ], [ [ "You can see that units are printed for atomic masses and ionic radii. Pymatgen comes with a complete system of managing units in pymatgen.core.unit. A Unit is a subclass of float that attaches units and handles conversions. For example,", "_____no_output_____" ] ], [ [ "print(\"Atomic mass of Si in kg: {}\".format(si.atomic_mass.to(\"kg\")))", "Atomic mass of Si in kg: 4.66370658657e-26 kg\n" ] ], [ [ "Please refer to the Units example for more information on units. Species are like Elements, except they have an explicit oxidation state. They can be used wherever Element is used for the most part.", "_____no_output_____" ] ], [ [ "fe2 = mg.Specie(\"Fe\", 2)\nprint(fe2.atomic_mass)\nprint(fe2.ionic_radius)", "55.845 amu\n0.92 ang\n" ] ], [ [ "A Composition is essentially an **immutable** mapping of Elements/Species with amounts, and useful properties like molecular weight, get_atomic_fraction, etc. Note that you can conveniently either use an Element/Specie object or a string as keys (this is a feature).", "_____no_output_____" ] ], [ [ "comp = mg.Composition(\"Fe2O3\")\nprint(\"Weight of Fe2O3 is {}\".format(comp.weight))\nprint(\"Amount of Fe in Fe2O3 is {}\".format(comp[\"Fe\"]))\nprint(\"Atomic fraction of Fe is {}\".format(comp.get_atomic_fraction(\"Fe\")))\nprint(\"Weight fraction of Fe is {}\".format(comp.get_wt_fraction(\"Fe\")))", "Weight of Fe2O3 is 159.6882 amu\nAmount of Fe in Fe2O3 is 2.0\nAtomic fraction of Fe is 0.4\nWeight fraction of Fe is 0.699425505454 \n" ] ], [ [ "## Lattice & Structure objects", "_____no_output_____" ], [ "A Lattice represents a Bravais lattice. Convenience static functions are provided for the creation of common lattice types from a minimum number of arguments. ", "_____no_output_____" ] ], [ [ "# Creates cubic Lattice with lattice parameter 4.2\nlattice = mg.Lattice.cubic(4.2)\nprint(lattice.lengths_and_angles)", "((4.2000000000000002, 4.2000000000000002, 4.2000000000000002), (90.0, 90.0, 90.0))\n" ] ], [ [ "A Structure object represents a crystal structure (lattice + basis). A Structure is essentially a list of PeriodicSites with the same Lattice. Let us now create a CsCl structure.", "_____no_output_____" ] ], [ [ "structure = mg.Structure(lattice, [\"Cs\", \"Cl\"], [[0, 0, 0], [0.5, 0.5, 0.5]])\nprint(\"Unit cell vol = {}\".format(structure.volume))\nprint(\"First site of the structure is {}\".format(structure[0]))", "Unit cell vol = 74.088\nFirst site of the structure is [ 0. 0. 0.] Cs\n" ] ], [ [ "The Structure object contains many useful manipulation functions. Since Structure is essentially a list, it contains a simple pythonic API for manipulation its sites. Some examples are given below. Please note that there is an immutable version of Structure known as IStructure, for the use case where you really need to enforce that the structure does not change. Conversion between these forms of Structure can be performed using from_sites().", "_____no_output_____" ] ], [ [ "structure.make_supercell([2, 2, 1]) #Make a 3 x 2 x 1 supercell of the structure\ndel structure[0] #Remove the first site\nstructure.append(\"Na\", [0,0,0]) #Append a Na atom.\nstructure[-1] = \"Li\" #Change the last added atom to Li.\nstructure[0] = \"Cs\", [0.01, 0.5, 0] #Shift the first atom by 0.01 in fractional coordinates in the x-direction.\nimmutable_structure = mg.IStructure.from_sites(structure) #Create an immutable structure (cannot be modified).\nprint(immutable_structure)", "Structure Summary (Cs3 Li1 Cl4)\nReduced Formula: Cs3LiCl4\nabc : 8.400000 8.400000 4.200000\nangles: 90.000000 90.000000 90.000000\nSites (8)\n1 Cs 0.010000 0.500000 0.000000\n2 Cs 0.500000 0.000000 0.000000\n3 Cs 0.500000 0.500000 0.000000\n4 Cl 0.250000 0.250000 0.500000\n5 Cl 0.250000 0.750000 0.500000\n6 Cl 0.750000 0.250000 0.500000\n7 Cl 0.750000 0.750000 0.500000\n8 Li 0.000000 0.000000 0.000000\n" ] ], [ [ "## Basic analyses", "_____no_output_____" ], [ "Pymatgen provides many analyses functions for Structures. Some common ones are given below.", "_____no_output_____" ] ], [ [ "#Determining the symmetry\nfrom pymatgen.symmetry.analyzer import SpacegroupAnalyzer\nfinder = SpacegroupAnalyzer(structure)\nprint(\"The spacegroup is {}\".format(finder.get_spacegroup_symbol()))", "The spacegroup is P2mm\n" ] ], [ [ "We also have an extremely powerful structure matching tool.", "_____no_output_____" ] ], [ [ "from pymatgen.analysis.structure_matcher import StructureMatcher\n#Let's create two structures which are the same topologically, but with different elements, and one lattice is larger.\ns1 = mg.Structure(lattice, [\"Cs\", \"Cl\"], [[0, 0, 0], [0.5, 0.5, 0.5]])\ns2 = mg.Structure(mg.Lattice.cubic(5), [\"Rb\", \"F\"], [[0, 0, 0], [0.5, 0.5, 0.5]])\nm = StructureMatcher()\nprint(m.fit_anonymous(s1, s2)) #Returns a mapping which maps s1 and s2 onto each other. Strict element fitting is also available.", "True\n" ] ], [ [ "## Input/output", "_____no_output_____" ], [ "Pymatgen also provides IO support for various file formats in the pymatgen.io package. A convenient set of read_structure and write_structure functions are also provided which auto-detects several well-known formats. ", "_____no_output_____" ] ], [ [ "#Convenient IO to various formats. Format is intelligently determined from file name and extension.\nstructure.to(filename=\"POSCAR\")\nstructure.to(filename=\"CsCl.cif\")\n\n#Or if you just supply fmt, you simply get a string.\nprint(structure.to(fmt=\"poscar\"))\nprint(structure.to(fmt=\"cif\"))", "Cs3 Li1 Cl4\n1.0\n8.400000 0.000000 0.000000\n0.000000 8.400000 0.000000\n0.000000 0.000000 4.200000\nCs Cl Li\n3 4 1\ndirect\n0.010000 0.500000 0.000000 Cs\n0.500000 0.000000 0.000000 Cs\n0.500000 0.500000 0.000000 Cs\n0.250000 0.250000 0.500000 Cl\n0.250000 0.750000 0.500000 Cl\n0.750000 0.250000 0.500000 Cl\n0.750000 0.750000 0.500000 Cl\n0.000000 0.000000 0.000000 Li\n\n#generated using pymatgen\ndata_Cs3LiCl4\n_symmetry_space_group_name_H-M 'P 1'\n_cell_length_a 8.40000000\n_cell_length_b 8.40000000\n_cell_length_c 4.20000000\n_cell_angle_alpha 90.00000000\n_cell_angle_beta 90.00000000\n_cell_angle_gamma 90.00000000\n_symmetry_Int_Tables_number 1\n_chemical_formula_structural Cs3LiCl4\n_chemical_formula_sum 'Cs3 Li1 Cl4'\n_cell_volume 296.352\n_cell_formula_units_Z 1\nloop_\n _symmetry_equiv_pos_site_id\n _symmetry_equiv_pos_as_xyz\n 1 'x, y, z'\nloop_\n _atom_site_type_symbol\n _atom_site_label\n _atom_site_symmetry_multiplicity\n _atom_site_fract_x\n _atom_site_fract_y\n _atom_site_fract_z\n _atom_site_occupancy\n Cs Cs1 1 0.010000 0.500000 0.000000 1\n Cs Cs2 1 0.500000 0.000000 0.000000 1\n Cs Cs3 1 0.500000 0.500000 0.000000 1\n Cl Cl4 1 0.250000 0.250000 0.500000 1\n Cl Cl5 1 0.250000 0.750000 0.500000 1\n Cl Cl6 1 0.750000 0.250000 0.500000 1\n Cl Cl7 1 0.750000 0.750000 0.500000 1\n Li Li8 1 0.000000 0.000000 0.000000 1\n\n" ], [ "#Reading a structure from a file.\nstructure = mg.Structure.from_file(\"POSCAR\")", "_____no_output_____" ] ], [ [ "The vaspio_set module provides a means o obtain a complete set of VASP input files for performing calculations. Several useful presets based on the parameters used in the Materials Project are provided.", "_____no_output_____" ] ], [ [ "from pymatgen.io.vaspio_set import MPVaspInputSet\nv = MPVaspInputSet()\nv.write_input(structure, \"MyInputFiles\") #Writes a complete set of input files for structure to the directory MyInputFiles", "_____no_output_____" ] ], [ [ "### This concludes this pymatgen tutorial. Please explore the usage pages on pymatgen.org for more information.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a50dea03f86e61775af05decbf438655e69e421
479,757
ipynb
Jupyter Notebook
Modelling-Update.ipynb
arms3/Jobs-Stock-Price_Prediction
08eeecd126bbcc287d11a58c6095ab38cc598246
[ "MIT" ]
1
2019-01-20T23:15:57.000Z
2019-01-20T23:15:57.000Z
Modelling-Update.ipynb
arms3/Jobs-Stock-Price_Prediction
08eeecd126bbcc287d11a58c6095ab38cc598246
[ "MIT" ]
null
null
null
Modelling-Update.ipynb
arms3/Jobs-Stock-Price_Prediction
08eeecd126bbcc287d11a58c6095ab38cc598246
[ "MIT" ]
null
null
null
401.134615
96,908
0.897415
[ [ [ "# Stock Price Prediction From Employee / Job Market Information\n## Modelling: Linear Model\nObjective utilise the Thinknum LinkedIn and Job Postings datasets, along with the Quandl WIKI prices dataset to investigate the effect of hiring practices on stock price. In this notebook I'll begin exploring the increase in predictive power from historic employment data.", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom pathlib import Path\nfrom glob import glob\n\n# Utilities\nfrom utils import *\n\n%matplotlib inline\nPATH = Path('D:\\data\\jobs')", "_____no_output_____" ], [ "%%capture #ignore output warnings for now\nlink, companies, stocks = data_load(PATH)", "_____no_output_____" ] ], [ [ "Let's start with some of the series that had the most promising cross correlations.", "_____no_output_____" ] ], [ [ "filtered = companies.sort_values('max_corr',ascending=False)[['dataset_id', 'company_name','MarketCap', 'Sector', 'Symbol',\n 'max_corr', 'best_lag']]\nfiltered = filtered.query('(max_corr > 0.95) & (best_lag < -50)')\nfiltered.head()", "_____no_output_____" ] ], [ [ "Modelling for the top stock here USA Truck Inc.", "_____no_output_____" ] ], [ [ "USAK = stocks.USAK\nUSAK_link = link[link['dataset_id']==929840]['employees_on_platform']", "_____no_output_____" ], [ "start = min(USAK_link.index)\nend = max(USAK_link.index)", "_____no_output_____" ], [ "fig, ax = plt.subplots(figsize=(12,8))\nax.set_xlim(start,end)\nax.plot(USAK.index,USAK, label='Adjusted Close Price (USAK)')\nax.set_ylabel('Adjusted close stock price')\nax1=ax.twinx()\nax1.set_ylabel('LinkedIn employee count')\nax1.plot(USAK_link.index, USAK_link,color='r',label='LinkedIn employee data')\nplt.legend();", "_____no_output_____" ], [ "# Error in this code leading to slightly different train time ranges\ndef build_t_feats(stock,employ,n, include_employ=True):\n if include_employ:\n X = pd.concat([stock,employ],axis=1)\n X.columns = ['close','emps']\n else:\n X = pd.DataFrame(stock)\n X.columns = ['close']\n y=None\n \n start = max(pd.datetime(2016,7,1),min(stock.dropna().index)) - pd.Timedelta(1, unit='d')\n end = max(stock.dropna().index)\n \n X = X.loc[start:end]\n \n # Normalize\n X = (X-X.mean())/X.std()\n \n # Fill gaps\n X = X.interpolate()\n \n # Daily returns\n X = X.diff()\n \n # Create target variable\n X['y'] = X.close.shift(-1)\n \n # Create time shifted features\n for t in range(n):\n X['c'+str(t+1)] = X.close.shift(t+1)\n if include_employ: X['e'+str(t+1)] = X.emps.shift(t+1)\n \n X = X.dropna()\n \n y = X.y\n X.drop('y',axis=1,inplace=True)\n \n return X,y\n\nX, y = build_t_feats(USAK,USAK_link,180)", "_____no_output_____" ] ], [ [ "## Linear Model\nStart with a basic linear model, so we can easily interpret the model outputs.", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import TimeSeriesSplit, cross_val_score\nfrom sklearn.linear_model import Ridge, LinearRegression\nfrom sklearn.metrics import mean_absolute_error\n\nreg = Ridge()\n\ndef fit_predict(reg, X, y, plot=True):\n cv = TimeSeriesSplit(n_splits=10)\n scores = cross_val_score(reg, X, y, cv=cv, scoring='neg_mean_absolute_error')\n if plot: print('Mean absolute error: ', np.mean(-scores), '\\nSplit scores: ',-scores)\n\n cut = int(X.shape[0]*0.9)\n X_train, y_train = X[:cut], y[:cut].values.reshape(-1,1)\n X_dev, y_dev = X[cut:], y[cut:].values.reshape(-1,1)\n\n reg.fit(X_train,y_train)\n\n pred_dev = reg.predict(X_dev)\n pred_train = reg.predict(X_train)\n \n if plot:\n f,ax = plt.subplots(nrows=1,ncols=2,figsize=(25,8))\n ax[0].plot(y_train,pred_train,marker='.',linestyle='None',alpha=0.6,label='train')\n ax[0].plot(y_dev,pred_dev,marker='.',linestyle='None',color='r',alpha=0.6,label='dev')\n ax[0].set_title('Predicted v actual daily changes')\n ax[0].legend()\n\n ax[1].plot(X[cut:].index,y_dev,alpha=0.6,label='actual',marker='.')\n ax[1].plot(X[cut:].index,pred_dev,color='r',alpha=0.6,label='predict',marker='.')\n ax[1].set_title('Development set, predicted v actual daily changes')\n ax[1].legend();\n \n return reg, np.mean(-scores)\n\nreg, _ = fit_predict(reg, X, y)", "Mean absolute error: 0.05485194746799064 \nSplit scores: [0.0214873 0.03508219 0.03497026 0.05428902 0.0430487 0.03043928\n 0.0585213 0.1008948 0.08044345 0.08934317]\n" ] ], [ [ "Using MAE (Mean Absolute Error) as the evaluation metric here. Around 0.05 MAE seems acceptable at predicting the daily changes.", "_____no_output_____" ] ], [ [ "coefs = reg.coef_.ravel()\nidx = coefs.argsort()[-40:]", "_____no_output_____" ], [ "x = np.arange(len(coefs[idx]))\nfig,ax = plt.subplots(figsize=(20,5))\nplt.bar(x,coefs[idx])\nplt.xticks(x,X.columns.values[idx])\nplt.title('Importance of shifted feature in model')\nplt.show();", "_____no_output_____" ] ], [ [ "Looks like most of the top features are time lagged versions of the daily price change rather than the employment data.\n\n## Same model excluding employment data\nI'll now rerun the same analysis but exluced the employment data.", "_____no_output_____" ] ], [ [ "X, y = build_t_feats(USAK,USAK_link,180,include_employ=False)", "_____no_output_____" ], [ "reg = Ridge()\nreg, _ = fit_predict(reg, X, y)", "Mean absolute error: 0.0607687153067917 \nSplit scores: [0.02911067 0.04328596 0.03876474 0.04835429 0.03579512 0.04716982\n 0.07197536 0.06298087 0.10960007 0.12065024]\n" ], [ "coefs = reg.coef_.ravel()\nidx = coefs.argsort()[-40:]", "_____no_output_____" ], [ "x = np.arange(len(coefs[idx]))\nfig,ax = plt.subplots(figsize=(20,5))\nplt.bar(x,coefs[idx])\nplt.xticks(x,X.columns.values[idx])\nplt.title('Importance of shifted feature in model')\nplt.show();", "_____no_output_____" ] ], [ [ "Over a similar time period it looks like our model performed better using employment data.", "_____no_output_____" ], [ "## Rerun analysis for all top stocks", "_____no_output_____" ] ], [ [ "%%capture\n\ndef run_for_all(filtered):\n MAEs = np.full((len(filtered),2),np.nan)\n for i,ID in enumerate(filtered.dataset_id.values):\n print(i, ID, filtered.set_index('dataset_id').loc[ID].company_name)\n\n try:\n sym = filtered.set_index('dataset_id').loc[ID].Symbol\n tick = stocks[sym]\n emp = link[link['dataset_id']==ID]['employees_on_platform']\n except:\n print('Symbol Error, Skipping')\n\n # Including employee data\n X, y = build_t_feats(tick,emp,180,True)\n reg = Ridge()\n reg, MAE = fit_predict(reg, X, y, plot=False)\n MAEs[i][0] = MAE\n\n # Excluding employee data\n X, y = build_t_feats(tick,emp,180,False)\n reg = Ridge()\n reg, MAE = fit_predict(reg, X, y, plot=False)\n MAEs[i][1] = MAE\n \n # Create columns with mean absolute errors added\n filtered['MAE_w_emp'] = MAEs[:,0]\n filtered['MAE_wo_emp'] = MAEs[:,1]\n \n return filtered\n\nfiltered = filtered[filtered.dataset_id != 868877].copy()\nfiltered = run_for_all(filtered)", "_____no_output_____" ], [ "from bokeh.plotting import figure, show, output_notebook\nfrom bokeh.models import HoverTool\noutput_notebook()", "_____no_output_____" ], [ "def plot_predicts(filtered):\n TOOLS=\"hover,save\"\n p1 = figure(plot_width=600, plot_height=600, title=\"Prediction score with and without LinkedIn data\",tools=TOOLS)\n p1.xgrid.grid_line_color = None\n p1.circle(x='MAE_wo_emp', y='MAE_w_emp', size=12, alpha=0.5, source=filtered)\n p1.line(x=np.arange(0,0.25,0.01),y=np.arange(0,0.25,0.01))\n\n p1.xaxis.axis_label = 'MAE with employee data in model'\n p1.yaxis.axis_label = 'MAE without employee data in model'\n\n hover = p1.select(dict(type=HoverTool))\n hover.tooltips = [\n (\"Name\", \"@company_name\"),\n (\"Correlation\", \"@max_corr\"),\n (\"Optimal Lag\", \"@best_lag\"),\n ]\n\n show(p1)\n \nplot_predicts(filtered)", "_____no_output_____" ] ], [ [ "The vast majority of points fall below the line, suggesting the predictions generated with a simple linear model were improved when Employee data was included in the model.\n\n**However** upon further review of my methodology it looks like I'm using comparing prediction accuracy on slightly different time ranges. I'll re-run the code below this time fixing identical time ranges.", "_____no_output_____" ] ], [ [ "# Updated code for processing data\ndef build_t_feats(stock,employ,n, include_employ=True, norm_diff=True):\n X = pd.concat([stock,employ],axis=1)\n X.columns = ['close','emps']\n y=None\n \n #start = max(pd.datetime(2016,7,1),min(stock.dropna().index)) - pd.Timedelta(1, unit='d')\n start = min(employ.dropna().index) - pd.Timedelta(1, unit='d')\n end = max(stock.dropna().index)\n \n #print(start,end)\n \n X = X.loc[start:end]\n \n if norm_diff:\n # Normalize\n X = (X-X.mean())/X.std()\n \n # Fill gaps\n X = X.interpolate()\n \n if norm_diff:\n # Daily returns\n X = X.diff()\n \n # Create target variable\n X['y'] = X.close.shift(-1)\n \n # Create time shifted features\n for t in range(n):\n X['c'+str(t+1)] = X.close.shift(t+1)\n if include_employ: X['e'+str(t+1)] = X.emps.shift(t+1)\n \n X = X.dropna()\n if not include_employ: X = X.drop('emps',axis=1)\n \n y = X.y\n X.drop('y',axis=1,inplace=True)\n \n return X,y", "_____no_output_____" ] ], [ [ "### With employment data", "_____no_output_____" ] ], [ [ "X, y = build_t_feats(USAK,USAK_link,180)", "_____no_output_____" ], [ "reg = Ridge()\nreg, _ = fit_predict(reg, X, y)", "Mean absolute error: 0.04926926725580603 \nSplit scores: [0.03335929 0.02690264 0.03467498 0.05053564 0.03168399 0.03827381\n 0.03724412 0.09934222 0.06237898 0.07829699]\n" ] ], [ [ "### Without Employment Data", "_____no_output_____" ] ], [ [ "X, y = build_t_feats(USAK,USAK_link,180,include_employ=False)", "_____no_output_____" ], [ "reg = Ridge()\nreg, _ = fit_predict(reg, X, y)", "Mean absolute error: 0.049356741203788926 \nSplit scores: [0.03338896 0.02696045 0.03466529 0.05056507 0.031752 0.03824312\n 0.03713299 0.09991927 0.06270097 0.07823932]\n" ] ], [ [ "As you can see the results are a lot less clear here. It looks as if there is no improved predictive power from including employment data.\n\n## Rerun on all stocks", "_____no_output_____" ] ], [ [ "%%capture\nfiltered = companies.sort_values('max_corr',ascending=False)[['dataset_id', 'company_name','MarketCap', 'Sector', 'Symbol',\n 'max_corr', 'best_lag']]\nfiltered = filtered.query('(max_corr > 0.95) & (best_lag < -50)')\nfiltered = filtered[filtered.dataset_id != 868877].copy()\nfiltered = run_for_all(filtered)", "_____no_output_____" ], [ "plot_predicts(filtered)", "_____no_output_____" ] ], [ [ "As you can see except for some noise most stocks fall along the line **suggesting that there is no improvement in prediction accuracy when including LinkedIn data**.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4a50e2fa0aceda5d10e3b25922ae8f347ced7fe7
20,637
ipynb
Jupyter Notebook
ch10.ipynb
YanhuiJing/pydata-book
edf47cff4a0bcb334fc94ee2fdd0016935ba20ab
[ "MIT" ]
null
null
null
ch10.ipynb
YanhuiJing/pydata-book
edf47cff4a0bcb334fc94ee2fdd0016935ba20ab
[ "MIT" ]
null
null
null
ch10.ipynb
YanhuiJing/pydata-book
edf47cff4a0bcb334fc94ee2fdd0016935ba20ab
[ "MIT" ]
null
null
null
21.036697
80
0.489606
[ [ [ "# Data Aggregation and Group Operations", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nPREVIOUS_MAX_ROWS = pd.options.display.max_rows\npd.options.display.max_rows = 20\nnp.random.seed(12345)\nimport matplotlib.pyplot as plt\nplt.rc('figure', figsize=(10, 6))\nnp.set_printoptions(precision=4, suppress=True)", "_____no_output_____" ] ], [ [ "## GroupBy Mechanics", "_____no_output_____" ] ], [ [ "df = pd.DataFrame({'key1' : ['a', 'a', 'b', 'b', 'a'],\n 'key2' : ['one', 'two', 'one', 'two', 'one'],\n 'data1' : np.random.randn(5),\n 'data2' : np.random.randn(5)})\ndf", "_____no_output_____" ], [ "grouped = df['data1'].groupby(df['key1'])\ngrouped", "_____no_output_____" ], [ "grouped.mean()", "_____no_output_____" ], [ "means = df['data1'].groupby([df['key1'], df['key2']]).mean()\nmeans", "_____no_output_____" ], [ "means.unstack()", "_____no_output_____" ], [ "states = np.array(['Ohio', 'California', 'California', 'Ohio', 'Ohio'])\nyears = np.array([2005, 2005, 2006, 2005, 2006])\ndf['data1'].groupby([states, years]).mean()", "_____no_output_____" ], [ "df.groupby('key1').mean()\ndf.groupby(['key1', 'key2']).mean()", "_____no_output_____" ], [ "df.groupby(['key1', 'key2']).size()", "_____no_output_____" ] ], [ [ "### Iterating Over Groups", "_____no_output_____" ] ], [ [ "for name, group in df.groupby('key1'):\n print(name)\n print(group)", "_____no_output_____" ], [ "for (k1, k2), group in df.groupby(['key1', 'key2']):\n print((k1, k2))\n print(group)", "_____no_output_____" ], [ "pieces = dict(list(df.groupby('key1')))\npieces['b']", "_____no_output_____" ], [ "df.dtypes\ngrouped = df.groupby(df.dtypes, axis=1)", "_____no_output_____" ], [ "for dtype, group in grouped:\n print(dtype)\n print(group)", "_____no_output_____" ] ], [ [ "### Selecting a Column or Subset of Columns", "_____no_output_____" ], [ "df.groupby('key1')['data1']\ndf.groupby('key1')[['data2']]", "_____no_output_____" ], [ "df['data1'].groupby(df['key1'])\ndf[['data2']].groupby(df['key1'])", "_____no_output_____" ] ], [ [ "df.groupby(['key1', 'key2'])[['data2']].mean()", "_____no_output_____" ], [ "s_grouped = df.groupby(['key1', 'key2'])['data2']\ns_grouped\ns_grouped.mean()", "_____no_output_____" ] ], [ [ "### Grouping with Dicts and Series", "_____no_output_____" ] ], [ [ "people = pd.DataFrame(np.random.randn(5, 5),\n columns=['a', 'b', 'c', 'd', 'e'],\n index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])\npeople.iloc[2:3, [1, 2]] = np.nan # Add a few NA values\npeople", "_____no_output_____" ], [ "mapping = {'a': 'red', 'b': 'red', 'c': 'blue',\n 'd': 'blue', 'e': 'red', 'f' : 'orange'}", "_____no_output_____" ], [ "by_column = people.groupby(mapping, axis=1)\nby_column.sum()", "_____no_output_____" ], [ "map_series = pd.Series(mapping)\nmap_series\npeople.groupby(map_series, axis=1).count()", "_____no_output_____" ] ], [ [ "### Grouping with Functions", "_____no_output_____" ] ], [ [ "people.groupby(len).sum()", "_____no_output_____" ], [ "key_list = ['one', 'one', 'one', 'two', 'two']\npeople.groupby([len, key_list]).min()", "_____no_output_____" ] ], [ [ "### Grouping by Index Levels", "_____no_output_____" ] ], [ [ "columns = pd.MultiIndex.from_arrays([['US', 'US', 'US', 'JP', 'JP'],\n [1, 3, 5, 1, 3]],\n names=['cty', 'tenor'])\nhier_df = pd.DataFrame(np.random.randn(4, 5), columns=columns)\nhier_df", "_____no_output_____" ], [ "hier_df.groupby(level='cty', axis=1).count()", "_____no_output_____" ] ], [ [ "## Data Aggregation", "_____no_output_____" ] ], [ [ "df\ngrouped = df.groupby('key1')\ngrouped['data1'].quantile(0.9)", "_____no_output_____" ], [ "def peak_to_peak(arr):\n return arr.max() - arr.min()\ngrouped.agg(peak_to_peak)", "_____no_output_____" ], [ "grouped.describe()", "_____no_output_____" ] ], [ [ "### Column-Wise and Multiple Function Application", "_____no_output_____" ] ], [ [ "tips = pd.read_csv('examples/tips.csv')\n# Add tip percentage of total bill\ntips['tip_pct'] = tips['tip'] / tips['total_bill']\ntips[:6]", "_____no_output_____" ], [ "grouped = tips.groupby(['day', 'smoker'])", "_____no_output_____" ], [ "grouped_pct = grouped['tip_pct']\ngrouped_pct.agg('mean')", "_____no_output_____" ], [ "grouped_pct.agg(['mean', 'std', peak_to_peak])", "_____no_output_____" ], [ "grouped_pct.agg([('foo', 'mean'), ('bar', np.std)])", "_____no_output_____" ], [ "functions = ['count', 'mean', 'max']\nresult = grouped['tip_pct', 'total_bill'].agg(functions)\nresult", "_____no_output_____" ], [ "result['tip_pct']", "_____no_output_____" ], [ "ftuples = [('Durchschnitt', 'mean'), ('Abweichung', np.var)]\ngrouped['tip_pct', 'total_bill'].agg(ftuples)", "_____no_output_____" ], [ "grouped.agg({'tip' : np.max, 'size' : 'sum'})\ngrouped.agg({'tip_pct' : ['min', 'max', 'mean', 'std'],\n 'size' : 'sum'})", "_____no_output_____" ] ], [ [ "### Returning Aggregated Data Without Row Indexes", "_____no_output_____" ] ], [ [ "tips.groupby(['day', 'smoker'], as_index=False).mean()", "_____no_output_____" ] ], [ [ "## Apply: General split-apply-combine\n 自定义group函数应用,对分组后的数据做进一步处理", "_____no_output_____" ] ], [ [ "def top(df, n=5, column='tip_pct'):\n return df.sort_values(by=column)[-n:]\ntop(tips, n=6)", "_____no_output_____" ], [ "tips.groupby('smoker').apply(top)", "_____no_output_____" ], [ "tips.groupby(['smoker', 'day']).apply(top, n=1, column='total_bill')", "_____no_output_____" ], [ "result = tips.groupby('smoker')['tip_pct'].describe()\nresult\nresult.unstack('smoker')", "_____no_output_____" ] ], [ [ "f = lambda x: x.describe()\ngrouped.apply(f)", "_____no_output_____" ], [ "### Suppressing the Group Keys", "_____no_output_____" ] ], [ [ "tips.groupby('smoker', group_keys=False).apply(top)", "_____no_output_____" ] ], [ [ "### Quantile and Bucket Analysis", "_____no_output_____" ] ], [ [ "frame = pd.DataFrame({'data1': np.random.randn(1000),\n 'data2': np.random.randn(1000)})\nquartiles = pd.cut(frame.data1, 4)\nquartiles[:10]", "_____no_output_____" ], [ "def get_stats(group):\n return {'min': group.min(), 'max': group.max(),\n 'count': group.count(), 'mean': group.mean()}\ngrouped = frame.data2.groupby(quartiles)\ngrouped.apply(get_stats).unstack()", "_____no_output_____" ], [ "# Return quantile numbers\ngrouping = pd.qcut(frame.data1, 10, labels=False)\ngrouped = frame.data2.groupby(grouping)\ngrouped.apply(get_stats).unstack()", "_____no_output_____" ] ], [ [ "### Example: Filling Missing Values with Group-Specific Values", "_____no_output_____" ] ], [ [ "s = pd.Series(np.random.randn(6))\ns[::2] = np.nan\ns\ns.fillna(s.mean())", "_____no_output_____" ], [ "states = ['Ohio', 'New York', 'Vermont', 'Florida',\n 'Oregon', 'Nevada', 'California', 'Idaho']\ngroup_key = ['East'] * 4 + ['West'] * 4\ndata = pd.Series(np.random.randn(8), index=states)\ndata", "_____no_output_____" ], [ "data[['Vermont', 'Nevada', 'Idaho']] = np.nan\ndata\ndata.groupby(group_key).mean()", "_____no_output_____" ], [ "fill_mean = lambda g: g.fillna(g.mean())\ndata.groupby(group_key).apply(fill_mean)", "_____no_output_____" ], [ "fill_values = {'East': 0.5, 'West': -1}\nfill_func = lambda g: g.fillna(fill_values[g.name])\ndata.groupby(group_key).apply(fill_func)", "_____no_output_____" ] ], [ [ "### Example: Random Sampling and Permutation", "_____no_output_____" ] ], [ [ "# Hearts, Spades, Clubs, Diamonds\nsuits = ['H', 'S', 'C', 'D']\ncard_val = (list(range(1, 11)) + [10] * 3) * 4\nbase_names = ['A'] + list(range(2, 11)) + ['J', 'K', 'Q']\ncards = []\nfor suit in ['H', 'S', 'C', 'D']:\n cards.extend(str(num) + suit for num in base_names)\n\ndeck = pd.Series(card_val, index=cards)", "_____no_output_____" ], [ "deck[:13]", "_____no_output_____" ], [ "def draw(deck, n=5):\n return deck.sample(n)\ndraw(deck)", "_____no_output_____" ], [ "get_suit = lambda card: card[-1] # last letter is suit\ndeck.groupby(get_suit).apply(draw, n=2)", "_____no_output_____" ], [ "deck.groupby(get_suit, group_keys=False).apply(draw, n=2)", "_____no_output_____" ] ], [ [ "### Example: Group Weighted Average and Correlation", "_____no_output_____" ] ], [ [ "df = pd.DataFrame({'category': ['a', 'a', 'a', 'a',\n 'b', 'b', 'b', 'b'],\n 'data': np.random.randn(8),\n 'weights': np.random.rand(8)})\ndf", "_____no_output_____" ], [ "grouped = df.groupby('category')\nget_wavg = lambda g: np.average(g['data'], weights=g['weights'])\ngrouped.apply(get_wavg)", "_____no_output_____" ], [ "close_px = pd.read_csv('examples/stock_px_2.csv', parse_dates=True,\n index_col=0)\nclose_px.info()\nclose_px[-4:]", "_____no_output_____" ], [ "spx_corr = lambda x: x.corrwith(x['SPX'])", "_____no_output_____" ], [ "rets = close_px.pct_change().dropna()", "_____no_output_____" ], [ "get_year = lambda x: x.year\nby_year = rets.groupby(get_year)\nby_year.apply(spx_corr)", "_____no_output_____" ], [ "by_year.apply(lambda g: g['AAPL'].corr(g['MSFT']))", "_____no_output_____" ] ], [ [ "### Example: Group-Wise Linear Regression", "_____no_output_____" ] ], [ [ "import statsmodels.api as sm\ndef regress(data, yvar, xvars):\n Y = data[yvar]\n X = data[xvars]\n X['intercept'] = 1.\n result = sm.OLS(Y, X).fit()\n return result.params", "_____no_output_____" ], [ "by_year.apply(regress, 'AAPL', ['SPX'])", "_____no_output_____" ] ], [ [ "## Pivot Tables and Cross-Tabulation\n povot相当于excel数据透视表操作,操作更便利", "_____no_output_____" ] ], [ [ "tips.pivot_table(index=['day', 'smoker'])", "_____no_output_____" ], [ "tips.pivot_table(['tip_pct', 'size'], index=['time', 'day'],\n columns='smoker')", "_____no_output_____" ], [ "tips.pivot_table(['tip_pct', 'size'], index=['time', 'day'],\n columns='smoker', margins=True)", "_____no_output_____" ], [ "tips.pivot_table('tip_pct', index=['time', 'smoker'], columns='day',\n aggfunc=len, margins=True)", "_____no_output_____" ], [ "tips.pivot_table('tip_pct', index=['time', 'size', 'smoker'],\n columns='day', aggfunc='mean', fill_value=0)", "_____no_output_____" ] ], [ [ "### Cross-Tabulations: Crosstab", "_____no_output_____" ] ], [ [ "from io import StringIO\ndata = \"\"\"\\\nSample Nationality Handedness\n1 USA Right-handed\n2 Japan Left-handed\n3 USA Right-handed\n4 Japan Right-handed\n5 Japan Left-handed\n6 Japan Right-handed\n7 USA Right-handed\n8 USA Left-handed\n9 Japan Right-handed\n10 USA Right-handed\"\"\"\ndata = pd.read_table(StringIO(data), sep='\\s+')", "_____no_output_____" ], [ "data", "_____no_output_____" ], [ "pd.crosstab(data.Nationality, data.Handedness, margins=True)", "_____no_output_____" ], [ "pd.crosstab([tips.time, tips.day], tips.smoker, margins=True)", "_____no_output_____" ], [ "pd.options.display.max_rows = PREVIOUS_MAX_ROWS", "_____no_output_____" ] ], [ [ "## Conclusion", "_____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" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ] ]
4a50e5f9059b9ea63203744c86ab6539ef5dc3f7
4,271
ipynb
Jupyter Notebook
notebooks/exploration/using_pretrained_cnn.ipynb
vishaalprasad/AnimeRecommendation
db46ef43449ebc38f234a1586627af9979b06357
[ "MIT" ]
null
null
null
notebooks/exploration/using_pretrained_cnn.ipynb
vishaalprasad/AnimeRecommendation
db46ef43449ebc38f234a1586627af9979b06357
[ "MIT" ]
null
null
null
notebooks/exploration/using_pretrained_cnn.ipynb
vishaalprasad/AnimeRecommendation
db46ef43449ebc38f234a1586627af9979b06357
[ "MIT" ]
null
null
null
24.831395
593
0.59026
[ [ [ "This notebook is an attempt to test and prototype using a pretrained tensorflow CNN to do classification. The end goal is to be able to take add the following as an anime-specific feature: a CNN's embeddings of the default image on MyAnimeList for that anime. The idea is that there is certain visual content that goes into a person's enjoyment of an anime: art style, character design, and color scheme, for example. I want that information via a high-level representation of the image in a deep CNN pipeline. This notebook is simply an attempt getting getting the CNN part to work. \n\nThe CNN is is downloaded from Illustration2Vec (Saito & Matsui, 2015) and is pretrained on anime images. That means the feature space is uniquely suited to capturing relevant information from anime. However, this was done on Caffe, which I do not have installed. Consequently, I used the caffe-tensorflow tool (https://github.com/ethereon/caffe-tensorflow) to convert this model into a tensorflow model (via an Amazon EC2 instance).\n\nThere are examples but no clear tutorials on how to use the caffe-tensorflow tool, so this exploratory notebook is an attempt to get it to work.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport tensorflow as tf\nimport os.path as osp", "_____no_output_____" ] ], [ [ "Images are 224x224 pixels, with 3 channels. Batch size is 50. This is specified in the caffemodel but not in the tf class (mynet.py)", "_____no_output_____" ] ], [ [ "input_size = {50, 3, 224, 224} ", "_____no_output_____" ], [ "fake_data = np.random.rand(2, 224, 224, 3)", "_____no_output_____" ] ], [ [ "Now to actually load the model. ", "_____no_output_____" ] ], [ [ "from mynet import CaffeNet\nimages = tf.placeholder(tf.float32, [None, 224, 224, 3])\n\nnet = CaffeNet({'data':images})", "_____no_output_____" ], [ "sesh = tf.Session()\nsesh.run(tf.global_variables_initializer())", "_____no_output_____" ], [ "# Load the data\nnet.load('mynet.npy', sesh)", "_____no_output_____" ], [ "# Forward pass\noutput = sesh.run(net.get_output(), feed_dict={images: fake_data})", "_____no_output_____" ], [ "sesh.close()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4a50e668560c5a45566418a6dc30e0395bd8ee0c
23,038
ipynb
Jupyter Notebook
notebooks/evaluation.ipynb
riveSunder/carles_game
8eff68cb7b2d87db3a9b160017632b714d309963
[ "MIT" ]
4
2021-04-30T21:27:47.000Z
2021-09-06T20:01:08.000Z
notebooks/evaluation.ipynb
riveSunder/carles_game
8eff68cb7b2d87db3a9b160017632b714d309963
[ "MIT" ]
5
2021-04-18T23:59:11.000Z
2021-06-17T02:41:48.000Z
notebooks/evaluation.ipynb
riveSunder/carles_game
8eff68cb7b2d87db3a9b160017632b714d309963
[ "MIT" ]
1
2021-07-25T02:59:29.000Z
2021-07-25T02:59:29.000Z
41.360862
127
0.547313
[ [ [ "from IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:75% !important; }</style>\"))\n\nimport numpy as np\nimport torch\nimport time\n\nfrom carle.env import CARLE\nfrom carle.mcl import CornerBonus, SpeedDetector, PufferDetector, AE2D, RND2D\nfrom game_of_carle.agents.harli import HARLI\nfrom game_of_carle.agents.carla import CARLA\nfrom game_of_carle.agents.grnn import ConvGRNN\nfrom game_of_carle.agents.toggle import Toggle\n\nimport bokeh\nimport bokeh.io as bio\nfrom bokeh.io import output_notebook, show\nfrom bokeh.plotting import figure\n\nfrom bokeh.layouts import column, row\nfrom bokeh.models import TextInput, Button, Paragraph\nfrom bokeh.models import ColumnDataSource\n\nfrom bokeh.events import DoubleTap, Tap\n\nimport matplotlib.pyplot as plt\nmy_cmap = plt.get_cmap(\"magma\")\n\noutput_notebook()", "_____no_output_____" ], [ "\"\"\"\nTrained with the SpeedDetector and RND2D bonus wrappers with the B358/S245 Morely rules,\nsome of these agents learned that they could game that reward system by exploiting a chaotic boundary with \nessentially random actions. This is something of a specification gaming/reward hacking strategy, as it is \nunlikely for agents to learn more interesting strategies when they already get a high reward from cells near \nthe border transiently becoming active. One way to improve this would be to restrict agent activity to the center \nof the action space (like with the Toggle agent), which yields a buffer between what the agent modifies and\nwhat the speed reward wrapper uses to calculate center of mass. Likewise the reward wrapper could be modified to \ninclude a 'frontier zone' itself.\n\nOccasionally agents exhibit a 'wave' strategy, where toggling all the cells at the action space boundary \ncreates a diminishing line of active cells that propagates toward the CA grid edges. For CARLA agents, this \nstrategy mostly if not only is used immediately after resetting the environment/agent.\n\"\"\"\n\nagent = CARLA()\n\nparams_list = [\\\n \"../policies/CARLA_42_glider_rnd2d_experiment1622466808best_params_gen31.npy\",\\\n \"../policies/CARLA_43110_glider_rnd2d_experiment1622503099best_params_gen31.npy\"] \n\n# choose parameters to load\nparams_index = 0\n\nagent.set_params(np.load(params_list[params_index]))\n\nenv = CARLE(height=128, width=128)\nenv = SpeedDetector(env)\n\nmy_rules = \"B368/S245\"\n\nenv.rules_from_string(my_rules)\n ", "_____no_output_____" ], [ "\"\"\"\nThe Toggle agent parameters become the actions at step 0, after which the agent does nothing until `agent.reset` \nis called. In other words you can use the Toggle agent to optimize an initial pattern directly. \n\nUsing CMA-ES with this strategy and SpeedDetector + RND2D reward wrappers pretty reliably finds patterns than \ncoalesce into a moving machine, although so far the pattern always turns into either a jellyfish glider or\nthe common puffer. \n\"\"\"\n\nagent = Toggle()\n\n#my_params = np.load(\"../policies/Toggle_13_glider_rnd2d_experiment1622420340best_params_gen31.npy\") # glider\n#my_params = np.load(\"../policies/Toggle_1337_glider_rnd2d_experiment1622437453best_params_gen31.npy\") # glider\n#my_params = np.load(\"../policies/Toggle_42_glider_rnd2d_experiment1622455453best_params_gen31.npy\") # glider\n#my_params = np.load(\"../policies/Toggle_12345_glider_rnd2d_experiment1622474002best_params_gen31.npy\") # puffer\n#my_params = np.load(\"../policies/Toggle_43110_glider_rnd2d_experiment1622491637best_params_gen31.npy\") # puffer\n\nparams_list = [\"../policies/Toggle_13_glider_rnd2d_experiment1622420340best_params_gen31.npy\", \\\n \"../policies/Toggle_1337_glider_rnd2d_experiment1622437453best_params_gen31.npy\",\\\n \"../policies/Toggle_42_glider_rnd2d_experiment1622455453best_params_gen31.npy\",\\\n \"../policies/Toggle_12345_glider_rnd2d_experiment1622474002best_params_gen31.npy\",\\\n \"../policies/Toggle_43110_glider_rnd2d_experiment1622491637best_params_gen31.npy\"]\n\nparams_index = 0\n\nagent.set_params(np.load(params_list[params_index]))\n\nenv = CARLE(height=128, width=128)\nenv = SpeedDetector(env)\n\nmy_rules = \"B368/S245\"\n\nenv.rules_from_string(my_rules) ", "_____no_output_____" ], [ "\"\"\"\nTrained with the SpeedDetector and RND2D bonus wrappers with the B358/S245 Morely rules,\nsome of these agents learned that they could game that reward system by exploiting a chaotic boundary with \nessentially random actions. This is something of a specification gaming/reward hacking strategy, as it is \nunlikely for agents to learn more interesting strategies when they already get a high reward from cells near \nthe border transiently becoming active. One way to improve this would be to restrict agent activity to the center \nof the action space (like with the Toggle agent), which yields a buffer between what the agent modifies and\nwhat the speed reward wrapper uses to calculate center of mass. Likewise the reward wrapper could be modified to \ninclude a 'frontier zone' itself.\n\nThere is an interesting reward hack that is sometimes exhibited by HARLI agents trained with SpeedDetector. \nCARLE instances can be reset if the agent toggles every cell in the action space simultaneously, and this can generate\nhigh rewards in one of two ways. The first is that if there are many live cells outside the action space these will\nbe zeroed out when the environment is reset, making for an large change in the center of mass of all live cells as\nis used by SpeedDetector to calculate rewards. The second is that this sets up the environment perfectly for a \nhighly rewarding \"wave\" strategy, where a line of active cells at the action space boundary sets up conditions for \na fast moving line of live cells to propagate toward the grid edge. When both those mechanisms are combined, \nthe rewards can be quite high, although we probably would have preferred agents that come up with or rediscover\ninteresting glider and spaceship patterns. \n\"\"\"\n\nagent = HARLI()\n\nparams_list = [\"../policies/HARLI_13_glider_rnd2d_experiment1622423202best_params_gen31.npy\", \\\n \"../policies/HARLI_42_glider_rnd2d_experiment1622458272best_params_gen31.npy\",\\\n \"../policies/HARLI_1337_glider_rnd2d_experiment1622440720best_params_gen31.npy\",\\\n \"../policies/HARLI_12345_glider_rnd2d_experiment1622477110best_params_gen31.npy\",\\\n \"../policies/HARLI_43110_glider_rnd2d_experiment1622494528best_params_gen31.npy\"]\n\n# choose parameters to load\nparams_index = 0\n\nagent.set_params(np.load(params_list[params_index]))\n\nenv = CARLE(height=128, width=128)\nenv = SpeedDetector(env)\n#env = AE2D(env)\n\nmy_rules = \"B368/S245\"\n\nenv.rules_from_string(my_rules) ", "_____no_output_____" ], [ "def modify_doc(doc):\n \n #agent = SubmissionAgent()\n #agent.toggle_rate = 0.48\n global obs\n obs = env.reset()\n \n p = figure(plot_width=3*256, plot_height=3*256, title=\"CA Universe\")\n p_plot = figure(plot_width=int(2.5*256), plot_height=int(2.5*256), title=\"'Reward'\")\n\n global my_period\n global number_agents\n global agent_number\n \n agent_number = 0\n number_agents = len(params_list)\n my_period = 512 \n \n source = ColumnDataSource(data=dict(my_image=[obs.squeeze().cpu().numpy()]))\n source_plot = ColumnDataSource(data=dict(x=np.arange(1), y=np.arange(1)*0))\n \n img = p.image(image='my_image',x=0, y=0, dw=256, dh=256, palette=\"Magma256\", source=source)\n line_plot = p_plot.line(line_width=3, color=\"firebrick\", source=source_plot)\n \n button_go = Button(sizing_mode=\"stretch_width\", label=\"Run >\") \n button_slower = Button(sizing_mode=\"stretch_width\",label=\"<< Slower\")\n button_faster = Button(sizing_mode=\"stretch_width\",label=\"Faster >>\")\n button_reset = Button(sizing_mode=\"stretch_width\",label=\"Reset\")\n \n button_reset_prev_agent = Button(sizing_mode=\"stretch_width\",label=\"Reset w/ Prev. Agent\")\n button_reset_this_agent = Button(sizing_mode=\"stretch_width\",label=\"Reset w/ This Agent\")\n button_reset_next_agent = Button(sizing_mode=\"stretch_width\",label=\"Reset w/ Next Agent\")\n \n \n input_birth = TextInput(value=\"B\")\n input_survive = TextInput(value=\"S\")\n button_birth = Button(sizing_mode=\"stretch_width\", label=\"Update Birth Rules\")\n button_survive = Button(sizing_mode=\"stretch_width\", label=\"Update Survive Rules\")\n button_agent_switch = Button(sizing_mode=\"stretch_width\", label=\"Turn Agent Off\")\n \n message = Paragraph()\n \n def update():\n global obs\n global stretch_pixel\n global action\n global agent_on\n global my_step\n global rewards\n \n obs, r, d, i = env.step(action)\n rewards = np.append(rewards, r.cpu().numpy().item())\n if agent_on:\n action = agent(obs) #1.0 * (torch.rand(env.instances,1,env.action_height,env.action_width) < 0.05)\n else:\n action = torch.zeros_like(action)\n \n #padded_action = stretch_pixel/2 + env.action_padding(action).squeeze()\n padded_action = stretch_pixel/2 + env.inner_env.action_padding(action).squeeze()\n \n my_img = (padded_action*2 + obs.squeeze()).cpu().numpy()\n my_img[my_img > 3.0] = 3.0\n (padded_action*2 + obs.squeeze()).cpu().numpy()\n new_data = dict(my_image=[my_img])\n \n #new_line = dict(x=np.arange(my_step+2), y=rewards)\n new_line = dict(x=[my_step], y=[r.cpu().numpy().item()])\n \n source.stream(new_data, rollover=1)\n source_plot.stream(new_line, rollover=2000)\n \n my_step += 1\n message.text = f\"agent {agent_number}, step {my_step}, reward: {r.item()} \\n\"\\\n f\"{params_list[agent_number]}\"\n \n \n def go():\n \n if button_go.label == \"Run >\":\n my_callback = doc.add_periodic_callback(update, my_period)\n button_go.label = \"Pause\"\n #doc.remove_periodic_callback(my_callback)\n \n else:\n doc.remove_periodic_callback(doc.session_callbacks[0])\n button_go.label = \"Run >\"\n \n def faster():\n \n \n global my_period\n my_period = max([my_period * 0.5, 1])\n go()\n go()\n \n def slower():\n \n global my_period\n my_period = min([my_period * 2, 8192])\n go()\n go()\n \n def reset():\n global obs\n global stretch_pixel\n global my_step\n global rewards\n \n my_step = 0\n \n obs = env.reset() \n agent.reset()\n \n stretch_pixel = torch.zeros_like(obs).squeeze()\n stretch_pixel[0,0] = 3\n new_data = dict(my_image=[(stretch_pixel + obs.squeeze()).cpu().numpy()])\n rewards = np.array([0])\n \n new_line = dict(x=[my_step], y=[0])\n \n source_plot.stream(new_line, rollover=1)\n source.stream(new_data, rollover=8)\n \n def reset_this_agent():\n \n global obs\n global stretch_pixel\n global my_step\n global rewards\n global agent_number\n global number_agents\n \n my_step = 0\n \n obs = env.reset() \n agent.reset()\n \n stretch_pixel = torch.zeros_like(obs).squeeze()\n stretch_pixel[0,0] = 3\n new_data = dict(my_image=[(stretch_pixel + obs.squeeze()).cpu().numpy()])\n rewards = np.array([0])\n \n new_line = dict(x=[my_step], y=[0])\n \n source_plot.stream(new_line, rollover=1)\n source.stream(new_data, rollover=8)\n \n \n def reset_next_agent():\n \n global obs\n global stretch_pixel\n global my_step\n global rewards\n global agent_number\n global number_agents\n \n my_step = 0\n \n obs = env.reset() \n \n stretch_pixel = torch.zeros_like(obs).squeeze()\n stretch_pixel[0,0] = 3\n new_data = dict(my_image=[(stretch_pixel + obs.squeeze()).cpu().numpy()])\n rewards = np.array([0])\n \n new_line = dict(x=[my_step], y=[0])\n \n source_plot.stream(new_line, rollover=1)\n source.stream(new_data, rollover=8)\n \n agent_number = (agent_number + 1) % number_agents\n \n agent.set_params(np.load(params_list[agent_number]))\n agent.reset()\n \n message.text = f\"reset with agent {agent_number}\"\n \n def reset_prev_agent():\n \n global obs\n global stretch_pixel\n global my_step\n global rewards\n global agent_number\n global number_agents\n \n my_step = 0\n \n obs = env.reset() \n \n stretch_pixel = torch.zeros_like(obs).squeeze()\n stretch_pixel[0,0] = 3\n new_data = dict(my_image=[(stretch_pixel + obs.squeeze()).cpu().numpy()])\n rewards = np.array([0])\n \n new_line = dict(x=[my_step], y=[0])\n \n source_plot.stream(new_line, rollover=1)\n source.stream(new_data, rollover=8)\n \n agent_number = (agent_number - 1) % number_agents\n \n agent.set_params(np.load(params_list[agent_number]))\n agent.reset()\n \n message.text = f\"reset with agent {agent_number}\"\n \n \n def set_birth_rules():\n env.birth_rule_from_string(input_birth.value)\n \n my_message = \"Rules updated to B\"\n \n for elem in env.birth:\n my_message += str(elem)\n my_message += \"/S\" \n \n for elem in env.survive:\n my_message += str(elem)\n \n message.text = my_message\n \n time.sleep(0.1)\n \n def set_survive_rules():\n env.survive_rule_from_string(input_survive.value)\n \n my_message = \"Rules updated to B\"\n \n for elem in env.birth:\n my_message += str(elem)\n my_message += \"/S\" \n \n for elem in env.survive:\n my_message += str(elem)\n \n message.text = my_message\n \n time.sleep(0.1)\n \n def human_toggle(event):\n global action\n \n coords = [np.round(env.height*event.y/256-0.5), np.round(env.width*event.x/256-0.5)]\n offset_x = (env.height - env.action_height) / 2\n offset_y = (env.width - env.action_width) / 2\n \n coords[0] = coords[0] - offset_x\n coords[1] = coords[1] - offset_y\n \n coords[0] = np.uint8(np.clip(coords[0], 0, env.action_height-1))\n coords[1] = np.uint8(np.clip(coords[1], 0, env.action_height-1))\n \n action[:, :, coords[0], coords[1]] = 1.0 * (not(action[:, :, coords[0], coords[1]]))\n \n padded_action = stretch_pixel/2 + env.inner_env.action_padding(action).squeeze()\n \n my_img = (padded_action*2 + obs.squeeze()).cpu().numpy()\n my_img[my_img > 3.0] = 3.0\n (padded_action*2 + obs.squeeze()).cpu().numpy()\n new_data = dict(my_image=[my_img])\n \n source.stream(new_data, rollover=8)\n \n def clear_toggles():\n global action\n \n if button_go.label == \"Pause\":\n \n action *= 0\n doc.remove_periodic_callback(doc.session_callbacks[0])\n button_go.label = \"Run >\"\n\n padded_action = stretch_pixel/2 + env.inner_env.action_padding(action).squeeze()\n\n my_img = (padded_action*2 + obs.squeeze()).cpu().numpy()\n my_img[my_img > 3.0] = 3.0\n (padded_action*2 + obs.squeeze()).cpu().numpy()\n new_data = dict(my_image=[my_img])\n\n source.stream(new_data, rollover=8)\n else:\n doc.add_periodic_callback(update, my_period)\n button_go.label = \"Pause\"\n \n def agent_on_off():\n global agent_on\n \n if button_agent_switch.label == \"Turn Agent Off\":\n agent_on = False\n button_agent_switch.label = \"Turn Agent On\"\n \n else:\n agent_on = True\n button_agent_switch.label = \"Turn Agent Off\"\n \n \n global agent_on\n agent_on = True\n global action\n action = torch.zeros(1, 1, env.action_height, env.action_width)\n \n reset()\n \n \n p.on_event(Tap, human_toggle)\n p.on_event(DoubleTap, clear_toggles)\n \n \n button_reset_prev_agent.on_click(reset_prev_agent)\n button_reset_this_agent.on_click(reset_this_agent)\n button_reset_next_agent.on_click(reset_next_agent)\n \n button_birth.on_click(set_birth_rules)\n button_survive.on_click(set_survive_rules)\n button_go.on_click(go)\n button_faster.on_click(faster)\n button_slower.on_click(slower)\n button_reset.on_click(reset)\n button_agent_switch.on_click(agent_on_off)\n \n \n control_layout = row(button_slower, button_go, button_faster, button_reset)\n policy_change_layout = row(button_reset_prev_agent, button_reset_this_agent, button_reset_next_agent)\n rule_layout = row(input_birth, button_birth, input_survive, button_survive)\n agent_toggle_layout = row(button_agent_switch)\n \n display_layout = row(p, p_plot)\n message_layout = row(message)\n \n doc.add_root(display_layout)\n doc.add_root(control_layout)\n doc.add_root(policy_change_layout)\n doc.add_root(rule_layout)\n doc.add_root(message_layout)\n doc.add_root(agent_toggle_layout)\n \n\nshow(modify_doc) ", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
4a50f317ab3e1f7be1c975961dff1b63ca3223dc
28,186
ipynb
Jupyter Notebook
NetworkVisualization-TensorFlow.ipynb
KeremKurban/Neural-Network
f148e02be5e4acf439812c34896d258cde107375
[ "MIT" ]
10
2019-01-18T10:32:36.000Z
2022-03-14T08:40:23.000Z
NetworkVisualization-TensorFlow.ipynb
KeremKurban/Neural-Network
f148e02be5e4acf439812c34896d258cde107375
[ "MIT" ]
15
2020-03-24T17:09:58.000Z
2022-03-11T23:48:50.000Z
NetworkVisualization-TensorFlow.ipynb
KeremKurban/Neural-Network
f148e02be5e4acf439812c34896d258cde107375
[ "MIT" ]
1
2019-03-09T09:12:25.000Z
2019-03-09T09:12:25.000Z
44.457413
737
0.547009
[ [ [ "# Network Visualization (TensorFlow)\n\nIn this notebook we will explore the use of *image gradients* for generating new images.\n\nWhen training a model, we define a loss function which measures our current unhappiness with the model's performance; we then use backpropagation to compute the gradient of the loss with respect to the model parameters, and perform gradient descent on the model parameters to minimize the loss.\n\nHere we will do something slightly different. We will start from a convolutional neural network model which has been pretrained to perform image classification on the ImageNet dataset. We will use this model to define a loss function which quantifies our current unhappiness with our image, then use backpropagation to compute the gradient of this loss with respect to the pixels of the image. We will then keep the model fixed, and perform gradient descent *on the image* to synthesize a new image which minimizes the loss.\n\nIn this notebook we will explore three techniques for image generation:\n\n1. **Saliency Maps**: Saliency maps are a quick way to tell which part of the image influenced the classification decision made by the network.\n2. **Fooling Images**: We can perturb an input image so that it appears the same to humans, but will be misclassified by the pretrained network.\n3. **Class Visualization**: We can synthesize an image to maximize the classification score of a particular class; this can give us some sense of what the network is looking for when it classifies images of that class.\n\nThis notebook uses **TensorFlow**; we have provided another notebook which explores the same concepts in PyTorch. You only need to complete one of these two notebooks.", "_____no_output_____" ] ], [ [ "# As usual, a bit of setup\nimport time, os, json\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\nfrom cs231n.classifiers.squeezenet import SqueezeNet\nfrom cs231n.data_utils import load_tiny_imagenet\nfrom cs231n.image_utils import preprocess_image, deprocess_image\nfrom cs231n.image_utils import SQUEEZENET_MEAN, SQUEEZENET_STD\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\ndef get_session():\n \"\"\"Create a session that dynamically allocates memory.\"\"\"\n # See: https://www.tensorflow.org/tutorials/using_gpu#allowing_gpu_memory_growth\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n session = tf.Session(config=config)\n return session\n\n# for auto-reloading external modules\n# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n%load_ext autoreload\n%autoreload 2", "_____no_output_____" ] ], [ [ "# Pretrained Model\n\nFor all of our image generation experiments, we will start with a convolutional neural network which was pretrained to perform image classification on ImageNet. We can use any model here, but for the purposes of this assignment we will use SqueezeNet [1], which achieves accuracies comparable to AlexNet but with a significantly reduced parameter count and computational complexity.\n\nUsing SqueezeNet rather than AlexNet or VGG or ResNet means that we can easily perform all image generation experiments on CPU.\n\nWe have ported the PyTorch SqueezeNet model to TensorFlow; see: `cs231n/classifiers/squeezenet.py` for the model architecture.\n\nTo use SqueezeNet, you will need to first **download the weights** by descending into the `cs231n/datasets` directory and running `get_squeezenet_tf.sh`. Note that if you ran `get_assignment3_data.sh` then SqueezeNet will already be downloaded.\n\nOnce you've downloaded the Squeezenet model, we can load it into a new TensorFlow session:\n\n[1] Iandola et al, \"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and < 0.5MB model size\", arXiv 2016", "_____no_output_____" ] ], [ [ "tf.reset_default_graph()\nsess = get_session()\n\nSAVE_PATH = 'cs231n/datasets/squeezenet.ckpt'\nif not os.path.exists(SAVE_PATH + \".index\"):\n raise ValueError(\"You need to download SqueezeNet!\")\nmodel = SqueezeNet(save_path=SAVE_PATH, sess=sess)", "_____no_output_____" ] ], [ [ "## Load some ImageNet images\nWe have provided a few example images from the validation set of the ImageNet ILSVRC 2012 Classification dataset. To download these images, descend into `cs231n/datasets/` and run `get_imagenet_val.sh`.\n\nSince they come from the validation set, our pretrained model did not see these images during training.\n\nRun the following cell to visualize some of these images, along with their ground-truth labels.", "_____no_output_____" ] ], [ [ "from cs231n.data_utils import load_imagenet_val\nX_raw, y, class_names = load_imagenet_val(num=5)\n\nplt.figure(figsize=(12, 6))\nfor i in range(5):\n plt.subplot(1, 5, i + 1)\n plt.imshow(X_raw[i])\n plt.title(class_names[y[i]])\n plt.axis('off')\nplt.gcf().tight_layout()", "_____no_output_____" ] ], [ [ "## Preprocess images\nThe input to the pretrained model is expected to be normalized, so we first preprocess the images by subtracting the pixelwise mean and dividing by the pixelwise standard deviation.", "_____no_output_____" ] ], [ [ "X = np.array([preprocess_image(img) for img in X_raw])", "_____no_output_____" ] ], [ [ "# Saliency Maps\nUsing this pretrained model, we will compute class saliency maps as described in Section 3.1 of [2].\n\nA **saliency map** tells us the degree to which each pixel in the image affects the classification score for that image. To compute it, we compute the gradient of the unnormalized score corresponding to the correct class (which is a scalar) with respect to the pixels of the image. If the image has shape `(H, W, 3)` then this gradient will also have shape `(H, W, 3)`; for each pixel in the image, this gradient tells us the amount by which the classification score will change if the pixel changes by a small amount. To compute the saliency map, we take the absolute value of this gradient, then take the maximum value over the 3 input channels; the final saliency map thus has shape `(H, W)` and all entries are nonnegative.\n\nYou will need to use the `model.scores` Tensor containing the scores for each input, and will need to feed in values for the `model.image` and `model.labels` placeholder when evaluating the gradient. Open the file `cs231n/classifiers/squeezenet.py` and read the documentation to make sure you understand how to use the model. For example usage, you can see the `loss` attribute. \n\n[2] Karen Simonyan, Andrea Vedaldi, and Andrew Zisserman. \"Deep Inside Convolutional Networks: Visualising\nImage Classification Models and Saliency Maps\", ICLR Workshop 2014.", "_____no_output_____" ] ], [ [ "def compute_saliency_maps(X, y, model):\n \"\"\"\n Compute a class saliency map using the model for images X and labels y.\n\n Input:\n - X: Input images, numpy array of shape (N, H, W, 3)\n - y: Labels for X, numpy of shape (N,)\n - model: A SqueezeNet model that will be used to compute the saliency map.\n\n Returns:\n - saliency: A numpy array of shape (N, H, W) giving the saliency maps for the\n input images.\n \"\"\"\n saliency = None\n # Compute the score of the correct class for each example.\n # This gives a Tensor with shape [N], the number of examples.\n #\n # Note: this is equivalent to scores[np.arange(N), y] we used in NumPy\n # for computing vectorized losses.\n correct_scores = tf.gather_nd(model.scores,\n tf.stack((tf.range(X.shape[0]), model.labels), axis=1))\n ###############################################################################\n # TODO: Produce the saliency maps over a batch of images. #\n # #\n # 1) Compute the “loss” using the correct scores tensor provided for you. #\n # (We'll combine losses across a batch by summing) #\n # 2) Use tf.gradients to compute the gradient of the loss with respect #\n # to the image (accessible via model.image). #\n # 3) Compute the actual value of the gradient by a call to sess.run(). #\n # You will need to feed in values for the placeholders model.image and #\n # model.labels. #\n # 4) Finally, process the returned gradient to compute the saliency map. #\n ###############################################################################\n pass\n ##############################################################################\n # END OF YOUR CODE #\n ##############################################################################\n return saliency", "_____no_output_____" ] ], [ [ "Once you have completed the implementation in the cell above, run the following to visualize some class saliency maps on our example images from the ImageNet validation set:", "_____no_output_____" ] ], [ [ "def show_saliency_maps(X, y, mask):\n mask = np.asarray(mask)\n Xm = X[mask]\n ym = y[mask]\n\n saliency = compute_saliency_maps(Xm, ym, model)\n\n for i in range(mask.size):\n plt.subplot(2, mask.size, i + 1)\n plt.imshow(deprocess_image(Xm[i]))\n plt.axis('off')\n plt.title(class_names[ym[i]])\n plt.subplot(2, mask.size, mask.size + i + 1)\n plt.title(mask[i])\n plt.imshow(saliency[i], cmap=plt.cm.hot)\n plt.axis('off')\n plt.gcf().set_size_inches(10, 4)\n plt.show()\n\nmask = np.arange(5)\nshow_saliency_maps(X, y, mask)", "_____no_output_____" ] ], [ [ "# INLINE QUESTION", "_____no_output_____" ], [ "A friend of yours suggests that in order to find an image that maximizes the correct score, we can perform gradient ascent on the input image, but instead of the gradient we can actually use the saliency map in each step to update the image. Is this assertion true? Why or why not?", "_____no_output_____" ], [ "# Fooling Images\nWe can also use image gradients to generate \"fooling images\" as discussed in [3]. Given an image and a target class, we can perform gradient **ascent** over the image to maximize the target class, stopping when the network classifies the image as the target class. Implement the following function to generate fooling images.\n\n[3] Szegedy et al, \"Intriguing properties of neural networks\", ICLR 2014", "_____no_output_____" ] ], [ [ "def make_fooling_image(X, target_y, model):\n \"\"\"\n Generate a fooling image that is close to X, but that the model classifies\n as target_y.\n\n Inputs:\n - X: Input image, a numpy array of shape (1, 224, 224, 3)\n - target_y: An integer in the range [0, 1000)\n - model: Pretrained SqueezeNet model\n\n Returns:\n - X_fooling: An image that is close to X, but that is classifed as target_y\n by the model.\n \"\"\"\n \n # Make a copy of the input that we will modify\n X_fooling = X.copy()\n \n # Step size for the update\n learning_rate = 1\n \n ##############################################################################\n # TODO: Generate a fooling image X_fooling that the model will classify as #\n # the class target_y. Use gradient *ascent* on the target class score, using #\n # the model.scores Tensor to get the class scores for the model.image. #\n # When computing an update step, first normalize the gradient: #\n # dX = learning_rate * g / ||g||_2 #\n # #\n # You should write a training loop, where in each iteration, you make an #\n # update to the input image X_fooling (don't modify X). The loop should #\n # stop when the predicted class for the input is the same as target_y. #\n # #\n # HINT: It's good practice to define your TensorFlow graph operations #\n # outside the loop, and then just make sess.run() calls in each iteration. #\n # #\n # HINT 2: For most examples, you should be able to generate a fooling image #\n # in fewer than 100 iterations of gradient ascent. You can print your #\n # progress over iterations to check your algorithm. #\n ##############################################################################\n pass\n ##############################################################################\n # END OF YOUR CODE #\n ##############################################################################\n return X_fooling", "_____no_output_____" ] ], [ [ "Run the following to generate a fooling image. You should ideally see at first glance no major difference between the original and fooling images, and the network should now make an incorrect prediction on the fooling one. However you should see a bit of random noise if you look at the 10x magnified difference between the original and fooling images. Feel free to change the `idx` variable to explore other images.", "_____no_output_____" ] ], [ [ "idx = 0\nXi = X[idx][None]\ntarget_y = 6\nX_fooling = make_fooling_image(Xi, target_y, model)\n\n# Make sure that X_fooling is classified as y_target\nscores = sess.run(model.scores, {model.image: X_fooling})\nassert scores[0].argmax() == target_y, 'The network is not fooled!'\n\n# Show original image, fooling image, and difference\norig_img = deprocess_image(Xi[0])\nfool_img = deprocess_image(X_fooling[0])\n# Rescale \nplt.subplot(1, 4, 1)\nplt.imshow(orig_img)\nplt.axis('off')\nplt.title(class_names[y[idx]])\nplt.subplot(1, 4, 2)\nplt.imshow(fool_img)\nplt.title(class_names[target_y])\nplt.axis('off')\nplt.subplot(1, 4, 3)\nplt.title('Difference')\nplt.imshow(deprocess_image((Xi-X_fooling)[0]))\nplt.axis('off')\nplt.subplot(1, 4, 4)\nplt.title('Magnified difference (10x)')\nplt.imshow(deprocess_image(10 * (Xi-X_fooling)[0]))\nplt.axis('off')\nplt.gcf().tight_layout()", "_____no_output_____" ] ], [ [ "# Class visualization\nBy starting with a random noise image and performing gradient ascent on a target class, we can generate an image that the network will recognize as the target class. This idea was first presented in [2]; [3] extended this idea by suggesting several regularization techniques that can improve the quality of the generated image.\n\nConcretely, let $I$ be an image and let $y$ be a target class. Let $s_y(I)$ be the score that a convolutional network assigns to the image $I$ for class $y$; note that these are raw unnormalized scores, not class probabilities. We wish to generate an image $I^*$ that achieves a high score for the class $y$ by solving the problem\n\n$$\nI^* = {\\arg\\max}_I (s_y(I) - R(I))\n$$\n\nwhere $R$ is a (possibly implicit) regularizer (note the sign of $R(I)$ in the argmax: we want to minimize this regularization term). We can solve this optimization problem using gradient ascent, computing gradients with respect to the generated image. We will use (explicit) L2 regularization of the form\n\n$$\nR(I) = \\lambda \\|I\\|_2^2\n$$\n\n**and** implicit regularization as suggested by [3] by periodically blurring the generated image. We can solve this problem using gradient ascent on the generated image.\n\nIn the cell below, complete the implementation of the `create_class_visualization` function.\n\n[2] Karen Simonyan, Andrea Vedaldi, and Andrew Zisserman. \"Deep Inside Convolutional Networks: Visualising\nImage Classification Models and Saliency Maps\", ICLR Workshop 2014.\n\n[3] Yosinski et al, \"Understanding Neural Networks Through Deep Visualization\", ICML 2015 Deep Learning Workshop", "_____no_output_____" ] ], [ [ "from scipy.ndimage.filters import gaussian_filter1d\ndef blur_image(X, sigma=1):\n X = gaussian_filter1d(X, sigma, axis=1)\n X = gaussian_filter1d(X, sigma, axis=2)\n return X", "_____no_output_____" ], [ "def create_class_visualization(target_y, model, **kwargs):\n \"\"\"\n Generate an image to maximize the score of target_y under a pretrained model.\n \n Inputs:\n - target_y: Integer in the range [0, 1000) giving the index of the class\n - model: A pretrained CNN that will be used to generate the image\n \n Keyword arguments:\n - l2_reg: Strength of L2 regularization on the image\n - learning_rate: How big of a step to take\n - num_iterations: How many iterations to use\n - blur_every: How often to blur the image as an implicit regularizer\n - max_jitter: How much to gjitter the image as an implicit regularizer\n - show_every: How often to show the intermediate result\n \"\"\"\n l2_reg = kwargs.pop('l2_reg', 1e-3)\n learning_rate = kwargs.pop('learning_rate', 25)\n num_iterations = kwargs.pop('num_iterations', 100)\n blur_every = kwargs.pop('blur_every', 10)\n max_jitter = kwargs.pop('max_jitter', 16)\n show_every = kwargs.pop('show_every', 25)\n \n # We use a single image of random noise as a starting point\n X = 255 * np.random.rand(224, 224, 3)\n X = preprocess_image(X)[None]\n \n ########################################################################\n # TODO: Compute the loss and the gradient of the loss with respect to #\n # the input image, model.image. We compute these outside the loop so #\n # that we don't have to recompute the gradient graph at each iteration #\n # #\n # Note: loss and grad should be TensorFlow Tensors, not numpy arrays! #\n # #\n # The loss is the score for the target label, target_y. You should #\n # use model.scores to get the scores, and tf.gradients to compute #\n # gradients. Don't forget the (subtracted) L2 regularization term! #\n ########################################################################\n \n loss = None # scalar loss\n grad = None # gradient of loss with respect to model.image, same size as model.image\n pass\n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n\n \n for t in range(num_iterations):\n # Randomly jitter the image a bit; this gives slightly nicer results\n ox, oy = np.random.randint(-max_jitter, max_jitter+1, 2)\n X = np.roll(np.roll(X, ox, 1), oy, 2)\n \n ########################################################################\n # TODO: Use sess to compute the value of the gradient of the score for #\n # class target_y with respect to the pixels of the image, and make a #\n # gradient step on the image using the learning rate. You should use #\n # the grad variable you defined above. #\n # #\n # Be very careful about the signs of elements in your code. #\n ########################################################################\n pass\n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n\n # Undo the jitter\n X = np.roll(np.roll(X, -ox, 1), -oy, 2)\n\n # As a regularizer, clip and periodically blur\n X = np.clip(X, -SQUEEZENET_MEAN/SQUEEZENET_STD, (1.0 - SQUEEZENET_MEAN)/SQUEEZENET_STD)\n if t % blur_every == 0:\n X = blur_image(X, sigma=0.5)\n\n # Periodically show the image\n if t == 0 or (t + 1) % show_every == 0 or t == num_iterations - 1:\n plt.imshow(deprocess_image(X[0]))\n class_name = class_names[target_y]\n plt.title('%s\\nIteration %d / %d' % (class_name, t + 1, num_iterations))\n plt.gcf().set_size_inches(4, 4)\n plt.axis('off')\n plt.show()\n return X", "_____no_output_____" ] ], [ [ "Once you have completed the implementation in the cell above, run the following cell to generate an image of Tarantula:", "_____no_output_____" ] ], [ [ "target_y = 76 # Tarantula\nout = create_class_visualization(target_y, model)", "_____no_output_____" ] ], [ [ "Try out your class visualization on other classes! You should also feel free to play with various hyperparameters to try and improve the quality of the generated image, but this is not required.", "_____no_output_____" ] ], [ [ "target_y = np.random.randint(1000)\n# target_y = 78 # Tick\n# target_y = 187 # Yorkshire Terrier\n# target_y = 683 # Oboe\n# target_y = 366 # Gorilla\n# target_y = 604 # Hourglass\nprint(class_names[target_y])\nX = create_class_visualization(target_y, model)", "_____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" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a50f58649afd31353e3775e2521942d83fea026
1,963
ipynb
Jupyter Notebook
learning_DSM.ipynb
texchi2/DeepSurvivalMachines
b72e3322ae560b3b3ab36d418d895b6f94909fbd
[ "MIT" ]
null
null
null
learning_DSM.ipynb
texchi2/DeepSurvivalMachines
b72e3322ae560b3b3ab36d418d895b6f94909fbd
[ "MIT" ]
1
2021-01-23T04:18:06.000Z
2021-01-23T04:18:06.000Z
learning_DSM.ipynb
texchi2/DeepSurvivalMachines
b72e3322ae560b3b3ab36d418d895b6f94909fbd
[ "MIT" ]
null
null
null
29.298507
239
0.516047
[ [ [ "<a href=\"https://colab.research.google.com/github/texchi2/DeepSurvivalMachines/blob/master/learning_DSM.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "Deep Survival Machines\nhttps://github.com/texchi2/DeepSurvivalMachines", "_____no_output_____" ] ], [ [ "! git clone https://github.com/texchi2/DeepSurvivalMachines.git", "Cloning into 'DeepSurvivalMachines'...\nremote: Enumerating objects: 73, done.\u001b[K\nremote: Counting objects: 100% (73/73), done.\u001b[K\nremote: Compressing objects: 100% (57/57), done.\u001b[K\nremote: Total 352 (delta 41), reused 35 (delta 16), pack-reused 279\u001b[K\nReceiving objects: 100% (352/352), 1.93 MiB | 13.16 MiB/s, done.\nResolving deltas: 100% (190/190), done.\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ] ]
4a50fb6df940cb29d8b834f12f8c6216a9ed3708
147,241
ipynb
Jupyter Notebook
Regression/Linear Models/LassoRegression_Scale_PowerTransformer.ipynb
guptayush179/ds-seed
9345e5d2f8f5fb2cb5d220a7b3a6896a20dca846
[ "Apache-2.0" ]
53
2021-08-28T07:41:49.000Z
2022-03-09T02:20:17.000Z
Regression/Linear Models/LassoRegression_Scale_PowerTransformer.ipynb
Akshar777/ds-seed
131e586f06b3f6ef802fc4d55f626c2bd6a87086
[ "Apache-2.0" ]
142
2021-07-27T07:23:10.000Z
2021-08-25T14:57:24.000Z
Regression/Linear Models/LassoRegression_Scale_PowerTransformer.ipynb
Akshar777/ds-seed
131e586f06b3f6ef802fc4d55f626c2bd6a87086
[ "Apache-2.0" ]
38
2021-07-27T04:54:08.000Z
2021-08-23T02:27:20.000Z
189.012837
78,386
0.874356
[ [ [ "# LassoRegresion with Scale & Power Transformer", "_____no_output_____" ], [ "This Code template is for the regression analysis using Lasso Regression, the feature transformation technique Power Transformer and rescaling technique Scale in a pipeline. Lasso stands for Least Absolute Shrinkage and Selection Operator is a type of linear regression that uses shrinkage.", "_____no_output_____" ], [ "### Required Packages", "_____no_output_____" ] ], [ [ "import warnings\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt \nimport seaborn as se \nfrom sklearn.linear_model import Lasso\nfrom sklearn.model_selection import train_test_split \nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import PowerTransformer\nfrom sklearn.preprocessing import scale\nfrom sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error \nwarnings.filterwarnings('ignore')", "_____no_output_____" ] ], [ [ "### Initialization\n\nFilepath of CSV file", "_____no_output_____" ] ], [ [ "#filepath\nfile_path = \"\"", "_____no_output_____" ] ], [ [ "List of features which are required for model training .", "_____no_output_____" ] ], [ [ "#x_values\nfeatures = []", "_____no_output_____" ] ], [ [ "Target feature for prediction.", "_____no_output_____" ] ], [ [ "#y_value\ntarget = ''", "_____no_output_____" ] ], [ [ "### Data Fetching\n\nPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.\n\nWe will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry.", "_____no_output_____" ] ], [ [ "df=pd.read_csv(file_path)\ndf.head()", "_____no_output_____" ] ], [ [ "### Feature Selections\n\nIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.\n\nWe will assign all the required input features to X and target/outcome to Y.", "_____no_output_____" ] ], [ [ "X=df[features]\nY=df[target]", "_____no_output_____" ] ], [ [ "### Data Preprocessing\n\nSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes.\n", "_____no_output_____" ] ], [ [ "def NullClearner(df):\n if(isinstance(df, pd.Series) and (df.dtype in [\"float64\",\"int64\"])):\n df.fillna(df.mean(),inplace=True)\n return df\n elif(isinstance(df, pd.Series)):\n df.fillna(df.mode()[0],inplace=True)\n return df\n else:return df\ndef EncodeX(df):\n return pd.get_dummies(df)", "_____no_output_____" ] ], [ [ "Calling preprocessing functions on the feature and target set.\n", "_____no_output_____" ] ], [ [ "x=X.columns.to_list()\nfor i in x:\n X[i]=NullClearner(X[i])\nX=EncodeX(X)\nY=NullClearner(Y)\nX.head()", "_____no_output_____" ] ], [ [ "#### Correlation Map\n\nIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns.", "_____no_output_____" ] ], [ [ "f,ax = plt.subplots(figsize=(18, 18))\nmatrix = np.triu(X.corr())\nse.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)\nplt.show()", "_____no_output_____" ] ], [ [ "### Data Splitting\n\nThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of the model on new data.", "_____no_output_____" ] ], [ [ "x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123)", "_____no_output_____" ] ], [ [ "## Data Rescaling\n### Scale: \nStandardize a dataset along any axis.\n\nCenter to the mean and component wise scale to unit variance.\n\nfor more... [click here](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.scale.html)", "_____no_output_____" ] ], [ [ "x_train = scale(x_train)\nx_test = scale(x_test)", "_____no_output_____" ] ], [ [ "### Model\n\nLinear Model trained with L1 prior as regularizer (aka the Lasso)\n\nThe Lasso is a linear model that estimates sparse coefficients. It is useful in some contexts due to its tendency to prefer solutions with fewer non-zero coefficients, effectively reducing the number of features upon which the given solution is dependent. For this reason Lasso and its variants are fundamental to the field of compressed sensing.\n\n#### Model Tuning Parameter\n> **alpha** -> Constant that multiplies the L1 term. Defaults to 1.0. alpha = 0 is equivalent to an ordinary least square, solved by the LinearRegression object. For numerical reasons, using alpha = 0 with the Lasso object is not advised.\n\n> **selection** -> If set to ‘random’, a random coefficient is updated every iteration rather than looping over features sequentially by default. This (setting to ‘random’) often leads to significantly faster convergence especially when tol is higher than 1e-4.\n\n> **tol** -> The tolerance for the optimization: if the updates are smaller than tol, the optimization code checks the dual gap for optimality and continues until it is smaller than tol.\n\n> **max_iter** -> The maximum number of iterations.\n\n\n#### Feature Transformation\nPower Transformers are a family of parametric, monotonic transformations that are applied to make data more Gaussian-like. This is useful for modeling issues related to heteroscedasticity (non-constant variance), or other situations where normality is desired\n\n[More on PowerTransformer module and parameters](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PowerTransformer.html)", "_____no_output_____" ] ], [ [ "model=make_pipeline(PowerTransformer(),Lasso(random_state=123))\nmodel.fit(x_train,y_train)", "_____no_output_____" ] ], [ [ "#### Model Accuracy\n\nWe will use the trained model to make a prediction on the test set.Then use the predicted value for measuring the accuracy of our model.\n\n> **score**: The **score** function returns the coefficient of determination <code>R<sup>2</sup></code> of the prediction.", "_____no_output_____" ] ], [ [ "print(\"Accuracy score {:.2f} %\\n\".format(model.score(x_test,y_test)*100))", "Accuracy score 62.54 %\n\n" ] ], [ [ "> **r2_score**: The **r2_score** function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions. \n\n> **mae**: The **mean abosolute error** function calculates the amount of total error(absolute average distance between the real data and the predicted data) by our model. \n\n> **mse**: The **mean squared error** function squares the error(penalizes the model for large errors) by our model. ", "_____no_output_____" ] ], [ [ "y_pred=model.predict(x_test)\nprint(\"R2 Score: {:.2f} %\".format(r2_score(y_test,y_pred)*100))\nprint(\"Mean Absolute Error {:.2f}\".format(mean_absolute_error(y_test,y_pred)))\nprint(\"Mean Squared Error {:.2f}\".format(mean_squared_error(y_test,y_pred)))", "R2 Score: 62.54 %\nMean Absolute Error 53169.49\nMean Squared Error 4981005659.65\n" ] ], [ [ "#### Prediction Plot\n\nFirst, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis.\nFor the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis.", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(14,10))\nplt.plot(range(20),y_test[0:20], color = \"green\")\nplt.plot(range(20),model.predict(x_test[0:20]), color = \"red\")\nplt.legend([\"Actual\",\"prediction\"]) \nplt.title(\"Predicted vs True Value\")\nplt.xlabel(\"Record number\")\nplt.ylabel(target)\nplt.show()", "_____no_output_____" ] ], [ [ "##### Creator - Vikas Mishra, Github: [Profile](https://github.com/Vikaas08)\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a5116cf5931e6f763c8f17a3d1a0e9dbce63fcf
20,835
ipynb
Jupyter Notebook
LSTM/LSTM - Sentence Input Vector.ipynb
handsonmachinelearning/Tutorials
eb55d63e381e3e8b8eb9e053fc0da101aadc09ea
[ "Apache-2.0" ]
1
2022-01-03T21:35:12.000Z
2022-01-03T21:35:12.000Z
LSTM/LSTM - Sentence Input Vector.ipynb
handsonmachinelearning/Tutorials
eb55d63e381e3e8b8eb9e053fc0da101aadc09ea
[ "Apache-2.0" ]
null
null
null
LSTM/LSTM - Sentence Input Vector.ipynb
handsonmachinelearning/Tutorials
eb55d63e381e3e8b8eb9e053fc0da101aadc09ea
[ "Apache-2.0" ]
1
2022-01-03T21:35:14.000Z
2022-01-03T21:35:14.000Z
35.494037
1,048
0.558435
[ [ [ "#http://colah.github.io/posts/2015-08-Understanding-LSTMs/\n\nfrom collections import Counter\nimport json\nimport nltk\nfrom nltk.corpus import stopwords\nWORD_FREQUENCY_FILE_FULL_PATH = \"analysis.vocab\"", "_____no_output_____" ], [ "class MyVocabulary:\n \n def __init__(self, vocabulary, wordFrequencyFilePath):\n self.vocabulary = vocabulary\n self.WORD_FREQUENCY_FILE_FULL_PATH = wordFrequencyFilePath\n self.input_word_index = {}\n self.reverse_input_word_index = {}\n \n self.input_word_index[\"START\"] = 1\n self.input_word_index[\"UNKOWN\"] = -1\n self.MaxSentenceLength = None\n \n def PrepareVocabulary(self,reviews):\n self._prepare_Word_Frequency_Count_File(reviews)\n self._create_Vocab_Indexes()\n \n self.MaxSentenceLength = max([len(txt.split(\" \")) for txt in reviews])\n \n def Get_Top_Words(self, number_words = None):\n if number_words == None:\n number_words = self.vocabulary\n \n chars = json.loads(open(self.WORD_FREQUENCY_FILE_FULL_PATH).read())\n counter = Counter(chars)\n most_popular_words = {key for key, _value in counter.most_common(number_words)}\n return most_popular_words\n \n def _prepare_Word_Frequency_Count_File(self,reviews):\n counter = Counter() \n for s in reviews:\n counter.update(s.split(\" \"))\n \n with open(self.WORD_FREQUENCY_FILE_FULL_PATH, 'w') as output_file:\n output_file.write(json.dumps(counter))\n \n def _create_Vocab_Indexes(self):\n INPUT_WORDS = self.Get_Top_Words(self.vocabulary)\n\n #word to int\n #self.input_word_index = dict(\n # [(word, i) for i, word in enumerate(INPUT_WORDS)])\n for i, word in enumerate(INPUT_WORDS):\n self.input_word_index[word] = i\n \n #int to word\n #self.reverse_input_word_index = dict(\n # (i, word) for word, i in self.input_word_index.items())\n for word, i in self.input_word_index.items():\n self.reverse_input_word_index[i] = word\n\n #self.input_word_index = input_word_index\n #self.reverse_input_word_index = reverse_input_word_index\n #seralize.dump(config.DATA_FOLDER_PATH+\"input_word_index.p\",input_word_index)\n #seralize.dump(config.DATA_FOLDER_PATH+\"reverse_input_word_index.p\",reverse_input_word_index)\n \n \n def TransformSentencesToId(self, sentences):\n vectors = []\n for r in sentences:\n words = r.split(\" \")\n vector = np.zeros(len(words))\n\n for t, word in enumerate(words):\n if word in self.input_word_index:\n vector[t] = self.input_word_index[word]\n else:\n pass\n #vector[t] = 2 #unk\n vectors.append(vector)\n \n return vectors\n \n def ReverseTransformSentencesToId(self, sentences):\n vectors = []\n for r in sentences:\n words = r.split(\" \")\n vector = np.zeros(len(words))\n\n for t, word in enumerate(words):\n if word in self.input_word_index:\n vector[t] = self.input_word_index[word]\n else:\n pass\n #vector[t] = 2 #unk\n vectors.append(vector)\n \n return vectors\n \n \n ", "_____no_output_____" ], [ "#Download DataSet\n#http://ai.stanford.edu/~amaas/data/sentiment/\n#https://www.liip.ch/en/blog/sentiment-detection-with-keras-word-embeddings-and-lstm-deep-learning-networks\nimport os\n\ndef GetTextFilePathsInDirectory(directory):\n files = []\n for file in os.listdir(directory):\n if file.endswith(\".txt\"):\n filePath = os.path.join(directory, file)\n files.append(filePath)\n return files\n\ndef GetLinesFromTextFile(filePath):\n with open(filePath,\"r\", encoding=\"utf-8\") as f:\n lines = [line.strip() for line in f]\n return lines\n\n\ndef RemoveStopWords(line, stopwords):\n words = []\n for word in line.split(\" \"):\n word = word.strip()\n if word not in stopwords and word != \"\" and word != \"&\":\n words.append(word)\n\n return \" \".join(words)\n\n\nimport re\nREPLACE_NO_SPACE = re.compile(\"(\\.)|(\\;)|(\\:)|(\\!)|(\\')|(\\?)|(\\,)|(\\\")|(\\()|(\\))|(\\[)|(\\])\")\nREPLACE_WITH_SPACE = re.compile(\"(<br\\s*/><br\\s*/>)|(\\-)|(\\/)\")\n\n#https://gist.github.com/aaronkub/257a1bd9215da3a7221148600d849450#file-clean_movie_reviews-py\ndef preprocess_reviews(reviews):\n default_stop_words = nltk.corpus.stopwords.words('english')\n stopwords = set(default_stop_words)\n \n reviews = [REPLACE_NO_SPACE.sub(\"\", line.lower()) for line in reviews]\n reviews = [REPLACE_WITH_SPACE.sub(\" \", line) for line in reviews]\n reviews = [RemoveStopWords(line,stopwords) for line in reviews]\n \n return reviews", "_____no_output_____" ], [ "default_stop_words = nltk.corpus.stopwords.words('english')\nstopwords = set(default_stop_words)\nRemoveStopWords(\"this is a very large test\",stopwords)", "_____no_output_____" ] ], [ [ "<h2>Prepare Data</h2>", "_____no_output_____" ] ], [ [ "positive_files = GetTextFilePathsInDirectory(\"aclImdb/train/pos/\")\nnegative_files = GetTextFilePathsInDirectory(\"aclImdb/train/neg/\")\n\nreviews_positive = []\nfor i in range(0,500):\n reviews_positive.extend(GetLinesFromTextFile(positive_files[i]))\n \nreviews_negative = []\nfor i in range(0,500):\n reviews_negative.extend(GetLinesFromTextFile(negative_files[i]))", "_____no_output_____" ], [ "print(\"Positive Review---> {0}\".format(reviews_positive[5]))\nprint()\nprint(\"Negative Review---> {0}\".format(reviews_negative[5]))\n\nprint()\nreviews_positive = preprocess_reviews(reviews_positive)\nprint(\"Processed Positive Review---> {0}\".format(reviews_positive[5]))\n\nreviews_negative = preprocess_reviews(reviews_negative)\nprint(\"Processed Negative Review---> {0}\".format(reviews_negative[5]))", "Positive Review---> This isn't the comedic Robin Williams, nor is it the quirky/insane Robin Williams of recent thriller fame. This is a hybrid of the classic drama without over-dramatization, mixed with Robin's new love of the thriller. But this isn't a thriller, per se. This is more a mystery/suspense vehicle through which Williams attempts to locate a sick boy and his keeper.<br /><br />Also starring Sandra Oh and Rory Culkin, this Suspense Drama plays pretty much like a news report, until William's character gets close to achieving his goal.<br /><br />I must say that I was highly entertained, though this movie fails to teach, guide, inspect, or amuse. It felt more like I was watching a guy (Williams), as he was actually performing the actions, from a third person perspective. In other words, it felt real, and I was able to subscribe to the premise of the story.<br /><br />All in all, it's worth a watch, though it's definitely not Friday/Saturday night fare.<br /><br />It rates a 7.7/10 from...<br /><br />the Fiend :.\n\nNegative Review---> \"It appears that many critics find the idea of a Woody Allen drama unpalatable.\" And for good reason: they are unbearably wooden and pretentious imitations of Bergman. And let's not kid ourselves: critics were mostly supportive of Allen's Bergman pretensions, Allen's whining accusations to the contrary notwithstanding. What I don't get is this: why was Allen generally applauded for his originality in imitating Bergman, but the contemporaneous Brian DePalma was excoriated for \"ripping off\" Hitchcock in his suspense/horror films? In Robin Wood's view, it's a strange form of cultural snobbery. I would have to agree with that.\n\nProcessed Positive Review---> isnt comedic robin williams quirky insane robin williams recent thriller fame hybrid classic drama without dramatization mixed robins new love thriller isnt thriller per se mystery suspense vehicle williams attempts locate sick boy keeper also starring sandra oh rory culkin suspense drama plays pretty much like news report williams character gets close achieving goal must say highly entertained though movie fails teach guide inspect amuse felt like watching guy williams actually performing actions third person perspective words felt real able subscribe premise story worth watch though definitely friday saturday night fare rates 77 10 fiend\n\nProcessed Negative Review---> appears many critics find idea woody allen drama unpalatable good reason unbearably wooden pretentious imitations bergman lets kid critics mostly supportive allens bergman pretensions allens whining accusations contrary notwithstanding dont get allen generally applauded originality imitating bergman contemporaneous brian depalma excoriated ripping hitchcock suspense horror films robin woods view strange form cultural snobbery would agree\n" ] ], [ [ "<h2>Labeled DataSet</h2>", "_____no_output_____" ] ], [ [ "Reviews_Labeled = list(zip(reviews_positive, np.ones(len(reviews_positive))))\nReviews_Labeled.extend(list(zip(reviews_negative, np.zeros(len(reviews_negative)))))\nReviews_Labeled[10]", "_____no_output_____" ] ], [ [ "<h3>Prepare Vocabulary</h3>", "_____no_output_____" ] ], [ [ "TOP_WORDS = 500\nvocab = MyVocabulary(TOP_WORDS,\"analysis.vocab\")\n\nreviews_text = [line[0] for line in Reviews_Labeled]\nvocab.PrepareVocabulary(reviews_text)\n\n#vocab.Get_Top_Words(10)\n\nvocab.input_word_index[\"START\"]\n#vocab.input_word_index[\"UNKOWN\"]\n#vocab.input_word_index", "_____no_output_____" ] ], [ [ "<h2>Integer Encode Words</h2>", "_____no_output_____" ] ], [ [ "reviews,labels=zip(*Reviews_Labeled)\nreviews_int = vocab.TransformSentencesToId(reviews)\n\nReviews_Labeled_Int = list(zip(reviews_int,labels))\n#print(len(Reviews_Labeled_Int))\nprint(Reviews_Labeled_Int[5])", "(array([354., 0., 0., 418., 0., 0., 0., 418., 0., 0., 0.,\n 0., 393., 269., 344., 0., 0., 0., 179., 171., 0., 354.,\n 0., 0., 0., 0., 0., 0., 418., 0., 0., 0., 396.,\n 0., 491., 0., 0., 496., 0., 0., 0., 269., 360., 62.,\n 475., 338., 0., 0., 418., 51., 197., 215., 0., 0., 431.,\n 428., 1., 0., 433., 423., 0., 0., 0., 0., 0., 268.,\n 338., 424., 427., 418., 299., 0., 0., 0., 21., 0., 0.,\n 268., 304., 454., 0., 0., 307., 82., 144., 433., 348., 0.,\n 0., 298., 0., 0., 0., 165., 0.]), 1.0)\n" ] ], [ [ "<h2>Split Train and Test </h2>", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split\ntrain, test = train_test_split(Reviews_Labeled_Int, test_size=0.2)", "_____no_output_____" ] ], [ [ "<h3>Pad Sentences</h3>", "_____no_output_____" ] ], [ [ "X_train, y_train = list(zip(*train))\nX_test, y_test = list(zip(*test))\n\ny_train = np.array(y_train)\ny_test = np.array(y_test)\n\n#max_review_length = vocab.MaxSentenceLength\nmax_review_length = 500\n\n# Truncate and pad the review sequences \nfrom keras.preprocessing import sequence \nmax_review_length = 500 \nX_train = sequence.pad_sequences(X_train, maxlen=max_review_length) \nX_test = sequence.pad_sequences(X_test, maxlen=max_review_length) ", "_____no_output_____" ], [ "print(type(X_train))\nprint(type(X_test))\n\nprint(X_train.shape)\nprint(X_test.shape)\n\nprint(type(y_train))\nprint(type(y_test))\n\nprint(y_train.shape)\nprint(y_test.shape)", "<class 'numpy.ndarray'>\n<class 'numpy.ndarray'>\n(800, 500)\n(200, 500)\n<class 'numpy.ndarray'>\n<class 'numpy.ndarray'>\n(800,)\n(200,)\n" ] ], [ [ "<h2>Model</h2>", "_____no_output_____" ] ], [ [ "from keras.models import Sequential\nfrom keras.layers import Dense, Activation, Embedding, LSTM\nimport keras \n\n# create the model\nembedding_vecor_length = 32\nmodel = Sequential()\nmodel.add(Embedding(TOP_WORDS, embedding_vecor_length, input_length=max_review_length))\nmodel.add(LSTM(100))\nmodel.add(Dense(1, activation='sigmoid'))\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nprint(model.summary())", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_11 (Embedding) (None, 500, 32) 16000 \n_________________________________________________________________\nlstm_11 (LSTM) (None, 100) 53200 \n_________________________________________________________________\ndense_11 (Dense) (None, 1) 101 \n=================================================================\nTotal params: 69,301\nTrainable params: 69,301\nNon-trainable params: 0\n_________________________________________________________________\nNone\n" ], [ "model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=3, batch_size=64)", "Train on 800 samples, validate on 200 samples\nEpoch 1/3\n800/800 [==============================] - 10s 13ms/step - loss: 0.6930 - acc: 0.4950 - val_loss: 0.6927 - val_acc: 0.4750\nEpoch 2/3\n800/800 [==============================] - 7s 9ms/step - loss: 0.6895 - acc: 0.6275 - val_loss: 0.6884 - val_acc: 0.6400\nEpoch 3/3\n800/800 [==============================] - 7s 9ms/step - loss: 0.6793 - acc: 0.7037 - val_loss: 0.6622 - val_acc: 0.5100\n" ], [ "TOP_WORDS", "_____no_output_____" ], [ "w = [\"a\",\"b\",\"c\"]\n\nfor i,w in enumerate(w):\n print(i+2)", "2\n3\n4\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
4a511dacc4c572e6738bf373661e38e360680577
32,815
ipynb
Jupyter Notebook
site/en/tutorials/keras/classification.ipynb
veeps/docs
20e6b9807038fcf3e9fb162bec0f5cacfcc7974f
[ "Apache-2.0" ]
1
2020-02-29T18:06:15.000Z
2020-02-29T18:06:15.000Z
site/en/tutorials/keras/classification.ipynb
veeps/docs
20e6b9807038fcf3e9fb162bec0f5cacfcc7974f
[ "Apache-2.0" ]
null
null
null
site/en/tutorials/keras/classification.ipynb
veeps/docs
20e6b9807038fcf3e9fb162bec0f5cacfcc7974f
[ "Apache-2.0" ]
null
null
null
31.522574
468
0.51446
[ [ [ "##### Copyright 2018 The TensorFlow Authors.", "_____no_output_____" ] ], [ [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.", "_____no_output_____" ], [ "#@title MIT License\n#\n# Copyright (c) 2017 François Chollet\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.", "_____no_output_____" ] ], [ [ "# Basic classification: Classify images of clothing", "_____no_output_____" ], [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/keras/classification\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/keras/classification.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/tutorials/keras/classification.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/keras/classification.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>", "_____no_output_____" ], [ "This guide trains a neural network model to classify images of clothing, like sneakers and shirts. It's okay if you don't understand all the details; this is a fast-paced overview of a complete TensorFlow program with the details explained as you go.\n\nThis guide uses [tf.keras](https://www.tensorflow.org/guide/keras), a high-level API to build and train models in TensorFlow.", "_____no_output_____" ] ], [ [ "try:\n # %tensorflow_version only exists in Colab.\n %tensorflow_version 2.x\nexcept Exception:\n pass\n", "_____no_output_____" ], [ "from __future__ import absolute_import, division, print_function, unicode_literals\n\n# TensorFlow and tf.keras\nimport tensorflow as tf\nfrom tensorflow import keras\n\n# Helper libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nprint(tf.__version__)", "_____no_output_____" ] ], [ [ "## Import the Fashion MNIST dataset", "_____no_output_____" ], [ "This guide uses the [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist) dataset which contains 70,000 grayscale images in 10 categories. The images show individual articles of clothing at low resolution (28 by 28 pixels), as seen here:\n\n<table>\n <tr><td>\n <img src=\"https://tensorflow.org/images/fashion-mnist-sprite.png\"\n alt=\"Fashion MNIST sprite\" width=\"600\">\n </td></tr>\n <tr><td align=\"center\">\n <b>Figure 1.</b> <a href=\"https://github.com/zalandoresearch/fashion-mnist\">Fashion-MNIST samples</a> (by Zalando, MIT License).<br/>&nbsp;\n </td></tr>\n</table>\n\nFashion MNIST is intended as a drop-in replacement for the classic [MNIST](http://yann.lecun.com/exdb/mnist/) dataset—often used as the \"Hello, World\" of machine learning programs for computer vision. The MNIST dataset contains images of handwritten digits (0, 1, 2, etc.) in a format identical to that of the articles of clothing you'll use here.\n\nThis guide uses Fashion MNIST for variety, and because it's a slightly more challenging problem than regular MNIST. Both datasets are relatively small and are used to verify that an algorithm works as expected. They're good starting points to test and debug code.\n\nHere, 60,000 images are used to train the network and 10,000 images to evaluate how accurately the network learned to classify images. You can access the Fashion MNIST directly from TensorFlow. Import and load the Fashion MNIST data directly from TensorFlow:", "_____no_output_____" ] ], [ [ "fashion_mnist = keras.datasets.fashion_mnist\n\n(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()", "_____no_output_____" ] ], [ [ "Loading the dataset returns four NumPy arrays:\n\n* The `train_images` and `train_labels` arrays are the *training set*—the data the model uses to learn.\n* The model is tested against the *test set*, the `test_images`, and `test_labels` arrays.\n\nThe images are 28x28 NumPy arrays, with pixel values ranging from 0 to 255. The *labels* are an array of integers, ranging from 0 to 9. These correspond to the *class* of clothing the image represents:\n\n<table>\n <tr>\n <th>Label</th>\n <th>Class</th>\n </tr>\n <tr>\n <td>0</td>\n <td>T-shirt/top</td>\n </tr>\n <tr>\n <td>1</td>\n <td>Trouser</td>\n </tr>\n <tr>\n <td>2</td>\n <td>Pullover</td>\n </tr>\n <tr>\n <td>3</td>\n <td>Dress</td>\n </tr>\n <tr>\n <td>4</td>\n <td>Coat</td>\n </tr>\n <tr>\n <td>5</td>\n <td>Sandal</td>\n </tr>\n <tr>\n <td>6</td>\n <td>Shirt</td>\n </tr>\n <tr>\n <td>7</td>\n <td>Sneaker</td>\n </tr>\n <tr>\n <td>8</td>\n <td>Bag</td>\n </tr>\n <tr>\n <td>9</td>\n <td>Ankle boot</td>\n </tr>\n</table>\n\nEach image is mapped to a single label. Since the *class names* are not included with the dataset, store them here to use later when plotting the images:", "_____no_output_____" ] ], [ [ "class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',\n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']", "_____no_output_____" ] ], [ [ "## Explore the data\n\nLet's explore the format of the dataset before training the model. The following shows there are 60,000 images in the training set, with each image represented as 28 x 28 pixels:", "_____no_output_____" ] ], [ [ "train_images.shape", "_____no_output_____" ] ], [ [ "Likewise, there are 60,000 labels in the training set:", "_____no_output_____" ] ], [ [ "len(train_labels)", "_____no_output_____" ] ], [ [ "Each label is an integer between 0 and 9:", "_____no_output_____" ] ], [ [ "train_labels", "_____no_output_____" ] ], [ [ "There are 10,000 images in the test set. Again, each image is represented as 28 x 28 pixels:", "_____no_output_____" ] ], [ [ "test_images.shape", "_____no_output_____" ] ], [ [ "And the test set contains 10,000 images labels:", "_____no_output_____" ] ], [ [ "len(test_labels)", "_____no_output_____" ] ], [ [ "## Preprocess the data\n\nThe data must be preprocessed before training the network. If you inspect the first image in the training set, you will see that the pixel values fall in the range of 0 to 255:", "_____no_output_____" ] ], [ [ "plt.figure()\nplt.imshow(train_images[0])\nplt.colorbar()\nplt.grid(False)\nplt.show()", "_____no_output_____" ] ], [ [ "Scale these values to a range of 0 to 1 before feeding them to the neural network model. To do so, divide the values by 255. It's important that the *training set* and the *testing set* be preprocessed in the same way:", "_____no_output_____" ] ], [ [ "train_images = train_images / 255.0\n\ntest_images = test_images / 255.0", "_____no_output_____" ] ], [ [ "To verify that the data is in the correct format and that you're ready to build and train the network, let's display the first 25 images from the *training set* and display the class name below each image.", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(10,10))\nfor i in range(25):\n plt.subplot(5,5,i+1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(train_images[i], cmap=plt.cm.binary)\n plt.xlabel(class_names[train_labels[i]])\nplt.show()", "_____no_output_____" ] ], [ [ "## Build the model\n\nBuilding the neural network requires configuring the layers of the model, then compiling the model.", "_____no_output_____" ], [ "### Set up the layers\n\nThe basic building block of a neural network is the *layer*. Layers extract representations from the data fed into them. Hopefully, these representations are meaningful for the problem at hand.\n\nMost of deep learning consists of chaining together simple layers. Most layers, such as `tf.keras.layers.Dense`, have parameters that are learned during training.", "_____no_output_____" ] ], [ [ "model = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation='relu'),\n keras.layers.Dense(10)\n])", "_____no_output_____" ] ], [ [ "The first layer in this network, `tf.keras.layers.Flatten`, transforms the format of the images from a two-dimensional array (of 28 by 28 pixels) to a one-dimensional array (of 28 * 28 = 784 pixels). Think of this layer as unstacking rows of pixels in the image and lining them up. This layer has no parameters to learn; it only reformats the data.\n\nAfter the pixels are flattened, the network consists of a sequence of two `tf.keras.layers.Dense` layers. These are densely connected, or fully connected, neural layers. The first `Dense` layer has 128 nodes (or neurons). The second (and last) layer is a 10-node *softmax* layer that returns an array of 10 probability scores that sum to 1. Each node contains a score that indicates the probability that the current image belongs to one of the 10 classes.\n\n### Compile the model\n\nBefore the model is ready for training, it needs a few more settings. These are added during the model's *compile* step:\n\n* *Loss function* —This measures how accurate the model is during training. You want to minimize this function to \"steer\" the model in the right direction.\n* *Optimizer* —This is how the model is updated based on the data it sees and its loss function.\n* *Metrics* —Used to monitor the training and testing steps. The following example uses *accuracy*, the fraction of the images that are correctly classified.", "_____no_output_____" ] ], [ [ "model.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])", "_____no_output_____" ] ], [ [ "## Train the model\n\nTraining the neural network model requires the following steps:\n\n1. Feed the training data to the model. In this example, the training data is in the `train_images` and `train_labels` arrays.\n2. The model learns to associate images and labels.\n3. You ask the model to make predictions about a test set—in this example, the `test_images` array.\n4. Verify that the predictions match the labels from the `test_labels` array.\n\n", "_____no_output_____" ], [ "### Feed the model\n\nTo start training, call the `model.fit` method—so called because it \"fits\" the model to the training data:", "_____no_output_____" ] ], [ [ "model.fit(train_images, train_labels, epochs=10)", "_____no_output_____" ] ], [ [ "As the model trains, the loss and accuracy metrics are displayed. This model reaches an accuracy of about 0.91 (or 91%) on the training data.", "_____no_output_____" ], [ "### Evaluate accuracy\n\nNext, compare how the model performs on the test dataset:", "_____no_output_____" ] ], [ [ "test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\n\nprint('\\nTest accuracy:', test_acc)", "_____no_output_____" ] ], [ [ "It turns out that the accuracy on the test dataset is a little less than the accuracy on the training dataset. This gap between training accuracy and test accuracy represents *overfitting*. Overfitting is when a machine learning model performs worse on new, previously unseen inputs than on the training data. An overfitted model \"memorizes\" the training data—with less accuracy on testing data. For more information, see the following:\n* [Demonstrate overfitting](https://www.tensorflow.org/tutorials/keras/overfit_and_underfit#demonstrate_overfitting)\n* [Strategies to prevent overfitting](https://www.tensorflow.org/tutorials/keras/overfit_and_underfit#strategies_to_prevent_overfitting)", "_____no_output_____" ], [ "### Make predictions\n\nWith the model trained, you can use it to make predictions about some images.", "_____no_output_____" ] ], [ [ "predictions = model.predict(test_images)", "_____no_output_____" ] ], [ [ "Here, the model has predicted the label for each image in the testing set. Let's take a look at the first prediction:", "_____no_output_____" ] ], [ [ "predictions[0]", "_____no_output_____" ] ], [ [ "A prediction is an array of 10 numbers. They represent the model's \"confidence\" that the image corresponds to each of the 10 different articles of clothing. You can see which label has the highest confidence value:", "_____no_output_____" ] ], [ [ "np.argmax(predictions[0])", "_____no_output_____" ] ], [ [ "So, the model is most confident that this image is an ankle boot, or `class_names[9]`. Examining the test label shows that this classification is correct:", "_____no_output_____" ] ], [ [ "test_labels[0]", "_____no_output_____" ] ], [ [ "Graph this to look at the full set of 10 class predictions.", "_____no_output_____" ] ], [ [ "def plot_image(i, predictions_array, true_label, img):\n predictions_array, true_label, img = predictions_array, true_label[i], img[i]\n plt.grid(False)\n plt.xticks([])\n plt.yticks([])\n\n plt.imshow(img, cmap=plt.cm.binary)\n\n predicted_label = np.argmax(predictions_array)\n if predicted_label == true_label:\n color = 'blue'\n else:\n color = 'red'\n\n plt.xlabel(\"{} {:2.0f}% ({})\".format(class_names[predicted_label],\n 100*np.max(predictions_array),\n class_names[true_label]),\n color=color)\n\ndef plot_value_array(i, predictions_array, true_label):\n predictions_array, true_label = predictions_array, true_label[i]\n plt.grid(False)\n plt.xticks(range(10))\n plt.yticks([])\n thisplot = plt.bar(range(10), predictions_array, color=\"#777777\")\n plt.ylim([0, 1])\n predicted_label = np.argmax(predictions_array)\n\n thisplot[predicted_label].set_color('red')\n thisplot[true_label].set_color('blue')", "_____no_output_____" ] ], [ [ "### Verify predictions\n\nWith the model trained, you can use it to make predictions about some images.", "_____no_output_____" ], [ "Let's look at the 0th image, predictions, and prediction array. Correct prediction labels are blue and incorrect prediction labels are red. The number gives the percentage (out of 100) for the predicted label.", "_____no_output_____" ] ], [ [ "i = 0\nplt.figure(figsize=(6,3))\nplt.subplot(1,2,1)\nplot_image(i, predictions[i], test_labels, test_images)\nplt.subplot(1,2,2)\nplot_value_array(i, predictions[i], test_labels)\nplt.show()", "_____no_output_____" ], [ "i = 12\nplt.figure(figsize=(6,3))\nplt.subplot(1,2,1)\nplot_image(i, predictions[i], test_labels, test_images)\nplt.subplot(1,2,2)\nplot_value_array(i, predictions[i], test_labels)\nplt.show()", "_____no_output_____" ] ], [ [ "Let's plot several images with their predictions. Note that the model can be wrong even when very confident.", "_____no_output_____" ] ], [ [ "# Plot the first X test images, their predicted labels, and the true labels.\n# Color correct predictions in blue and incorrect predictions in red.\nnum_rows = 5\nnum_cols = 3\nnum_images = num_rows*num_cols\nplt.figure(figsize=(2*2*num_cols, 2*num_rows))\nfor i in range(num_images):\n plt.subplot(num_rows, 2*num_cols, 2*i+1)\n plot_image(i, predictions[i], test_labels, test_images)\n plt.subplot(num_rows, 2*num_cols, 2*i+2)\n plot_value_array(i, predictions[i], test_labels)\nplt.tight_layout()\nplt.show()", "_____no_output_____" ] ], [ [ "## Use the trained model\n\nFinally, use the trained model to make a prediction about a single image.", "_____no_output_____" ] ], [ [ "# Grab an image from the test dataset.\nimg = test_images[1]\n\nprint(img.shape)", "_____no_output_____" ] ], [ [ "`tf.keras` models are optimized to make predictions on a *batch*, or collection, of examples at once. Accordingly, even though you're using a single image, you need to add it to a list:", "_____no_output_____" ] ], [ [ "# Add the image to a batch where it's the only member.\nimg = (np.expand_dims(img,0))\n\nprint(img.shape)", "_____no_output_____" ] ], [ [ "Now predict the correct label for this image:", "_____no_output_____" ] ], [ [ "predictions_single = model.predict(img)\n\nprint(predictions_single)", "_____no_output_____" ], [ "plot_value_array(1, predictions_single[0], test_labels)\n_ = plt.xticks(range(10), class_names, rotation=45)", "_____no_output_____" ] ], [ [ "`model.predict` returns a list of lists—one list for each image in the batch of data. Grab the predictions for our (only) image in the batch:", "_____no_output_____" ] ], [ [ "np.argmax(predictions_single[0])", "_____no_output_____" ] ], [ [ "And the model predicts a label as expected.", "_____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" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "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" ], [ "markdown" ] ]
4a511df441546120f97db94862511cd15680f991
7,084
ipynb
Jupyter Notebook
max_level.ipynb
twitterdev/JSON-to-CSV-livestream
39b1b2258b815a2559cfb63aace4223af76815eb
[ "Apache-2.0" ]
2
2021-05-07T16:10:57.000Z
2021-05-11T23:46:48.000Z
max_level.ipynb
twitterdev/JSON-to-CSV-livestream
39b1b2258b815a2559cfb63aace4223af76815eb
[ "Apache-2.0" ]
null
null
null
max_level.ipynb
twitterdev/JSON-to-CSV-livestream
39b1b2258b815a2559cfb63aace4223af76815eb
[ "Apache-2.0" ]
null
null
null
31.625
110
0.377612
[ [ [ "import pandas as pd\nimport requests\nimport os", "_____no_output_____" ], [ "bearer_token = os.environ.get('BEARER_TOKEN')\nheaders = {\"Authorization\": \"Bearer {}\".format(bearer_token)}", "_____no_output_____" ], [ "url = \"https://api.twitter.com/2/tweets/search/recent\"\nparams = {\"query\":\"from:TwitterDev\", \"tweet.fields\":\"public_metrics\", \"max_results\":\"15\"}\nresponse = requests.request(\"GET\", url, headers=headers, params=params).json()", "_____no_output_____" ], [ "data = response['data']\nnormalized = pd.json_normalize(data, max_level=3)", "_____no_output_____" ], [ "normalized", "_____no_output_____" ], [ "normalized.to_csv('normalized.csv')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
4a511e511c79cd252c8cb8a60830f5534bb5fa7a
64,096
ipynb
Jupyter Notebook
DEEP LEARNING/Autoencoders GANS/fastai/fastai gan super resolution.ipynb
Diyago/ML-DL-scripts
40718a9d4318d6d6531bcea5998c0a18afcd9cb3
[ "Apache-2.0" ]
142
2018-09-02T08:59:45.000Z
2022-03-30T17:08:24.000Z
DEEP LEARNING/Autoencoders GANS/fastai/fastai gan super resolution.ipynb
jerinka/ML-DL-scripts
eeb5c3c7c5841eb4cdb272690e14d6718f3685b2
[ "Apache-2.0" ]
4
2019-09-08T07:27:11.000Z
2021-10-19T05:50:24.000Z
DEEP LEARNING/Autoencoders GANS/fastai/fastai gan super resolution.ipynb
jerinka/ML-DL-scripts
eeb5c3c7c5841eb4cdb272690e14d6718f3685b2
[ "Apache-2.0" ]
75
2018-10-04T17:08:40.000Z
2022-03-08T18:50:52.000Z
64.808898
738
0.648933
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4a5121fd3f149bb681726dd931ae0ddbf43fa1ea
1,202
ipynb
Jupyter Notebook
02_Further_into_Python_Assignments/A_06_File_Operations_en.ipynb
serhanoner/data_science
0896ffc9fd4514f5b30dc98fe51e532604fda807
[ "Apache-2.0" ]
1
2022-01-29T14:45:28.000Z
2022-01-29T14:45:28.000Z
02_Further_into_Python_Assignments/A_06_File_Operations_en.ipynb
serhanoner/data_science
0896ffc9fd4514f5b30dc98fe51e532604fda807
[ "Apache-2.0" ]
null
null
null
02_Further_into_Python_Assignments/A_06_File_Operations_en.ipynb
serhanoner/data_science
0896ffc9fd4514f5b30dc98fe51e532604fda807
[ "Apache-2.0" ]
null
null
null
17.676471
86
0.50416
[ [ [ "**(1)** Please write a poem you wanted in a `.txt` file and save it to the disk.", "_____no_output_____" ], [ "**(2)** Append a new poem into the file you have created.", "_____no_output_____" ], [ "**(3)** Read and print all poems.", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown" ] ]
4a513da5918526a5be6555630d0bc6d477d1e150
60,896
ipynb
Jupyter Notebook
ex4_mnist_digits_recognition.ipynb
qyangaa/cv_tutorial_in_jupyter_notebook
704a980ff585c3f8dbe2fa28668415a610cdac18
[ "MIT" ]
null
null
null
ex4_mnist_digits_recognition.ipynb
qyangaa/cv_tutorial_in_jupyter_notebook
704a980ff585c3f8dbe2fa28668415a610cdac18
[ "MIT" ]
null
null
null
ex4_mnist_digits_recognition.ipynb
qyangaa/cv_tutorial_in_jupyter_notebook
704a980ff585c3f8dbe2fa28668415a610cdac18
[ "MIT" ]
null
null
null
76.215269
26,312
0.715942
[ [ [ "import torch\nfrom torch import nn\nimport torchvision\nfrom torchvision import datasets, transforms", "_____no_output_____" ] ], [ [ "# Load data", "_____no_output_____" ] ], [ [ "batch_size = 32\ntrain_transforms = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize([0.131],[0.308])])\ntest_transforms = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize([0.131],[0.308])])\ntrain_data = datasets.MNIST('./data/mnist',\n train = True,\n transform = train_transforms,\n download=True)\ntest_data = datasets.MNIST('./data/mnist',\n train = False,\n transform = test_transforms,\n download=True)\n\ntrain_loader = torch.utils.data.DataLoader(train_data,\n batch_size = batch_size,\n shuffle = True)\n\n#no need to shuffle for tests\ntest_loader = torch.utils.data.DataLoader(train_data,\n batch_size = batch_size,\n shuffle = False)\n", "Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to ./data/mnist/MNIST/raw/train-images-idx3-ubyte.gz\n" ] ], [ [ "# Data exploration", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport numpy as np\n%matplotlib inline\ninputs, labels = next(iter(train_loader))\nprint(inputs.shape, labels.shape)\n#32 samples per batch, each of 28*28 pixels, with 1 color channel\ninputs[0]", "torch.Size([32, 1, 28, 28]) torch.Size([32])\n" ], [ "def imshow(img):\n img = img.numpy().transpose((1,2,0))\n img = img*0.308+0.131\n img = np.clip(img,0,1)\n plt.imshow(img)\nout = torchvision.utils.make_grid(inputs)\nimshow(out)", "_____no_output_____" ] ], [ [ "# Model", "_____no_output_____" ] ], [ [ "class Linear_classifier(nn.Module):\n def __init__(self,layers=[512,128],input_size = 784,out_channels=10):\n super().__init__()\n layers = [input_size]+layers\n layers.append(out_channels)\n L = []\n for i in range(1,len(layers)):\n L.append(nn.Linear(layers[i-1],layers[i]))\n L.append(nn.ReLU())\n L.append(nn.Softmax())\n self.network = nn.Sequential(*L)\n \n def forward(self,x):\n x = x.view(-1,28*28)\n x = self.network(x)\n return x\n\n\n ", "Linear_classifier(\n (network): Sequential(\n (0): Linear(in_features=784, out_features=512, bias=True)\n (1): ReLU()\n (2): Linear(in_features=512, out_features=128, bias=True)\n (3): ReLU()\n (4): Linear(in_features=128, out_features=10, bias=True)\n (5): ReLU()\n (6): Softmax(dim=None)\n )\n)\n" ] ], [ [ "# Training", "_____no_output_____" ] ], [ [ "def train(lr=1e-3,epochs=20,mode='SGD'):\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model = Linear_classifier().to(device)\n print(model)\n print('lr: {}, epochs: {}'.format(lr, epochs))\n if mode=='SGD':\n optimizer = torch.optim.SGD(model.parameters(),lr = lr)\n else:\n optimizer = torch.optim.Adam(model.parameters(),lr = lr)\n criteria = nn.CrossEntropyLoss()\n import time\n\n for i in range(epochs):\n start_time = time.time()\n running_loss = 0.0\n for inputs, labels in train_loader:\n optimizer.zero_grad()\n outputs = model(inputs)\n loss = criteria(outputs,labels)\n loss.backward()\n optimizer.step()\n running_loss = running_loss+loss.item()\n running_loss = running_loss/len(train_loader)\n cur_time = time.time()\n print('Epoch: {}, loss: {}, time: {}'.format(i, running_loss,cur_time-start_time))\n start_time = cur_time\n \n #test\n correct = 0\n total = 0\n with torch.no_grad():\n for inputs, labels in train_loader:\n outputs = model(inputs)\n loss = criteria(outputs,labels)\n _, predicted = torch.max(outputs.data,1)\n total+=labels.size(0)\n correct+=(predicted==labels).sum().item()\n accuracy = 100.0*correct/total\n\n print(\"accuracy is {} percentage\".format(accuracy))\n return model", "_____no_output_____" ] ], [ [ "# Test", "_____no_output_____" ] ], [ [ "model1 = train(lr=0.03,epochs=20)", "Linear_classifier(\n (network): Sequential(\n (0): Linear(in_features=784, out_features=512, bias=True)\n (1): ReLU()\n (2): Linear(in_features=512, out_features=128, bias=True)\n (3): ReLU()\n (4): Linear(in_features=128, out_features=10, bias=True)\n (5): ReLU()\n (6): Softmax(dim=None)\n )\n)\nlr: 0.03, epochs: 20\nEpoch: 0, loss: 1.8653203535715739, time: 24.240259170532227\nEpoch: 1, loss: 1.7121058294932048, time: 24.04960012435913\nEpoch: 2, loss: 1.7005050527572632, time: 24.025945901870728\nEpoch: 3, loss: 1.6929047777811685, time: 24.204917192459106\nEpoch: 4, loss: 1.6871904738108316, time: 24.40277075767517\nEpoch: 5, loss: 1.6827733764648438, time: 23.927614212036133\nEpoch: 6, loss: 1.6789499739329021, time: 23.402230978012085\nEpoch: 7, loss: 1.6443322028477987, time: 23.324887990951538\nEpoch: 8, loss: 1.5912256618499756, time: 24.462833166122437\nEpoch: 9, loss: 1.5860878664016724, time: 24.474854946136475\nEpoch: 10, loss: 1.5826284267425537, time: 24.25729775428772\nEpoch: 11, loss: 1.579831836636861, time: 24.43934392929077\nEpoch: 12, loss: 1.5777186856587728, time: 24.282562017440796\nEpoch: 13, loss: 1.575645426940918, time: 24.353923082351685\nEpoch: 14, loss: 1.573247243944804, time: 24.26136302947998\nEpoch: 15, loss: 1.5668233373006184, time: 24.30819797515869\nEpoch: 16, loss: 1.563784584935506, time: 24.254648208618164\nEpoch: 17, loss: 1.5619224407831829, time: 24.27418279647827\nEpoch: 18, loss: 1.5605236742655437, time: 24.3195161819458\nEpoch: 19, loss: 1.55921228834788, time: 24.25277590751648\naccuracy is 89.29666666666667 percentage\n" ], [ "model2 = train(lr=0.05,epochs=20)", "Linear_classifier(\n (network): Sequential(\n (0): Linear(in_features=784, out_features=512, bias=True)\n (1): ReLU()\n (2): Linear(in_features=512, out_features=128, bias=True)\n (3): ReLU()\n (4): Linear(in_features=128, out_features=10, bias=True)\n (5): ReLU()\n (6): Softmax(dim=None)\n )\n)\nlr: 0.05, epochs: 20\nEpoch: 0, loss: 1.9550402484258016, time: 24.40858817100525\nEpoch: 1, loss: 1.85327001508077, time: 24.220336198806763\nEpoch: 2, loss: 1.838732870165507, time: 24.288219928741455\nEpoch: 3, loss: 1.8309776888529459, time: 24.207036018371582\nEpoch: 4, loss: 1.8257667839050293, time: 24.120702028274536\nEpoch: 5, loss: 1.8219868227640788, time: 24.206580877304077\nEpoch: 6, loss: 1.8191900794347127, time: 24.16806697845459\nEpoch: 7, loss: 1.8169230650583903, time: 24.331862688064575\nEpoch: 8, loss: 1.8152085454940796, time: 24.128501892089844\nEpoch: 9, loss: 1.8138571093877156, time: 24.18015480041504\nEpoch: 10, loss: 1.8126553833007812, time: 24.11116600036621\nEpoch: 11, loss: 1.8118234336853027, time: 24.138602018356323\nEpoch: 12, loss: 1.810927623240153, time: 24.178167819976807\nEpoch: 13, loss: 1.8100264540990194, time: 24.15476083755493\nEpoch: 14, loss: 1.8094680803934733, time: 24.750940084457397\nEpoch: 15, loss: 1.808909009552002, time: 24.56411099433899\nEpoch: 16, loss: 1.808419003168742, time: 24.33816170692444\nEpoch: 17, loss: 1.8080004588445027, time: 24.542700052261353\nEpoch: 18, loss: 1.8076393677393596, time: 24.074925184249878\nEpoch: 19, loss: 1.8073650669733683, time: 24.70185089111328\naccuracy is 68.33833333333334 percentage\n" ], [ "model3 = train(lr=0.01,epochs=50)", "Linear_classifier(\n (network): Sequential(\n (0): Linear(in_features=784, out_features=512, bias=True)\n (1): ReLU()\n (2): Linear(in_features=512, out_features=128, bias=True)\n (3): ReLU()\n (4): Linear(in_features=128, out_features=10, bias=True)\n (5): ReLU()\n (6): Softmax(dim=None)\n )\n)\nlr: 0.01, epochs: 50\nEpoch: 0, loss: 2.129818073908488, time: 24.080988883972168\nEpoch: 1, loss: 1.7400812965393067, time: 24.8941650390625\nEpoch: 2, loss: 1.6670827271779378, time: 24.320021152496338\nEpoch: 3, loss: 1.6411245574951172, time: 24.07512092590332\nEpoch: 4, loss: 1.6310888650894164, time: 24.034185886383057\nEpoch: 5, loss: 1.6244946219762166, time: 24.036355018615723\nEpoch: 6, loss: 1.6195142652511596, time: 24.098693132400513\nEpoch: 7, loss: 1.6154249067306519, time: 24.087377071380615\nEpoch: 8, loss: 1.6116558298746744, time: 24.026623249053955\nEpoch: 9, loss: 1.6084177863438924, time: 24.03950786590576\nEpoch: 10, loss: 1.6055069213231405, time: 24.047260761260986\nEpoch: 11, loss: 1.6028189906438193, time: 24.124579191207886\nEpoch: 12, loss: 1.6005029698689779, time: 24.037775993347168\nEpoch: 13, loss: 1.5983643069585165, time: 24.01310682296753\nEpoch: 14, loss: 1.5964917603174846, time: 24.032498121261597\nEpoch: 15, loss: 1.5947590896606445, time: 24.02513098716736\nEpoch: 16, loss: 1.5931226430892944, time: 24.12795114517212\nEpoch: 17, loss: 1.5916109048843383, time: 24.05271601676941\nEpoch: 18, loss: 1.5901567092259725, time: 24.063508987426758\nEpoch: 19, loss: 1.5888247659683228, time: 24.195612907409668\nEpoch: 20, loss: 1.5876165884653728, time: 24.080713987350464\nEpoch: 21, loss: 1.5864203458150228, time: 24.144744873046875\nEpoch: 22, loss: 1.5852547505696615, time: 24.090742826461792\nEpoch: 23, loss: 1.584233110555013, time: 24.076359033584595\nEpoch: 24, loss: 1.5832076705296834, time: 24.049517154693604\nEpoch: 25, loss: 1.5822782171885172, time: 24.04938817024231\nEpoch: 26, loss: 1.58135567334493, time: 24.15090274810791\nEpoch: 27, loss: 1.580672452990214, time: 24.02203917503357\nEpoch: 28, loss: 1.5798677792231242, time: 24.056845903396606\nEpoch: 29, loss: 1.5790389831542968, time: 23.998090982437134\nEpoch: 30, loss: 1.57846678536733, time: 24.036945819854736\nEpoch: 31, loss: 1.577757869529724, time: 24.11064100265503\nEpoch: 32, loss: 1.577204416211446, time: 24.08041787147522\nEpoch: 33, loss: 1.5766699955622354, time: 24.049437999725342\nEpoch: 34, loss: 1.576108709081014, time: 24.071058988571167\nEpoch: 35, loss: 1.5755958372116088, time: 24.07719588279724\nEpoch: 36, loss: 1.5751629572550456, time: 24.34847402572632\nEpoch: 37, loss: 1.5746964686711629, time: 24.086578845977783\nEpoch: 38, loss: 1.574321648724874, time: 23.33028292655945\nEpoch: 39, loss: 1.573866577720642, time: 23.2348153591156\nEpoch: 40, loss: 1.5734696179707846, time: 23.761223793029785\nEpoch: 41, loss: 1.5730959978103638, time: 23.381640911102295\nEpoch: 42, loss: 1.5726915952046712, time: 23.28765106201172\nEpoch: 43, loss: 1.5723644069671632, time: 23.25067973136902\nEpoch: 44, loss: 1.5720338404973349, time: 23.30796480178833\nEpoch: 45, loss: 1.5717352633794148, time: 23.243934869766235\nEpoch: 46, loss: 1.5714073214213053, time: 23.808011054992676\nEpoch: 47, loss: 1.5710991270701091, time: 24.056615114212036\nEpoch: 48, loss: 1.5708042559305826, time: 24.06311297416687\nEpoch: 49, loss: 1.5705430344263713, time: 24.07011604309082\naccuracy is 89.045 percentage\n" ], [ "model4 = train(lr=0.01,epochs=20,mode='Adam')", "Linear_classifier(\n (network): Sequential(\n (0): Linear(in_features=784, out_features=512, bias=True)\n (1): ReLU()\n (2): Linear(in_features=512, out_features=128, bias=True)\n (3): ReLU()\n (4): Linear(in_features=128, out_features=10, bias=True)\n (5): ReLU()\n (6): Softmax(dim=None)\n )\n)\nlr: 0.01, epochs: 20\nEpoch: 0, loss: 2.363519980239868, time: 35.35069227218628\nEpoch: 1, loss: 2.363634099451701, time: 38.660786867141724\nEpoch: 2, loss: 2.3636341013590494, time: 38.3831102848053\nEpoch: 3, loss: 2.363634102757772, time: 38.38648819923401\nEpoch: 4, loss: 2.3636341040293374, time: 38.41402864456177\nEpoch: 5, loss: 2.3636341053009033, time: 38.64765691757202\nEpoch: 6, loss: 2.3636341068267823, time: 38.38868474960327\nEpoch: 7, loss: 2.363634105173747, time: 38.293275117874146\nEpoch: 8, loss: 2.363634103393555, time: 37.99690890312195\nEpoch: 9, loss: 2.363634108479818, time: 38.30868577957153\nEpoch: 10, loss: 2.3636341086069743, time: 38.563183069229126\nEpoch: 11, loss: 2.3636341050465903, time: 38.28367495536804\nEpoch: 12, loss: 2.363634106572469, time: 38.599061727523804\nEpoch: 13, loss: 2.363634108734131, time: 38.416993141174316\nEpoch: 14, loss: 2.363634106318156, time: 37.85789108276367\nEpoch: 15, loss: 2.3636341059366863, time: 36.84247875213623\nEpoch: 16, loss: 2.3636341064453124, time: 38.0234899520874\nEpoch: 17, loss: 2.3636341070810953, time: 38.47244596481323\nEpoch: 18, loss: 2.3636341112772623, time: 38.53123712539673\nEpoch: 19, loss: 2.363634104537964, time: 38.3549919128418\naccuracy is 9.751666666666667 percentage\n" ], [ "model4 = train(lr=0.001,epochs=20,mode='Adam')", "Linear_classifier(\n (network): Sequential(\n (0): Linear(in_features=784, out_features=512, bias=True)\n (1): ReLU()\n (2): Linear(in_features=512, out_features=128, bias=True)\n (3): ReLU()\n (4): Linear(in_features=128, out_features=10, bias=True)\n (5): ReLU()\n (6): Softmax(dim=None)\n )\n)\nlr: 0.001, epochs: 20\nEpoch: 0, loss: 1.596229276974996, time: 29.52825117111206\nEpoch: 1, loss: 1.513808993212382, time: 30.539342880249023\nEpoch: 2, loss: 1.5034395808537802, time: 31.73619294166565\nEpoch: 3, loss: 1.5025473094940185, time: 32.89376187324524\nEpoch: 4, loss: 1.4989228372573853, time: 33.86837577819824\nEpoch: 5, loss: 1.500059866841634, time: 34.27565813064575\nEpoch: 6, loss: 1.4964721212387084, time: 35.40650820732117\nEpoch: 7, loss: 1.4984564292907714, time: 35.563862800598145\nEpoch: 8, loss: 1.493804841931661, time: 35.99980068206787\nEpoch: 9, loss: 1.4947130980809529, time: 35.73797297477722\nEpoch: 10, loss: 1.4957053396224975, time: 35.02749800682068\nEpoch: 11, loss: 1.4990937310536703, time: 34.7343270778656\nEpoch: 12, loss: 1.496659952354431, time: 34.74005675315857\nEpoch: 13, loss: 1.4935693226496378, time: 34.355056047439575\nEpoch: 14, loss: 1.4921105810801187, time: 34.19899582862854\nEpoch: 15, loss: 1.4946571371714275, time: 34.1012020111084\nEpoch: 16, loss: 1.4958946170806884, time: 34.05534267425537\nEpoch: 17, loss: 1.4953842925389609, time: 33.84981083869934\nEpoch: 18, loss: 1.4945051233927409, time: 33.45101284980774\nEpoch: 19, loss: 1.4963880776087444, time: 33.6051549911499\naccuracy is 96.93 percentage\n" ], [ "model4 = train(lr=0.001,epochs=5,mode='Adam')", "Linear_classifier(\n (network): Sequential(\n (0): Linear(in_features=784, out_features=512, bias=True)\n (1): ReLU()\n (2): Linear(in_features=512, out_features=128, bias=True)\n (3): ReLU()\n (4): Linear(in_features=128, out_features=10, bias=True)\n (5): ReLU()\n (6): Softmax(dim=None)\n )\n)\nlr: 0.001, epochs: 5\nEpoch: 0, loss: 1.6744712434132893, time: 29.775541067123413\nEpoch: 1, loss: 1.5162453948338825, time: 30.73548913002014\nEpoch: 2, loss: 1.5054007658640545, time: 31.64878487586975\nEpoch: 3, loss: 1.5018550045013428, time: 33.25916504859924\nEpoch: 4, loss: 1.500238242594401, time: 34.56008005142212\naccuracy is 96.57333333333334 percentage\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
4a5146af80a38d991e541cf5ac76c7dab0489ad7
25,378
ipynb
Jupyter Notebook
CSS-Le_BN_pour_styler.ipynb
ericECmorlaix/m0-jupyter
c7b38b38d361841ace8c55f6941a18218038c055
[ "CC0-1.0" ]
1
2021-04-26T13:28:19.000Z
2021-04-26T13:28:19.000Z
CSS-Le_BN_pour_styler.ipynb
ericECmorlaix/m0-jupyter
c7b38b38d361841ace8c55f6941a18218038c055
[ "CC0-1.0" ]
null
null
null
CSS-Le_BN_pour_styler.ipynb
ericECmorlaix/m0-jupyter
c7b38b38d361841ace8c55f6941a18218038c055
[ "CC0-1.0" ]
3
2019-04-29T07:22:23.000Z
2020-09-25T13:53:02.000Z
34.341001
447
0.556939
[ [ [ "# Le Bloc Note pour ajouter du style", "_____no_output_____" ], [ "Dans un notebook jupyter on peut rédiger des commentaires en langage naturel, intégrer des liens hypertextes, des images et des vidéos en langage HTML dans des cellules de type **`Markdown`**.\n\nC'est ce que décrit le bloc-note [HTML](HTML-Le_BN_pour_multimedier.ipynb) - Un bloc-note pour créer un document Web multimédia en HTML dans un jupyter notebook.\n\nCependant, l'affichage se fait avec le rendu définit dans le style par défaut de l'environnement jupyter notebook qui est utilisé pour lire le document.\n\nNous allons voir qu'il est possible de modifier cet affichage en apportant du code CSS et cela à différents niveaux...", "_____no_output_____" ], [ "*** \n> Ce document est un notebook jupyter, pour bien vous familiariser avec cet environnement regardez cette rapide [Introduction](Introduction-Le_BN_pour_explorer.ipynb). \n\n***", "_____no_output_____" ], [ "**CSS**, pour [Cascading Style Sheets](https://fr.wikipedia.org/wiki/Feuilles_de_style_en_cascade), est un langage qui décrit au navigateur le style dans lequel le contenu d'une page HTML doit être affichée.\n\nIl s'agit de déclarer des propriétés CSS et leur valeur, soit directement dans la balise du code HTML à \"styler\", ou par l'intermédiaire d'un sélecteur qui pointe vers l'élément HTML visé.\n\n![https://www.w3schools.com/css/css_syntax.asp](https://www.w3schools.com/css/selector.gif)\n\n\nLa suite n'utilise que quelques propriétés de CSS afin de montrer comment les appliquer dans un jupyter notebook.\n\nPour bien comprendre et vous initiez au langage CSS vous pouvez, par exemple, faire ce tutoriel de la [Khanacademy](https://fr.khanacademy.org/computing/computer-programming/html-css/intro-to-css/pt/css-basics) et pour le découvrir de façon plus complète et détaillée rendez-vous sur ce site de référence https://www.w3schools.com/css/...", "_____no_output_____" ], [ "## Déclaration CSS en ligne :\n\nLa façon la plus simple d'apporter un peu de style dans une cellule de type Markdown d'un jupyter notebook est d'écrire la déclaration CSS directement dans la balise HTML concernée :", "_____no_output_____" ], [ "> <h3 class='fa fa-cogs' style=\"color: darkorange\"> A faire vous-même </h3>\n>\n> Pour voir le résultat du code **CSS** associé au **HTML** copier/coller les deux codes suivants dans deux cellules de type **`Markdown`**, puis appuyer sur les touches **`<Maj+Entree>`** ou sur le bouton <button class='fa fa-step-forward icon-step-forward btn btn-xs btn-default'></button>.\n\n**** \n\n````html\n<h1 style=\"color:purple;text-shadow: 3px 2px darkorange;text-align:center; font-size:5vw;font-variant: small-caps;\">\n Un résultat stylé !\n</h1>\n<h1>\n Le résultat par défaut.\n</h1>\n````\n\n****\n\n````html\n<center><br>\n <img src=\"https://ericecmorlaix.github.io/img/Jupyter_logo.svg\" style = \"display:inline-block\">\n <img src=\"https://ericecmorlaix.github.io/img/Jupyter_logo.svg\" style = \"display:inline-block\">\n <img src=\"https://ericecmorlaix.github.io/img/Jupyter_logo.svg\" style = \"display:inline-block\">\n <img src=\"https://ericecmorlaix.github.io/img/Jupyter_logo.svg\">\n <img src=\"https://ericecmorlaix.github.io/img/Jupyter_logo.svg\">\n <img src=\"https://ericecmorlaix.github.io/img/Jupyter_logo.svg\">\n</center>\n````\n\n****", "_____no_output_____" ] ], [ [ "# Tester votre code ici", "_____no_output_____" ], [ "# Tester votre code ici", "_____no_output_____" ] ], [ [ "> L'attribut style ajouté en ligne dans une balise HTML permet de surcharger le CSS pour forcer un style d'affichage différent du style par défaut. Les trois premières images s'affichent donc ici en ligne, l'une à coté de l'autre, et non pas comme par défaut, en bloc, l'une sous l'autre : https://www.w3schools.com/css/css_inline-block.asp.", "_____no_output_____" ], [ "## Déclaration CSS en interne :\n\nLa déclaration du CSS en ligne est limitée car elle ne s'applique qu'à une seule balise. Si on souhaite appliquer le même style à plusieurs balises, il nous faut le réécrire à chaque fois...\n\nSi on écrit toutes les déclaration de CSS entre deux balises `<styles>...</style>` dans un code HTML, il s'appliquera potentiellement à tout le contenu de ce code. Et alors, pour distinguer à quelle balise le style doit s'appliquer spécifiquement, on utilise des sélecteurs : https://www.w3schools.com/css/css_selectors.asp\n\nCelà devient très pertinent lorsque l'on souhaite faire une simple modification dans le style car il suffit de la faire à un seul endroit pour qu'elle s'étende sur l'ensemble du code concerné.\n\n> <h3 class='fa fa-cogs' style=\"color: darkorange\"> A faire vous-même </h3>\n>\n> Pour voir le résultat du code **CSS** sur le **HTML** visé copier/coller tout le code suivant dans une cellule de type **`Markdown`**, puis appuyer sur les touches **`<Maj+Entree>`** ou sur le bouton <button class='fa fa-step-forward icon-step-forward btn btn-xs btn-default'></button>.\n\n**** \n\n````html\n<style>\n h1 {\n color:purple;\n text-shadow: 3px 2px darkorange;\n text-align:center;\n font-style: oblique; \n font-variant: small-caps;\n }\n</style>\n<h1 style=\"font-size:5vw\">Un résultat sur-stylé !</h1>\n<h1>Le nouveau résultat par défaut.</h1>\n````\n\n****", "_____no_output_____" ] ], [ [ "# Tester votre code ici", "_____no_output_____" ] ], [ [ "On observe que le style définit entre deux balises `<styles>...</style>` dans un code HTML, ne s'applique pas dans une cellule de type Markdown.\n\nPour celà il nous faut recourrir à la fonction \"magic\" `%%html` de IPython dans une cellule de type **`Code`** :", "_____no_output_____" ] ], [ [ "%%HTML\n<style>\n h1 {\n color:purple;\n text-shadow: 3px 2px darkorange;\n text-align:center;\n font-style: oblique; \n font-variant: small-caps;\n }\n</style>\n<h1 style=\"font-size:5vw\">Un résultat sur-stylé !</h1>\n<h1>Le nouveau résultat par défaut.</h1>", "_____no_output_____" ] ], [ [ "***Super !*** Notre style c'est maintenant bien appliqué aux balises `<h1>` ciblés et on peut toujours surcharger une balise en particulier avec du style en ligne...\n\n***Problème !*** Notre style c'est aussi appliqué à toutes les balises `<h1>` précédentes de ce notebook et même au titre de niveau 1 codé en Markdown tout en haut de cette page, comme il s'appliquera au code suivant s'il est copier/coller dans une cellule de type **`Markdown`** :\n\n**** \n\n````markdown\n# Mon titre de niveau 1 codé en markdown est stylé !\n````\n\n****", "_____no_output_____" ] ], [ [ "# Tester votre code ici", "_____no_output_____" ] ], [ [ "On vient de définir un style qui s'applique à tout ce jupyter notebook. C'est intéressant...\n\nPour annuler son effet il faut Redémarrer le Noyau & Effacer toutes les sorties (``Kernel > Restart & Clear Output``).\n\nMais si on souhaite que ce style ne s'applique qu'à certaines balises, il nous faut être plus précis avec nos sélecteurs CSS, par exemple, en utilisant une sélection par classe :", "_____no_output_____" ] ], [ [ "%%HTML\n<style>\n.maClasse {\n color:purple;\n text-shadow: 3px 2px darkorange;\n text-align:center;\n font-style: oblique; \n font-variant: small-caps;\n }\n</style>\n<h1 class = \"maClasse\" style=\"font-size:5vw\">Un résultat sur-stylé !</h1>\n<h1 class = \"maClasse\">Le nouveau résultat stylé.</h1>", "_____no_output_____" ] ], [ [ "Et on peut maintenant le réutiliser n'importe où dans ce jupyter notebook dans une simple cellule Markdown", "_____no_output_____" ] ], [ [ "<p class = \"maClasse\">Super ! Mon style s'applique où je le souhaite...</p>", "_____no_output_____" ] ], [ [ "### Exemple d'application :\n\nAinsi si on utilise un [générateur de tableau HTML](https://www.tablesgenerator.com/html_tables#) et que l'on souhaite que le style CSS soit pris en compte, on peut copier/coller le code du style CSS dans une cellule de ``Code`` et celui du contenu HTML dans une cellule ``Markdown``:", "_____no_output_____" ] ], [ [ "%%html\n<style type=\"text/css\">\n.tg {border-collapse:collapse;border-spacing:0;border-color:#aabcfe;margin:0px auto;}\n.tg td{font-family:Arial, sans-serif;font-size:14px;padding:12px 12px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#669;background-color:#e8edff;}\n.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:12px 12px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#039;background-color:#b9c9fe;}\n.tg .tg-c9kt{font-size:16px;font-family:\"Comic Sans MS\", cursive, sans-serif !important;;text-align:left;vertical-align:middle}\n.tg .tg-sd90{font-weight:bold;font-size:16px;font-family:\"Comic Sans MS\", cursive, sans-serif !important;;text-align:left;vertical-align:middle}\n.tg .tg-nyir{background-color:#D2E4FC;font-size:16px;font-family:\"Comic Sans MS\", cursive, sans-serif !important;;text-align:left;vertical-align:middle}\n</style>", "_____no_output_____" ] ], [ [ "> <h3 class='fa fa-cogs' style=\"color: darkorange\"> A faire vous-même </h3>\n>\n> Pour voir le résultat du code **CSS** sur le **HTML** visé, copier/coller le code suivant dans une cellule de type **`Markdown`**, puis appuyer sur les touches **`<Maj+Entree>`** ou sur le bouton <button class='fa fa-step-forward icon-step-forward btn btn-xs btn-default'></button>.\n**** \n````html\n<center> \n <table class=\"tg\">\n <tr>\n <th class=\"tg-sd90\">A</th>\n <th class=\"tg-sd90\">B</th>\n <th class=\"tg-sd90\">C</th>\n </tr>\n <tr>\n <td class=\"tg-nyir\">a1</td>\n <td class=\"tg-nyir\">b1</td>\n <td class=\"tg-nyir\">c1</td>\n </tr>\n <tr>\n <td class=\"tg-c9kt\">a2</td>\n <td class=\"tg-c9kt\">b2</td>\n <td class=\"tg-c9kt\">c2</td>\n </tr>\n <tr>\n <td class=\"tg-nyir\">a3</td>\n <td class=\"tg-nyir\">b3</td>\n <td class=\"tg-nyir\">c3</td>\n </tr>\n </table>\n</center>\n````\n\n****", "_____no_output_____" ] ], [ [ "# Tester votre code ici", "_____no_output_____" ] ], [ [ "<h2 class=\"maClasse\">On peut alors réutiliser le style pour d'autres tableaux :</h2>\n<br>\n<center> \n <table class=\"tg\">\n <tr>\n <th class=\"tg-sd90\">Décimal</th>\n <th class=\"tg-sd90\">Binaire</th>\n <th class=\"tg-sd90\">Hexadécimal</th>\n <th class=\"tg-sd90\">Décimal</th>\n <th class=\"tg-sd90\">Binaire</th>\n <th class=\"tg-sd90\">Hexadécimal</th> \n </tr>\n <tr>\n <td class=\"tg-nyir\">0</td>\n <td class=\"tg-nyir\">0b0000</td>\n <td class=\"tg-nyir\">0x0</td>\n <td class=\"tg-nyir\">8</td>\n <td class=\"tg-nyir\">0b1000</td>\n <td class=\"tg-nyir\">0x8</td> \n </tr>\n <tr>\n <td class=\"tg-c9kt\">1</td>\n <td class=\"tg-c9kt\">0b0001</td>\n <td class=\"tg-c9kt\">0x1</td>\n <td class=\"tg-c9kt\">9</td>\n <td class=\"tg-c9kt\">0b1001</td>\n <td class=\"tg-c9kt\">0x9</td> \n </tr>\n <tr>\n <td class=\"tg-nyir\">2</td>\n <td class=\"tg-nyir\">0b0010</td>\n <td class=\"tg-nyir\">0x2</td>\n <td class=\"tg-nyir\">10</td>\n <td class=\"tg-nyir\">0b1010</td>\n <td class=\"tg-nyir\">0xA</td> \n </tr>\n <tr>\n <td class=\"tg-c9kt\">3</td>\n <td class=\"tg-c9kt\">0b0011</td>\n <td class=\"tg-c9kt\">0x3</td>\n <td class=\"tg-c9kt\">11</td>\n <td class=\"tg-c9kt\">0b1011</td>\n <td class=\"tg-c9kt\">0xB</td> \n </tr> \n <tr>\n <td class=\"tg-nyir\">4</td>\n <td class=\"tg-nyir\">0b0100</td>\n <td class=\"tg-nyir\">0x4</td>\n <td class=\"tg-nyir\">12</td>\n <td class=\"tg-nyir\">0b1100</td>\n <td class=\"tg-nyir\">0xC</td> \n </tr>\n <tr>\n <td class=\"tg-c9kt\">5</td>\n <td class=\"tg-c9kt\">0b0101</td>\n <td class=\"tg-c9kt\">0x5</td>\n <td class=\"tg-c9kt\">13</td>\n <td class=\"tg-c9kt\">0b1101</td>\n <td class=\"tg-c9kt\">0xD</td> \n </tr>\n <tr>\n <td class=\"tg-nyir\">6</td>\n <td class=\"tg-nyir\">0b0110</td>\n <td class=\"tg-nyir\">0x6</td>\n <td class=\"tg-nyir\">14</td>\n <td class=\"tg-nyir\">0b1110</td>\n <td class=\"tg-nyir\">0xE</td> \n </tr>\n <tr>\n <td class=\"tg-c9kt\">7</td>\n <td class=\"tg-c9kt\">0b0111</td>\n <td class=\"tg-c9kt\">0x7</td>\n <td class=\"tg-c9kt\">15</td>\n <td class=\"tg-c9kt\">0b1111</td>\n <td class=\"tg-c9kt\">0xF</td> \n </tr>\n </table>\n</center>", "_____no_output_____" ], [ "## Déclaration CSS en externe :\n\nLe défaut de la déclaration du CSS en interne est qu'il ne s'applique que sur la page dans laquelle il est défini.\n\nIl serait intéressant de pouvoir définir une feuille de style CSS commune à plusieurs carnets jupyter...\n\nIci aussi, lorsque l'on souhaitera faire une simple modification dans le style, il suffira de la faire à un seul endroit pour qu'elle s'étende sur l'ensemble des bloc-notes qui s'y réfèrent.\n\nDe plus on peut définir plusieurs feuilles de style différentes et choisir, au gré de nos envies, laquelle appliquée en ne changeant qu'une ligne de code...\n\nOn va créer un fichier externe nommé ``monStyle.css`` qui contiendra notre déclaration de style telle que :\n```css\nh1 {\n color: red; \n}\n\nh2 {\n color: green; \n}\n\np {\n color: blue;\n}\n```\nPuis l'enregistrer dans le même dossier que ce notebook.\n\nPar ailleurs, nous allons utiliser deux autres feuilles de style disponibles sur le web :\n- https://ericecmorlaix.github.io/monStyle.css ;\n- https://ericecmorlaix.github.io/monAutreStyle.css.\n\nPour appliquer le résultat du code **CSS** sur le **HTML** basculer le type de la cellule ci-dessous de **`Code`** en **`Markdown`**, et appuyer sur les touches **`<Maj+Entree>`** ou sur le bouton <button class='fa fa-step-forward icon-step-forward btn btn-xs btn-default'></button>.\n\nEnfin exécuter successivement les trois cellules de codes suivantes...", "_____no_output_____" ] ], [ [ "<h1>Mon titre de niveau 1 :</h1>\n<h2>Mon titre de niveau 2 :</h2>\n<p>Mon paragraphe.</p>", "_____no_output_____" ], [ "%%html\n<link rel=\"stylesheet\" type=\"text/css\" href=\"monStyle.css\">", "_____no_output_____" ], [ "%%html\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://ericecmorlaix.github.io/monStyle.css\">", "_____no_output_____" ], [ "%%html\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://ericecmorlaix.github.io/monAutreStyle.css\">", "_____no_output_____" ] ], [ [ "> <h3 class='fa fa-cogs' style=\"color: darkorange\"> A faire vous-même </h3>\n>\n> Jouer avec les flèches <button class='fa fa-arrow-up icon-arrow-up btn btn-xs btn-default'></button> <button class='fa fa-arrow-down icon-arrow-down btn btn-xs btn-default'></button> pour modifier l'ordre des cellules de code.\n> On observe que c'est toujours le style de la cellule la plus basse qui s'applique...\n\n> Rappel : pour revenir au style par défaut de l'environnement jupyter, il faut Redémarrer le Noyau & Effacer toutes les sorties (``Kernel > Restart & Clear Output``).", "_____no_output_____" ], [ "## Complément avec la fonction HTML() de IPython.display :\n\nLa fonction HTML() du module IPython.display permet d'afficher directement une chaine de caractères écrite en langage HTML. Cette chaine générée par un script Python peut inclure du CSS.", "_____no_output_____" ] ], [ [ "from IPython.display import HTML\n\nenLigne = '<img src=\"https://ericecmorlaix.github.io/img/Jupyter_logo.svg\" style = \"display:inline-block\">'\n\nenBloc = '<img src=\"https://ericecmorlaix.github.io/img/Jupyter_logo.svg\">'\n\nchaine = '<center><br>' + enLigne * 8 + enBloc * 3 + '</center>'\n\nHTML(chaine)", "_____no_output_____" ], [ "from IPython.display import HTML\nfrom random import randint\n\ncouleur=['red','blue','green', 'yellow', 'purple', 'pink', 'orange', 'cyan', 'magenta', 'nany', 'yellowgreen', 'lightcoral']\n\nchaine = ''\n\nfor i in range(1,7) :\n chaine = chaine + f'<h{i} style = \"color:{couleur[randint(0, len(couleur) - 1)]}; text-align:center;\">Mon titre de niveau {i}</h{i}>'\n\nHTML(chaine)", "_____no_output_____" ] ], [ [ "## Ressources :", "_____no_output_____" ], [ "* Pour aller plus loin en HTML/CSS : http://api.si.lycee.ecmorlaix.fr/APprentissageHtmlCss/\n* Un site de référence pour le CSS : https://www.w3schools.com/css/default.asp\n* On peut très avantageusement utiliser un [générateur de feuille de style CSS](https://www.megaptery.com/2012/05/21-outils-generateurs-css-developpeurs-web.html)", "_____no_output_____" ], [ "## A vous de jouer :\n\n> <h3 class='fa fa-cogs' style=\"color: darkorange\"> A faire vous-même </h3>\n>", "_____no_output_____" ], [ "*** \n\n> **Félicitations !** Vous êtes parvenu au bout des activités de ce bloc note. \n> Vous êtes maintenant capable d'imposer votre style en **CSS** dans l'environnement interactif jupyter notebook.\n\n> Pour explorer plus avant d'autres fonctionnalités de jupyter notebook repassez par le [Sommaire](index.ipynb).\n\n***", "_____no_output_____" ], [ "<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-sa/4.0/\"><img alt=\"Licence Creative Commons\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-sa/4.0/88x31.png\" /></a><br />Ce document est mis à disposition selon les termes de la <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-sa/4.0/\">Licence Creative Commons Attribution - Partage dans les Mêmes Conditions 4.0 International</a>.\n\nPour toute question, suggestion ou commentaire : <a href=\"mailto:[email protected]\">[email protected]</a>", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4a515c562dfff80da142bf24f780907bbfcce701
569,514
ipynb
Jupyter Notebook
Final_Project.ipynb
ds3300/adl_final_project
49e7e6bf9190e6c56bd950ccd9bee7a39606dd13
[ "Apache-2.0" ]
null
null
null
Final_Project.ipynb
ds3300/adl_final_project
49e7e6bf9190e6c56bd950ccd9bee7a39606dd13
[ "Apache-2.0" ]
null
null
null
Final_Project.ipynb
ds3300/adl_final_project
49e7e6bf9190e6c56bd950ccd9bee7a39606dd13
[ "Apache-2.0" ]
null
null
null
359.996207
208,718
0.9121
[ [ [ "# Applied Deep Learning Final Project\r\n### Author: David Schemitsch (ds3300)\r\n\r\nMany local governments aim to make data available to the public under the open data movement. However, a significant portion are released as PDFs, which makes it \"available\" but not in an easily accessible format like a CSV (for example: property assessment data). In this project, I aim to take a PDF of tabular data, use a convolutional neural network (CNN) to do object character recognition (OCR) on the text, and ultimately convert it to a more accessible format for analysis. This project will use as a test case the [Town of Southampton Assessment Roll](https://www.southamptontownny.gov/DocumentCenter/View/20996/Village-of-Southampton-473605), which lists assessed values for properties and their owners. An example image of the file is below.\r\n", "_____no_output_____" ], [ "![southampton_assessment_roll.jpg](data:image/jpeg;base64,/9j/4AAQSkZJRgABAAEAYABgAAD//gAfTEVBRCBUZWNobm9sb2dpZXMgSW5jLiBWMS4wMQD/2wCEAAUFBQgFCAwHBwwMCQkJDA0MDAwMDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0BBQgICgcKDAcHDA0MCgwNDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDf/EAaIAAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKCwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoLEAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+foRAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/AABEIAaIExwMBIgACEQEDEQH/2gAMAwEAAhEDEQA/APsuiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACigkKMngDqfSmxyLKoeMhkYBlZSCCCMggjggjkEcEUAOoopglRmMYYF0ALKCNwDZ2kjqAcHBPXBx0NAD6KKKACiiigAooooAKKKKAIbkssLmNfMcI21A2wscHC7jwuTxu7ZzXi8Xglf7J1C2l0qSdXAaC1nGl+ZJcATqJFFvJDZPEnnB45bnZdsweSbfKIjXsl9LJBbSyQLvlSN2RcE7nCkquBgnJAGAcmvNzrsf2WSaDXRPbGVY7m6IsDJpvyyu5fbAsUPzeVCBeQOYfvTFznC7+i7ae9p879/lqUtLPs2/Wy1Xpbot1cytY8LzbLBdD0lLA6ckt7EWt7GQwzudxs4dmpW/2eWVizM6NLZZ2h94+7rt4btL/AF221S40QrNLCJprx/sLPBdKYGiRpFumuC0SwGPMCSQ/PgMyPKRSvdduIoI55NVe3hlt7yK1nCWSLeXCugtJE862cPPKrN5ccOIrjb5kUBQ4Aut3zX7aeuoySGC+sopPLSyaWPfBC0kF0otmEcVxmV0cJDIskbos2GjjXRXumt76Xvo5ScPVWvF2eqtD7Talm9E77Wd/NQSl6O75tdm3P7KTS+APDi6HeSv/AGPNYSTG5ZruRdIjQRvMrx28Y06Vp5lwAytdq7x7WUS4YLXaeK7A38EYe1/tO3jk3T2WYf36bHVRtuHjt5NjlX8uaREON2dyqDyWkS3V7c6lar4ieeWxDROoTSz9lZoonE5RLYOnlS+dHsuGlUqpR8yIXrqPB+p/23bPqKXkd9FPJtRYZLeaGDygEZElhijLl2BlfzNxUuFXCgZjdJdFFP5N6eXndaefMW/db7ttfO3yfy36NWOKvvBSard6Ympacbi2gW7D5j0y4it45ZkeC2mN5vn8uONSm6xXejBQ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Zpnd2b7IrBCIjEkedjRuQVFVNBupP7ZIvUt7m8lubteUZru0ijDeU+5mIjt5E2oqoiBjIG8x2ZlAo6X/uuVrdu3deZLxHK+W321C6lda9XZaPpy73v01PXqK8b8Mm0EsRjO24Fle/2kUVmlD+amw3KqC7Sj955YcGQjIQYrS8C2trpdybLTJYb63FojS3UUMCMsyvtWJ3gRSxZSX2TtJMhUlnO6nyb67K603s5p69F7t038V9NQVdtxXKrNtNqSbWkLe7a7fv2kl8HK23Y9SooorI7gooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACioLtpFhcwlVkCMVLqWUMAcFlDIWGeoDqT6ivLtP8eXc1q9yTaXjJYG7cW6SILaUFQsE5M04LPuYgAxuPLbKYORUYuV+Xpb8U3/7a9/Tdo56laNFpT0vfX0cU9L3fxLZPS72Ta9Yorz/UdZ1fS5JLeSSzkk+xTXiOttMiqbdkDxtGbti+8ONriRNhBJR84F661bULfQDqoa3N0tv9pIMEnlFdnmeWE+0bwcELv80jILbOdofLZc11bT85Lt3jJfLzV0qybceWSaTbWnRRdt97Ti+2u900uyoqlprzSW0b3LI8roGYxo0afNyAEaSUjAIBy5yQTxnAyPE2rz6PDFJAoCPKElneKSZLdNrHzHihZXYFgEyHUKW3McClaz5fO36GvOlD2jula/ntf0/Gy72Okory7WPGN7plra3qy2csVybjc9vbz3S7IleSNowLmA52qFlDkLG+5i4VTWxbaxrFw8FgY7eG9eKS4md1ZohEsrRxBI0mLb5RsY7piIwSSGYbKrka182vuTb+5JvvtpdnOsR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6lE0TwXcdxE12sktnJIZ3gQOWW0u7sR4KbUR3BSMJGudhC+mVT6ei222W3l28uxK677vfffr59/MKKKKQwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKpx6fbxXMl8qAXE0ccTyckmOIu0a8nACtI54AyWyc4GLlFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUVg+JEJsmdWkjaNo2UxySRnIlTgmNl3KejI2VYEqwIJFAG9RRXn3iTxRf6XfRx2MPn2sTRLeMY4sIZ2CxjzpdQtmQ7W34hs75m+7tQkZOqXfQO77HoNFchLqWoTXMjwTWMFrb3KWzxXCSea5JhLMJhOiRsyOwhiMEvmMY2Mihiox7HXpL3xC0JF7Fsgu41hktbyK2IgltwsokkhS2meQmQrJHJIBE0aAgsdx2fdOXnZR5vxVvv12sH6NLyve36P1a80z0eiuN0ASRzQsXmc3tn9puBLNLKFn/cgeWkj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dvL5beVtW3dkK3R3Xfvotem++yWuiSsgoooqCgooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigDDu/DGkX7TPdWNnO90EE7S28LmYREGMSlkJkEZAKB87CBtxinyeHNKlne6ks7V7iaIwSStbxGSSEjaYncpuaMrwUYlSOMYrZoo8un+ej/DQPP+tP+GMGfwro11AtnNYWUttGgjSF7aFoljVtyosZQqqKwDBQAAwyBmo/+EQ0MQJZjTrH7NCxaOH7LB5SMzKzMkfl7VYsqsSoBLKpPIFdFRR/w/z3D+vwt+WnoAGOBxiiiigAooooARlDAqRkHgg9xWZYaNa6bG8UIkKzElzLNNO5Bz8geaSR1jXJ2RKwjjBIjVcmtSijy76PzXYP028jCh8N2Nrp0ejW6y29nAqpGsFzcwyIqHKgTxSpcYz1/e/MMq2VJFXpdMt5bVrDDJA6FCIpJInw2dxWWJ0lVjkkurh8ktuyc1fooet7633v19Q226beRhS+G7KWCC1YTeVZhVjAublWKKAvlzOswe5jYAeZHcNLHJgGRWIrd6cCiindvfvf5vd+obadtF5LsFFFFIAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACq15aR38D2028RyqUby5JInwwwdssTJIhx0ZHVh2IqzRS30YbbHMR+DtNiZXUXG6NLeNc3t6cLaHdAMG4IypJ3sRumDOsxkV3BD4O0srChjl22yiNV+03W10UkpHcL52LqNCTsS5Eqp0QAV09FVd/jf59/XzF/lb5LZenkZFxoNndXaX8iN58WMbZZkjbaSUMsKSLDM0ZJMTTRu0RJMZU81JDo9tb3T3qB/OkGCGmmaNe7GOBpDDCznmRoo0aQ8yFq06KW39d9/vH/X3bfcZFjoVnps8lzbI6yTZzulmdF3HcwhieRooFdvndYEjV3+Zwzc1r0UUeXYAooooAKKKKACiiigCKeFbiNonLBZFKko7xsAwwdroyujc8MjKynlSCAa5OTwVaR6XdaRZy3MMV+jpI8t1dXjKJciUxm7nlKFwz52FQXbewY9exopfro/NdmPazXR3Xk+67MyrnRbW6tUsWV44YlVY/Jllt5Iwq7F8uWB45YyEyuUdTtJUnBINa88M2F9FFDKkirbjCGK4uIZNpxuV5YZY5JUcgGVJXdJT80gY81vUU99X3v8+4lpouisvJdjIutBs7sQq6MqW2BGkUssMZUDAjkjidEmhA/5YzLJF/sZqFdCT+1m1p23yfZUtYkKgCJBI0kpDZJJmYxhuAAIl65rdop7a+v4qz+9Np90Ly9F9zuvuaujH/sGz+2/2lsYXHfEswiLbQnmG3En2czBAEExiMwjGwPt4qPT/DlhpczXFsjB3BUB5ppUjQkFkgjlkeO2jYhS0dukaMVUspwMblFL/hvl2H/X3bfcZGlaFZ6Lv+xq6eaRkPLNKFVc7Y4hLI4hhTJ2QwhIkydqDJrXoooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAoorE8QSTQWjTW8rwPG0ZyojbcPMQFGEkcg2sCVJXawByrKcEAG3RRXE6/4xOiX0NmkBuY3KCd41u3aDzGCRk+RZT2yAk7ibq7tBsyyl8Gjql1eiDz7anbUVzT6vqEtyyWVpHPaxSrDJI115cwbdH5jRw+Q6NHGrsxL3EcjFCqRsGVjg2HjG31PXpLC3vLeRIYbpGs0kgacS20kCtLIoJmjJLSokZ2gqhkIO4bT/Jy+SjzX77bd79rtH6NL5t2t+f3W30PQ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lFLy9fx3/Mfn6fha35GVpmlf2cXd55ruWTA8yfyQyxqWMcSiGKFNke9tpZWlbJMkjnBGrRRQGwUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQB/9k=)", "_____no_output_____" ], [ "Before training a CNN to recognize text in the PDF, a large amount of preprocessing needs to be done first. The tabular structure of the image needs to be maintained in order to know what the text represents. Preprocessing is a multistep process:\r\n\r\n1. Identify the pixel ranges for each column by identifying the header row, and then finding out where a column begins by calculating a moving average of pixel values (if the window changes from 255 (white) to less than 255, that indicates there is text, and so, a new column).\r\n2. Identify the pixel ranges for each row with the same moving pixel technique. This time, use the horizontal lines in the PDF that indicate a new row. If the moving window changes from very low (representing a row of pixels in the line) to very high (representing blank space), this indicate the start of a new row.\r\n3. Divide up the rows into column cells by using the column start indices.\r\n4. Since each column cell is composed of multiple lines of text, which each indicate different information, the cells need to be divided into lines of text. Since text can overlap between lines of text (e.g. with letters like 'g' that hang below the line), the moving average technique isn't sufficient. Here, I identify the coutours of the letters using the `cv2` package, determine which is the first letter as defined by being closest to the top-left hand corner of the image, and then assign the remaining contours as being part of the first line based on whether the top contour is above the bottom contour of the first letter. This process is repeated until all contours are assigned to a line.\r\n5. Once the contours of the text lines are determined, the lines are broken into words based on a moving average approach (a change in the moving average indicates the start of a new word). \r\n6. Finally, the letters are then identified and the bounding box surroundng the letter is extended to a dimension that will match the training set, so as to avoid distorting the image when it is processed through the model. It is important throughout this process to maintain the order of the contours so that the predicted text will make sense.\r\n\r\nThe preprocessing functions are in the `pdf_text_extraction.py` file, and the aforementioned process is wrapped up in the `extract_img_rows_and_cols` function.", "_____no_output_____" ], [ "#### Install packages\r\nThis project requires installation of `pdf2image` to convert a PDF into a JPEG.", "_____no_output_____" ] ], [ [ "# Install necessary packages\n\n!pip install pdf2image -q\n!pip install s3fs -q\n!pip install boto3 -q\n!apt-get update --fix-missing && apt-get install poppler-utils -q", "_____no_output_____" ] ], [ [ "#### Load packages", "_____no_output_____" ] ], [ [ "from pdf2image import convert_from_path, convert_from_bytes\nfrom IPython.display import display, Image\nimport matplotlib.pyplot as plt\nimport os\nimport pandas as pd\nimport s3fs\nimport boto3\nimport sys\nfrom PIL import Image\nimport numpy as np\nimport tensorflow as tf\nfrom google.colab.patches import cv2_imshow\nimport cv2\nimport re\nfrom PIL import Image, ImageDraw, ImageFont\nfrom string import ascii_lowercase, ascii_uppercase", "_____no_output_____" ] ], [ [ "### Set image dimensions", "_____no_output_____" ] ], [ [ "# Set image dimensions\nIMG_WIDTH=50\nIMG_HEIGHT=70", "_____no_output_____" ] ], [ [ "##Create cropped image corpus", "_____no_output_____" ], [ "### Read in files from GitHub", "_____no_output_____" ] ], [ [ "#! rm -r adl_final_project/\r\n! git clone https://github.com/ds3300/adl_final_project\r\n! cp adl_final_project/pdf_text_extraction.py .", "Cloning into 'adl_final_project'...\nremote: Enumerating objects: 54, done.\u001b[K\nremote: Counting objects: 100% (54/54), done.\u001b[K\nremote: Compressing objects: 100% (49/49), done.\u001b[K\nremote: Total 54 (delta 14), reused 0 (delta 0), pack-reused 0\u001b[K\nUnpacking objects: 100% (54/54), done.\n" ], [ "import pdf_text_extraction", "_____no_output_____" ], [ "pdf_text_extraction.convert_pdf_to_jpegs(pdf_file_name='adl_final_project/Southampton 473605_2_pgs1-5.pdf')\r\nprocessed_imgs = pdf_text_extraction.extract_img_rows_and_cols(\r\n pdf_sheet_dir='/content/pdf_sheets', cutoff=150)", "Making directory /content/pdf_sheets\nConverting PDF sheets to JPEGs\nReading in and converting JPEGs (5/5)\n\nExtracting image rows and columns (5/5)" ], [ "# Display example of one row-column cell\r\nplt.imshow(processed_imgs[0][1].get('col0'))", "_____no_output_____" ] ], [ [ "##Create training data set from generated text images", "_____no_output_____" ], [ "One benefit of creating a model to recognize machine text is that it is possible to generate a large training set of labeled data. The training data for the model is generated from 12 fonts. I originally only used the Courier font that most closely matched the font in the PDF, but tests showed that incorporating multiple fonts allowed the model to learn more general representations of the text, which acted as a sort of data augmentation. 500 images per glyph per font were generated, each having a small random effect of positioning, font size, or partially observed adjacent glyphs to best represent the image data from the PDF.", "_____no_output_____" ] ], [ [ "# All of the potential glyphs in the image\nglyphs = list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-#,.$')\n\nfont_size = 80", "_____no_output_____" ], [ "symbol_dict = {\n \"$\": \"dollar\",\n \"\\\\\": \"back_slash\",\n \"/\": \"forward_slash\",\n \"‘\": \"single_left_quote\",\n \"?\": \"question_mark\",\n \"’\": \"single_right_quote\",\n \"“\": \"double_left_quote\",\n \"!\": \"exclamation_mark\",\n \"”\": \"double_right_quote\",\n \"(\": \"left_parens\",\n \"%\": \"percent\",\n \")\": \"right_parens\",\n \"[\": \"left_bracket\",\n \"#\": \"hash\",\n \"]\": \"right_bracket\",\n \"{\": \"left_curly_brace\",\n \"@\": \"at_symbol\",\n \"}\": \"right_curly_brace\",\n \"/\": \"forward_slash\",\n \"&\": \"ampersand\",\n \"\\\\\": \"back_slash\",\n \"<\": \"less_than\",\n \"-\": \"hyphen\",\n \":\": \"colon\",\n \";\": \"semicolon\",\n \",\": \"comma\",\n \".\": \"period\",\n \"*\": \"star\",\n \"'\": \"single_quote\",\n '\"': \"double_quote\"\n}", "_____no_output_____" ], [ "import sys\nnp.random.seed(1)\n\n# NOTE: takes about 30 minutes to create the training set with 500 \n# examples per font per glyph. The training set was not saved due to \n# the size of the training set and the time needed to export it. The \n# random seed should ensure the same set of images is created each time.\n\n# Create directory for initial glyph images\n\nif \"text_images\" not in os.listdir(\"/content\"):\n print('Making directory /content/text_images')\n os.mkdir(\"/content/text_images\")\nelse:\n print('Removing and making directory /content/text_images')\n os.system(\"rm -r /content/text_images\")\n os.mkdir(\"/content/text_images\")\n\nif \"original\" not in os.listdir(\"/content/text_images\"):\n print('Making directory /content/text_images/original')\n os.mkdir(\"/content/text_images/original\")\nelse:\n print('Removing and making directory /content/text_images/original')\n os.system(\"rm -r /content/text_images/original\")\n os.mkdir(\"/content/text_images/original\")\n\nif \"train_test_images\" not in os.listdir(\"/content/text_images\"):\n print('Making directory /content/text_images/train_test_images')\n os.mkdir(\"/content/text_images/train_test_images\")\nelse:\n print('Removing and making directory /content/text_images/train_test_images')\n os.system(\"rm -r /content/text_images/train_test_images\")\n os.mkdir(\"/content/train_test_images\")\n\nprint(\"Progress:\")\n\n# Loop through the glyphs and create an image for each\nfor g_idx, g in enumerate(glyphs):\n g = str(g)\n progress = \"\\r \" + g + \" (\" + str(g_idx+1) + \"/\" + str(len(glyphs)) + \")\"\n\n sys.stdout.write(progress)\n sys.stdout.flush()\n \n im = Image.new(\"RGB\", (IMG_WIDTH, IMG_HEIGHT), \"white\")\n d = ImageDraw.Draw(im)\n d.text(xy=(0, 0), text=g, fill=\"black\", anchor=\"ms\", \n font=ImageFont.truetype('adl_final_project/CourierPrime-Regular.ttf', 80))\n \n if g in symbol_dict.keys():\n g_fn = symbol_dict.get(g)\n else:\n g_fn = g\n\n if g in ascii_lowercase:\n prefix_fn = 'lower_'\n elif g in ascii_uppercase:\n prefix_fn = 'upper_'\n elif g in '0123456789':\n prefix_fn = 'digit_'\n else:\n prefix_fn = 'symbol_'\n\n fn = os.path.join(\"/content\", \"text_images\", \"original\", prefix_fn+g_fn+\".jpeg\")\n \n im.save(fn)\n\n os.mkdir(\"/content/text_images/train_test_images/\"+prefix_fn+g_fn)\n\n for idx, f in enumerate(os.listdir('adl_final_project')):\n #print(f)\n if re.search(pattern='ttf$', string=f):\n ttf = os.path.join('adl_final_project', f)\n #print(ttf)\n else:\n continue\n \n if g in '1li$':\n n = 1000\n else:\n n = 500\n\n # Loop through each glyph and make a directory of 2000 images\n for i in range(n):\n if g in 'gjpqy':\n y_adj=10\n else:\n y_adj=0\n \n im = Image.new(\"RGB\", (IMG_WIDTH,IMG_HEIGHT), \"white\")\n d = ImageDraw.Draw(im)\n font_size = np.random.randint(low=60, high=80)\n font_i = ImageFont.truetype(ttf, font_size)\n \n g1 = glyphs[np.random.randint(0, len(glyphs))]\n g3 = glyphs[np.random.randint(0, len(glyphs))]\n msg = g1+g+g3\n w, h = d.textsize(msg, font = font_i)\n w1, h1 = d.textsize(g1, font = font_i)\n w2, h2 = d.textsize(g, font = font_i)\n x_adj = (w/2)-(w1+(w2/2))\n x_noise = np.random.randint(low=-4, high=4)\n y_noise = np.random.randint(low=-6, high=6)\n # Adjust position of the central glyph so that it its fully visible\n # within the frame - this accounts for fonts that are not monospaced,\n # where the left or right glyph may push the central glyph out of frame.\n d.text(xy=((IMG_WIDTH/2)-(w/2)+x_adj+x_noise,(IMG_HEIGHT/2)-(h/2)-y_adj+y_noise), \n text=msg, fill=\"black\", \n anchor='mm',\n font = font_i)\n\n fn = os.path.join(\"/content/text_images/train_test_images\", prefix_fn+g_fn, prefix_fn+g_fn+\"_\"+\"{:02d}\".format(idx)+\"{:05d}\".format(i)+\".jpeg\")\n im.save(fn)\n\nprint(\"\\r \"+'All done')", "Removing and making directory /content/text_images\nMaking directory /content/text_images/original\nMaking directory /content/text_images/train_test_images\nProgress:\n All done\n" ] ], [ [ "Below are a few examples of the randomly generated 'H' glyphs that show different font styles, font sizes, glyph position, and adjacent text in the frame.", "_____no_output_____" ] ], [ [ "# Display a few examples of \"H\"\r\nH_dir = os.listdir(\"/content/text_images/train_test_images/upper_H/\")\r\n\r\nfig, ax = plt.subplots(nrows=1, ncols=5)\r\nfor i in range(5):\r\n ax = plt.subplot(1, 5, i + 1)\r\n idx = np.random.randint(low = 0, high = len(H_dir))\r\n H_path = os.path.join(\"/content/text_images/train_test_images/upper_H/\",H_dir[idx])\r\n H_img = Image.open(H_path)\r\n H_img = np.array(H_img)\r\n plt.imshow(H_img)\r\n plt.axis(\"off\")\r\n\r\nfig.tight_layout(pad = 1.0)\r\n", "_____no_output_____" ] ], [ [ "##Train the OCR model", "_____no_output_____" ], [ "###Read in train/test set", "_____no_output_____" ] ], [ [ "batch_size = 32\r\nprint(IMG_HEIGHT)\r\nprint(IMG_WIDTH)\r\ndata_dir = \"/content/text_images/train_test_images/\"", "70\n50\n" ], [ "# https://www.tensorflow.org/tutorials/load_data/images\r\n\r\ntrain_ds = tf.keras.preprocessing.image_dataset_from_directory(\r\n data_dir,\r\n labels='inferred',\r\n label_mode='int',\r\n validation_split=0.2,\r\n subset=\"training\",\r\n shuffle=True,\r\n seed=123,\r\n image_size=(IMG_HEIGHT, IMG_WIDTH),\r\n batch_size=batch_size)", "Found 426000 files belonging to 67 classes.\nUsing 340800 files for training.\n" ], [ "val_ds = tf.keras.preprocessing.image_dataset_from_directory(\r\n data_dir,\r\n labels='inferred',\r\n label_mode='int',\r\n validation_split=0.2,\r\n subset=\"validation\",\r\n shuffle=True,\r\n seed=123,\r\n image_size=(IMG_HEIGHT, IMG_WIDTH),\r\n batch_size=batch_size)", "Found 426000 files belonging to 67 classes.\nUsing 85200 files for validation.\n" ], [ "# Save the class labels\r\nclass_names_df = pd.DataFrame({'class_names':train_ds.class_names})\r\nclass_names_df.to_csv('class_names_df.csv')\r\nfrom google.colab import files\r\nfiles.download(\"class_names_df.csv\")", "_____no_output_____" ], [ "# Take in one 32 image batch and display the first image and label\r\nfig, ax = plt.subplots(nrows=3, ncols=3)\r\nfor images, labels in train_ds.take(1):\r\n for i in range(9):\r\n ax = plt.subplot(3, 3, i + 1)\r\n plt.title(train_ds.class_names[labels[i]])\r\n plt.imshow(images[i].numpy().astype(\"uint8\"))\r\n #plt.title(class_names[labels[i]])\r\n plt.axis(\"off\")\r\nfig.tight_layout(pad = 1.0)", "_____no_output_____" ] ], [ [ "###Create and train the model", "_____no_output_____" ] ], [ [ "# Model source: https://www.tensorflow.org/tutorials/images/data_augmentation\r\nfrom tensorflow.keras import layers\r\n\r\nresize_and_rescale = tf.keras.Sequential([\r\n layers.experimental.preprocessing.Resizing(height=IMG_HEIGHT, width=IMG_WIDTH),\r\n layers.experimental.preprocessing.Rescaling(1./255, input_shape = (IMG_HEIGHT, IMG_WIDTH, 3))\r\n])", "_____no_output_____" ], [ "num_classes = len(os.listdir(\"/content/text_images/train_test_images\"))\r\n\r\nmodel = tf.keras.Sequential([\r\n resize_and_rescale,\r\n layers.Conv2D(32, 3, activation='relu'),\r\n layers.MaxPooling2D(),\r\n layers.Conv2D(32, 3, activation='relu'),\r\n layers.MaxPooling2D(),\r\n layers.Conv2D(32, 3, activation='relu'),\r\n layers.MaxPooling2D(),\r\n layers.Flatten(),\r\n layers.Dense(256, activation='relu'),\r\n layers.Dense(num_classes)\r\n])", "_____no_output_____" ], [ "model.compile(optimizer='adam',\r\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\r\n metrics=['accuracy'])", "_____no_output_____" ], [ "import tensorflow as tf\nfrom tensorflow.keras import datasets, layers, models", "_____no_output_____" ], [ "# Train the model. Takes about 15 minutes with GPU enabled\r\ntf.random.set_seed(1)\r\n\r\nepochs = 5\r\nhistory = model.fit(\r\n train_ds,\r\n validation_data=val_ds,\r\n epochs=epochs\r\n)", "Epoch 1/5\n10650/10650 [==============================] - 210s 19ms/step - loss: 0.3447 - accuracy: 0.9044 - val_loss: 0.0364 - val_accuracy: 0.9852\nEpoch 2/5\n10650/10650 [==============================] - 203s 19ms/step - loss: 0.0338 - accuracy: 0.9869 - val_loss: 0.0228 - val_accuracy: 0.9905\nEpoch 3/5\n10650/10650 [==============================] - 214s 20ms/step - loss: 0.0235 - accuracy: 0.9904 - val_loss: 0.0177 - val_accuracy: 0.9923\nEpoch 4/5\n10650/10650 [==============================] - 210s 20ms/step - loss: 0.0182 - accuracy: 0.9924 - val_loss: 0.0175 - val_accuracy: 0.9933\nEpoch 5/5\n10650/10650 [==============================] - 208s 20ms/step - loss: 0.0155 - accuracy: 0.9939 - val_loss: 0.0256 - val_accuracy: 0.9911\n" ], [ "# Save the model for predicting at a later date.\r\nmodel.save('content/model_cnn')\r\n!zip -r content/model_cnn.zip content/model_cnn\r\nfrom google.colab import files\r\nfiles.download(\"content/model_cnn.zip\")\r\nimport json\r\nmodel_hist = history.history\r\njson.dump(model_hist, open('model_history', 'w'))", "INFO:tensorflow:Assets written to: content/model1_20201218/assets\nINFO:tensorflow:Assets written to: /content/drive/MyDrive/Data Science MS Notes/Applied DL/Final Project/model1_20201218/assets\nupdating: content/model1_20201218/ (stored 0%)\nupdating: content/model1_20201218/saved_model.pb (deflated 89%)\nupdating: content/model1_20201218/assets/ (stored 0%)\nupdating: content/model1_20201218/variables/ (stored 0%)\nupdating: content/model1_20201218/variables/variables.data-00000-of-00001 (deflated 13%)\nupdating: content/model1_20201218/variables/variables.index (deflated 67%)\n" ] ], [ [ "### Optionally import previously trained model", "_____no_output_____" ] ], [ [ "model = tf.keras.models.load_model('/content/adl_final_project/model')\r\nmodel.summary()\r\nlabels = pd.read_csv(\"/content/adl_final_project/class_names_20201218.csv\")\r\nhistory = json.load(open('/content/adl_final_project/model_history', 'r'))", "Model: \"sequential_2\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nsequential (Sequential) (None, 70, 50, 3) 0 \n_________________________________________________________________\nconv2d (Conv2D) (None, 68, 48, 32) 896 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 34, 24, 32) 0 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 32, 22, 32) 9248 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 16, 11, 32) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 14, 9, 32) 9248 \n_________________________________________________________________\nmax_pooling2d_2 (MaxPooling2 (None, 7, 4, 32) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 896) 0 \n_________________________________________________________________\ndense (Dense) (None, 256) 229632 \n_________________________________________________________________\ndense_1 (Dense) (None, 67) 17219 \n=================================================================\nTotal params: 266,243\nTrainable params: 266,243\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "history_df = pd.DataFrame(history)\r\nplt.plot(history_df['accuracy'], label='Train Accuracy')\r\nplt.plot(history_df['val_accuracy'], label = 'Val. Accuracy')\r\nplt.xlabel('Epoch')\r\nplt.ylabel('Accuracy')\r\nplt.ylim([0.5, 1])\r\nplt.legend(loc='lower right')\r\nplt.title(\"Training vs. Validation Accuracy\")\r\nplt.show()", "_____no_output_____" ], [ "# Model has a high accuracy\r\nval_loss, val_acc = model.evaluate(val_ds, verbose=2)", "2663/2663 - 31s - loss: 0.0225 - accuracy: 0.9917\n" ] ], [ [ "#### Predict on one image", "_____no_output_____" ] ], [ [ "# Use the component functions of get_image_text to show how one column cell\r\n# is broken up into its hierarchy of images\r\n\r\nmy_img=processed_imgs[0][1].get('col0')\r\n\r\ncontour_l = pdf_text_extraction.get_char_contours(img=my_img)\r\nbb_coord_l = pdf_text_extraction.make_bb_coord_l(contour_l=contour_l, img=my_img, \r\n IMG_HEIGHT=IMG_HEIGHT)\r\nmax_height = np.amin([pdf_text_extraction.char_max_height(bb_coords=bb_coord_l, IMG_HEIGHT=IMG_HEIGHT),\r\n IMG_HEIGHT])\r\nmax_width = np.amin([pdf_text_extraction.char_max_width(bb_coords=bb_coord_l, IMG_WIDTH=IMG_WIDTH),\r\n IMG_WIDTH])\r\n\r\nisolated_text_example=pdf_text_extraction.sort_bb_coords(\r\n bb_coords=bb_coord_l,img=my_img, \r\n max_height=max_height,max_width=max_width,\r\n IMG_HEIGHT=70)", "/usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py:3373: RuntimeWarning: Mean of empty slice.\n out=out, **kwargs)\n/usr/local/lib/python3.6/dist-packages/numpy/core/_methods.py:170: RuntimeWarning: invalid value encountered in double_scalars\n ret = ret.dtype.type(ret / rcount)\n" ], [ "# Show nested structure of column cell -> text line -> line word -> word letter\r\nH_dir = os.listdir(\"/content/text_images/train_test_images/upper_H/\")\r\n\r\nimg_titles = ['Column Cell','Text Line','Line Word','Word Letter']\r\nimg_dict = {'Column Cell':my_img,\r\n 'Text Line':isolated_text_example.get('whole_line0'),\r\n 'Line Word':isolated_text_example.get('line_words0')[0],\r\n 'Word Letter':isolated_text_example.get('line_words_letters0')[0][0]}\r\n\r\nfig, ax = plt.subplots(nrows=4, ncols=1, figsize = (10,10))\r\nfor i, t in enumerate(img_titles):\r\n ax = plt.subplot(4, 1, i + 1)\r\n text_img = img_dict.get(t)\r\n plt.imshow(text_img)\r\n plt.title(t)\r\nfig.tight_layout(pad = 1.0)", "_____no_output_____" ] ], [ [ "A prediction test shows that the model is not 100% accurate on real world data. The model has trouble telling the difference between lowercase and uppercase versions of letters that have similar shapes (e.g. 'c' and 'C', 'o' and 'O'). Other problem shapes are lowercase 'L', numeric '1', and lowercase 'I', given their similar shapes.", "_____no_output_____" ] ], [ [ "# Demonstration of predicting the labels of the letters in a single word\r\nexample_batch=pdf_text_extraction.assemble_pred_batch(isolated_text_example.get('line_words_letters0')[0], \r\n 70, 50)\r\n\r\npreds=model.predict(example_batch)\r\nscores = tf.nn.softmax(preds)\r\npred_labels=labels.class_names.str.extract('(\\w$)').loc[np.argmax(scores, axis=1)]\r\n\r\ntrue_labels = 'Richard'\r\n\r\nfig, ax = plt.subplots(nrows=1, ncols=len(pred_labels), figsize = (15,15))\r\nfor i in range(len(pred_labels)):\r\n ax = plt.subplot(1, len(pred_labels), i + 1)\r\n true_label = true_labels[i]\r\n pred_label = pred_labels.iloc[i,0]\r\n if true_label==pred_label:\r\n label_match = 'True'\r\n else:\r\n label_match = 'False'\r\n title = 'True label: '+true_label+'\\nPredicted label: '+pred_label+'\\nCorrect prediction: '+label_match\r\n plt.title(title)\r\n plt.imshow(isolated_text_example.get('line_words_letters0')[0][i])\r\n\r\nfig.tight_layout(pad = 1.0)\r\n", "_____no_output_____" ] ], [ [ "## Extract PDF text and convert to data frame", "_____no_output_____" ], [ "Getting from the processed PDF image to a DataFrame takes a few additional steps:\r\n\r\n* `get_image_text` isolates the lines, words, and letters in each column cell and returns the softmax predicted label for each letter image in a series of lists.\r\n* `reorganize_doc_text` takes in the previous output and converts it into a dictionary format. The feature names for the text are inferred based on the line order and anticipated text formatting through regular expressions. For example, the address line for city, state, and zip code expects a 5-digit number at the end of the line, so a regular expression is used to identify it.\r\n* `doc_text_to_dataframe` converts the dictionary into a data frame for easier analysis.\r\n\r\n\r\n\r\n", "_____no_output_____" ] ], [ [ "doc_text = pdf_text_extraction.get_image_text(\r\n processed_imgs=processed_imgs, \r\n IMG_HEIGHT=70, IMG_WIDTH=50,\r\n model=model, labels=labels)", "\rExtracting image text (1/5)" ], [ "doc_text_reorganized=pdf_text_extraction.reorganize_doc_text(doc_text=doc_text)", "_____no_output_____" ], [ "doc_df=pdf_text_extraction.doc_text_to_dataframe(doc_text_reorganized)", "_____no_output_____" ], [ "doc_df.head()", "_____no_output_____" ] ], [ [ "## Conclusion\r\nThe OCR model performed fairly well on the PDF images based on visual inspection of the results. As previously mentioned, there are some specific characters that the model confuses. This could be corrected by adding additional training data for frequently incorrect letters or adding additional layers to the model. The validation accuracy of the model was already very high, however, so it may be the case that the training data does not adequately represent the extracted images from the PDF. Perhaps additional data augmentation (random crops, rotation, etc.) could lead to better performance gains on the PDF images. Post-prediction, rules-based text cleanup might help correct some of the mistakes as well. For instance, convert predicted uppercase letters in the middle of words to lowercase (`COCCOOn` -> `Coccoon`).", "_____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" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
4a51760a030a86ec53b09f8aab8045fd464761fb
213,784
ipynb
Jupyter Notebook
cryptolytic/notebooks/second.ipynb
Lambda-School-Labs/cryptolytic-ds
b58b6eb2b82a404f9d2d468e706d49d9c5999f21
[ "MIT" ]
13
2019-10-10T21:01:23.000Z
2020-06-05T11:18:31.000Z
cryptolytic/notebooks/second.ipynb
ross-fisher/cryptolytic-ds
1539ae7311a622035d631058ebe47e7c697e3c11
[ "MIT" ]
3
2019-12-18T16:46:48.000Z
2020-01-09T21:47:48.000Z
cryptolytic/notebooks/second.ipynb
ross-fisher/cryptolytic-ds
1539ae7311a622035d631058ebe47e7c697e3c11
[ "MIT" ]
10
2019-10-15T15:30:25.000Z
2020-05-11T22:07:52.000Z
80.430399
89,444
0.765698
[ [ [ "%cd ../..\n%run cryptolytic/notebooks/init.ipynb\n\nimport pandas as pd\nimport cryptolytic.util.core as util\nimport cryptolytic.start as start\nimport cryptolytic.viz.plot as plot\nimport cryptolytic.data.sql as sql\nimport cryptolytic.data.historical as h\nimport cryptolytic.model as m\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\n\nfrom matplotlib.pylab import rcParams\nfrom IPython.core.display import HTML\nfrom pandas.plotting import register_matplotlib_converters # to stop a warning message\n\n\nohclv = ['open', 'high', 'close', 'low', 'volume']\nplt.style.use('ggplot')\nrcParams['figure.figsize'] = 20,7\nstart.init()\nregister_matplotlib_converters()\n\n\n# Make math readable\nHTML(\"\"\"\n<style>\n.MathJax {\n font-size: 2rem;\n}\n</style>\"\"\")", "/home/me/Documents/Git/Lambda-School-Labs/cryptolytic-ds\nUsing matplotlib backend: Qt5Agg\nPopulating the interactive namespace from numpy and matplotlib\n" ], [ "df = sql.get_some_candles(\n info={'start':1574368000, 'end':1579046400, 'exchange_id':'hitbtc',\n 'trading_pair':'btc_usd', 'period':300}, n=5e4)\ndf2 = df.copy() # mutable copy\ntrain_test_pivot = int(len(df)*0.8)\ndf['diff'] = df['high'] - df['low']", "_____no_output_____" ] ], [ [ "# Considerations for time series\n- Understanding temporal behavior of data: seasonality, stationarity\n- Identifying underlying distributions and nature of temporal process producing data\n- Estimation of past, present, and future values\n - filtering vs forecasting\n- Classification of time series (for example, arrhythmia in heart data)\n- Anomaly detection of outlier points within time series", "_____no_output_____" ] ], [ [ "from scipy.stats import pearsonr\n#a = m.get_by_time(df, '2019-11-22', '2019-11-26')\n#b = m.get_by_time(df, '2019-11-26', '2019-11-28')", "_____no_output_____" ], [ "train = df\nparams = {\n 'level' : 'smooth trend', \n 'cycle' : False,\n 'seasonal' : None\n}", "_____no_output_____" ], [ "import statsmodels as sm\n\nutil.bdir(sm.tsa)\nutil.bdir(sm.tsa.tsatools)\nutil.bdir(sm.tsa.stattools)", "_____no_output_____" ], [ "# statsmodels.api\nimport statsmodels.api as sm \nimport statsmodels as sm", "_____no_output_____" ], [ "candles_in_day = int(1440 / 5)\ncandles_in_day", "_____no_output_____" ] ], [ [ "# Hidden Markov Models (HMMs)\nType of state space model: Observations are an indicator of underlying state\n\nMarkov process: past doesn't matter if preset status is known\n\nParameter estimation: Baum-Welch Algorithm\n\nSmootheing/state labeling: Viterbi algorithm\n\nThere is an unobservable state that is affecting the output, along with the input\n\n$x_{t-1} -> x_{t} -> x_{t+1}$\n\n$y_{t-1} -> y_{t} -> y_{t+1}$", "_____no_output_____" ], [ "# Baum-Welch Algorithm for Determining Parameters\n- Expectation maximization parameter estimation:\n- - Initialize parameters (with informative priors or randomly)\n- - Em iterations\n- - - Compute the expectation of the log likelihood given the data\n- - Exit when desired convergence is reached\n- - - Choose the parameters that maximize the log likelihood expectation\n- Guarantee that the likelihood increases with each iteration (Forward-Backward Expectation Maximization Algorithm)\n- - Figure out your likelihood expectation is given the data, that's the expectation step and the maximization step\n- is to update the estimates of your parameters to maximize that likelihood given that expression of that likelihood,\n and then repeat\n- BUT\n- - converges to a local maximum not a global maximum\n- - can overfit the data\n\nProblem\nA : Transition Matrix probability, how likely x to transition to another state at that timestep. Gives a matrix, saying how likely for example to go from state i to state k, etc.\nB : What is the probability of seeing a value at y, given a particular x.\n\n$\\theta = (A,B,\\pi)$\n\nForward Step\n\n$\\pi$ : Priors, telling how likely you are to begin in a particular state\n\n$\\alpha_i(t) = P(Y_1 = y_1,...,Y_t = y_t, X_t = i |\\theta) \\\\\n\\alpha_i(1) = \\pi_ib_i(y_1)\\\\\n\\alpha_i(t+1) = b_i(y_{t+1})\\sum_{j=1}^N\\alpha_j(t)\\alpha_{ji}\n$\n\nBackward Step\nHow probable is it, being conditionod on being in state i at time t, how probable is it to see the sequence from t+1 to T.\n\n\n$\n\\beta_i(t) = P(Y_{t+1}=y_{t+1},...,Y_T=y_T|X_t=i,\\theta)\\\\\n\\beta_i(T) = 1\\\\\n\\beta_i(t)=\\sum_{j=1}^N\\beta_j(t+1)a_{ij}b_j(y_{t+1}\n$\n\nThen there are $\\gamma_i$ the probabliity of being in state i at time t given all the observed data and parameters $\\theta$\n$\\gamma_i(t) = P(X_t=i|Y,\\theta)=\\frac{P(X_t=i|Y,\\theta)}{P(Y|\\theta)}=\\frac{\\alpha_i(t)\\beta_i(t)}{\\sum_{j=1}^N\\alpha_j(t)\\beta_j(t)}$\n\n$\\xi_{ij}(t)=P(X_t=i,X_{t+1}=j|Y,\\theta)$ \n\n- Prior, how likely at the beginning of a sequennce to be at any given starting state\n$$\\pi_i^*=\\gamma_i(1)$$\n\n- How likely to transition from state i to state j at a particular timestep\n$$\\alpha_{ij}^*\\frac{\\sum_{t=1}^{T-1}\\xi_ij(t)}{\\sum_{t=1}^{T-1}\\gamma_i(t)}$$\n\n- How likely to see a observed value, given being in state i\n$$b_i^*(v_k) = \\frac{ \\sum_{t=1}^T1_{y_t=v_k}\\gamma_i(t) }{\\sum_{t=1}^T\\gamma_i(t)}$$", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nplt.plot(df.index, df.close)", "_____no_output_____" ], [ "!pip -q install hmmlearn\ndf_sub = df.iloc[:int(len(df)/4)]\nfrom hmmlearn import hmm\n# HMM Learn\nvals = np.expand_dims(df_sub.close.values, 1) # requires two dimensions for the input\nn_states = 2\nmodel = hmm.GaussianHMM(n_components=n_states, n_iter=100, random_state=100).fit(vals)\nhidden_states = model.predict(vals)", "_____no_output_____" ], [ "# Predicts two different states for the thing to be in. Kind of mirrors how \nhidden_states", "_____no_output_____" ], [ "np.unique(hidden_states)", "_____no_output_____" ], [ "# There should be 2 distinct states, a Low flow state, high flow state\nplt.plot(df_sub.index, df_sub.close)\n_min = df_sub.close.min()\n_max = df_sub.close.max()\nh_min = hidden_states.min()\nh_max = hidden_states.max()\n\nplt.title('2 State HMM')\nplt.plot(df_sub.index,[np.interp(x,[h_min,h_max], [_min,_max]) for x in hidden_states])", "_____no_output_____" ], [ "def fitHMM(vals, n_states):\n vals = np.reshape(vals, [len(vals), 1])\n \n # Fit Gaussian HMM to 0\n model = hmm.GaussianHMM(n_components=n_states, n_iter=100).fit(vals)\n \n # classify each observation as state 0 or 1\n hidden_states = model.predict(vals)\n \n # fit HMM parameters\n mus = np.squeeze(model.means_)\n sigmas = np.squeeze(np.sqrt(model.covars_))\n # Transition matrix which describes how likely you are to go from state i to state j\n transmat = np.array(model.transmat_)\n print(mus)\n print(sigmas)\n \n # reorder parameters in ascending order of mean of underlying distributions\n idx = np.argsort(mus)\n mus = mus[idx]\n sigmas = sigmas[idx]\n transmat = transmat[idx, :][:, idx]\n \n state_dict = {}\n states = [i for i in range(n_states)]\n for i in idx:\n state_dict[i] = states[idx[i]]\n \n relabeled_states = [state_dict[h] for h in hidden_states]\n return (relabeled_states, mus, sigmas, transmat, model)", "_____no_output_____" ], [ "hidden_states, mus, sigmas, transmat, model = fitHMM(df.close.values, 3)", "[8048.85589562 7407.51028877 7127.95733329]\n[259.1329164 93.17233082 146.81259604]\n" ], [ "hidden_states", "_____no_output_____" ], [ "np.unique(hidden_states, return_counts=True)", "_____no_output_____" ], [ "rcParams['figure.figsize'] = 20,7\ndef plot_states(ts_vals, states, time_vals):\n fig, ax1 = plt.subplots()\n\n color = 'tab:red'\n ax1.set_ylabel('Data', color=color)\n ax1.plot(time_vals, ts_vals, color=color)\n ax1.tick_params(axis='y', labelcolor=color)\n\n ax2 = ax1.twinx() \n color = 'tab:blue'\n ax2.set_ylabel('Hidden state', color=color) \n ax2.plot(time_vals,states, color=color)\n ax2.tick_params(axis='y', labelcolor=color)\n\n plt.title(f'{len(np.unique(states))} State Model')\n fig.tight_layout() \n plt.show()\n \nplot_states(df.close, hidden_states, df.index)", "_____no_output_____" ], [ "x = np.array([hidden_states]).T\nm = np.array([mus])\nprint(np.shape(x), np.shape(m))\nprint(np.shape(m.T), np.shape(x.T))\nz = np.matmul(x, m)", "(15595, 1) (1, 3)\n(3, 1) (1, 15595)\n" ] ], [ [ "# Comparing the states", "_____no_output_____" ] ], [ [ "# The averages for the three states\nmus", "_____no_output_____" ], [ "# In the high state, variance is highest, and it's lowest in the middle transitioning state. \nsigmas", "_____no_output_____" ], [ "# Transmat gives teh probability of one state transition to another. \n# The values are very low because the number of data points is large.\nrcParams['figure.figsize'] = 9, 5\nimport seaborn as sns\nsns.heatmap(transmat)", "_____no_output_____" ], [ "# Can see from here though that the probability of transitioning \n# from the state 1 to state 3 and vice versa is low, they are more\n# likely to transition to the in-between state instead. \ntransmat", "_____no_output_____" ], [ "rcParams['figure.figsize'] = 20, 7", "_____no_output_____" ], [ "len(z[:, 0]), len(z[0])", "_____no_output_____" ] ], [ [ "# Time series feature generation\nTime series features: catch22 canonical set\nhttps://arxiv.org/pdf/1901.10200.pdf\nxgboost \nGood at time series analysis\nClustering ", "_____no_output_____" ] ], [ [ "df", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
4a5186478a63ecfc8a8398877c380666cd4ee2a5
16,430
ipynb
Jupyter Notebook
notebooks/07_model_linear.ipynb
Marcelobbr/fraud_detection
dd2f81e1ca1325cee10b21fb40b4ec3612420069
[ "MIT" ]
null
null
null
notebooks/07_model_linear.ipynb
Marcelobbr/fraud_detection
dd2f81e1ca1325cee10b21fb40b4ec3612420069
[ "MIT" ]
1
2021-07-27T22:43:24.000Z
2021-07-27T22:43:24.000Z
notebooks/07_model_linear.ipynb
Marcelobbr/fraud_detection
dd2f81e1ca1325cee10b21fb40b4ec3612420069
[ "MIT" ]
null
null
null
31.535509
228
0.434449
[ [ [ "import json\nimport os\nimport sys\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\nfrom pprint import pprint\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.impute import SimpleImputer as Imputer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV\n\nwarnings.filterwarnings('ignore')", "_____no_output_____" ], [ "sys.path.append(os.path.join('..', 'src'))", "_____no_output_____" ], [ "import importlib\nimport model\nimportlib.reload(model)\n\nfrom model import get_model_params, timer, measure_prediction_time, apply_ml_model, save_model_parameters, save_model_metrics", "_____no_output_____" ] ], [ [ "# set model parameters and capture data", "_____no_output_____" ] ], [ [ "# scoring = 'neg_mean_squared_error'\nscoring = 'f1'\n\ninputs = os.path.join('..', 'data', '03_processed')\nmodels_reports = os.path.join('..', 'data', '04_models')\nmodel_outputs = os.path.join('..', 'data', '05_model_output')\nreports = os.path.join('..', 'data', '06_reporting')\n\nX_train = pd.read_csv(os.path.join(inputs, 'X_train.csv'), index_col='id')\nX_train_onehot = pd.read_csv(os.path.join(inputs, 'X_train_onehot.csv'), index_col='id')\ny_train = pd.read_csv(os.path.join(inputs, 'y_train.csv'), index_col='id')\n\ndata_list = [X_train, X_train_onehot, y_train]\n\nfor df in data_list:\n print(df.shape)", "(7000, 46)\n(7000, 158)\n(7000, 1)\n" ], [ "X_train_onehot.head()", "_____no_output_____" ] ], [ [ "# Machine Learning", "_____no_output_____" ], [ "convergence warning: https://stackoverflow.com/questions/20681864/lasso-on-sklearn-does-not-converge", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import ElasticNet\nfrom sklearn.linear_model import LogisticRegression", "_____no_output_____" ], [ "ml_dict = {}\n\n# Specify the hyperparameter space\n# if target_type == 'regression':\n# parameters = {\n# 'model__alpha': np.linspace(0.2, 1, 5), \n# 'model__l1_ratio': np.linspace(0, 1, 5),\n# 'model__random_state':[42]\n# }\n# ml_model = ElasticNet()\n# # set tol, default is 1e-4\n# do_transform_label = 'log'\n# elif target_type == 'binary':\nc_space = np.logspace(-5, 1, 5)\nparameters = {\n'model__C': c_space, \n'model__penalty': ['l2'],\n'model__random_state':[42]\n}\nml_model = LogisticRegression()\ndo_transform_label = None\n\n# key = 'standard'", "_____no_output_____" ] ], [ [ "## test with different preprocessing steps\nThere are 2 different X_sets: On X_train_onehot, I applied one-hot encoding, while on X_train I applied Ordinal Encoding. The former is aimed at linear regression models, and the later is generally used for tree models.\n\nOn 'column' parameter, I am able to choose column groups. For instance, I might exclude collinear variables obtained from the VIF function applied on notebook 5. That is useful for linear regression models.", "_____no_output_____" ], [ "```python\ntreat_collinearity = False, do_build_polynomals=False, do_treat_skewness=False\n```", "_____no_output_____" ] ], [ [ "model_type = 'reg'\nml_dict[model_type] = {}\ncolumns = X_train_onehot.columns\n\nclf, ml_dict[model_type]['train_time'], ml_dict[model_type]['prediction_time'] = apply_ml_model(\n X_train_onehot, y_train, columns, ml_model, parameters, scoring,\n do_build_polynomals=False, \n do_treat_skewness=False,\n imputation=Imputer(strategy='median'), scaler=StandardScaler(),\n )\nml_dict[model_type]['best_params'], ml_dict[model_type]['best_score'] = get_model_params(clf, scoring)\npprint(ml_dict)\n\nsave_model_parameters(models_reports, model_type, clf)\nsave_model_metrics(model_outputs, model_type, ml_dict)", "test type: False\n{'reg': {'best_params': {'model__C': 10.0,\n 'model__penalty': 'l2',\n 'model__random_state': 42},\n 'best_score': 0.12536338274396502,\n 'prediction_time': 0.0003,\n 'train_time': 6.464915}}\n" ] ], [ [ "```python\ntreat_collinearity = True, do_build_polynomals=False, do_treat_skewness=False,\n```", "_____no_output_____" ] ], [ [ "model_type = 'reg_nocol'\nml_dict[model_type] = {}\n\n# columns_nocol = dfs_dict['X_train_oh_nocol'].columns.to_list()\n\nclf, ml_dict[model_type]['train_time'], ml_dict[model_type]['prediction_time'] = apply_ml_model(\n X_train_onehot, y_train, columns, ml_model, parameters, scoring,\n do_build_polynomals=False, \n do_treat_skewness=False,\n imputation=Imputer(strategy='median'), scaler=StandardScaler(),\n )\nml_dict[model_type]['best_params'], ml_dict[model_type]['best_score'] = get_model_params(clf, scoring)\npprint(ml_dict)\n\nsave_model_parameters(models_reports, model_type, clf)\nsave_model_metrics(model_outputs, model_type, ml_dict)", "test type: False\n{'reg': {'best_params': {'model__C': 10.0,\n 'model__penalty': 'l2',\n 'model__random_state': 42},\n 'best_score': 0.12536338274396502,\n 'prediction_time': 0.0003,\n 'train_time': 6.464915},\n 'reg_nocol': {'best_params': {'model__C': 10.0,\n 'model__penalty': 'l2',\n 'model__random_state': 42},\n 'best_score': 0.12536338274396502,\n 'prediction_time': 0.0003999,\n 'train_time': 5.743999}}\n" ] ], [ [ "I might use the alternative encoding just to demonstrate the impact on the score.", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a518a3d1b1b9799fc8965cb83a5627c25bdd486
666
ipynb
Jupyter Notebook
Naive Bayes and Decision Tree/.ipynb_checkpoints/Decision Tree-checkpoint.ipynb
Yaki666/ML-DA
9814c6390fc6e29cd046694182c217ce0dd2571e
[ "MIT" ]
null
null
null
Naive Bayes and Decision Tree/.ipynb_checkpoints/Decision Tree-checkpoint.ipynb
Yaki666/ML-DA
9814c6390fc6e29cd046694182c217ce0dd2571e
[ "MIT" ]
null
null
null
Naive Bayes and Decision Tree/.ipynb_checkpoints/Decision Tree-checkpoint.ipynb
Yaki666/ML-DA
9814c6390fc6e29cd046694182c217ce0dd2571e
[ "MIT" ]
null
null
null
16.65
34
0.518018
[ [ [ "# COSC74/174 Decision Tree\n", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
4a519c03bca368068e19c608885e0a4f1ed14de7
65,796
ipynb
Jupyter Notebook
mcmc-pymc3-101/notebooks/3.0-smm-golf.ipynb
smu095/presentations
1de1523401cf4453af3ebf36f01f0afae1d0daa2
[ "MIT" ]
2
2020-02-17T11:28:33.000Z
2020-02-17T18:55:31.000Z
mcmc-pymc3-101/notebooks/3.0-smm-golf.ipynb
smu095/presentations
1de1523401cf4453af3ebf36f01f0afae1d0daa2
[ "MIT" ]
null
null
null
mcmc-pymc3-101/notebooks/3.0-smm-golf.ipynb
smu095/presentations
1de1523401cf4453af3ebf36f01f0afae1d0daa2
[ "MIT" ]
null
null
null
106.985366
45,973
0.847802
[ [ [ "# 0. Setup", "_____no_output_____" ] ], [ [ "# Imports\nimport arviz as az\nimport io\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport pymc3 as pm\nimport scipy\nimport scipy.stats as st\nimport theano.tensor as tt\n\n\n# Helper functions\ndef plot_golf_data(data, ax=None):\n \"\"\"Utility function to standardize a pretty plotting of the golf data.\"\"\"\n if ax is None:\n _, ax = plt.subplots(figsize=(10, 6))\n bg_color = ax.get_facecolor()\n ax.vlines(\n data[\"distance\"],\n ymin=data[\"p_hat\"] - data[\"se\"],\n ymax=data[\"p_hat\"] + data[\"se\"],\n label=None,\n )\n ax.plot(data[\"distance\"], data[\"p_hat\"], 'o', mfc=bg_color, label=None)\n \n\n ax.set_xlabel(\"Distance from hole\")\n ax.set_ylabel(\"Proportion of putts made\")\n ax.set_ylim(bottom=0, top=1)\n\n ax.set_xlim(left=0)\n ax.grid(True, axis='y', alpha=0.7)\n return ax", "_____no_output_____" ] ], [ [ "# 1. Introduction", "_____no_output_____" ], [ "The following example is based on a study by [Gelman and Nolan (2002)](http://www.stat.columbia.edu/~gelman/research/published/golf.pdf), where they use Bayesian methods to estimate the accuracy of pro golfers with respect to putting.\n\nThe data comes from Don Berry's textbook *Statistics: A Bayesian Perspective* (1995) and describes the number of tries and successes of golf putting from a range of distances.\n\nThis example is also featured in the case studies sections of the [Stan](https://mc-stan.org/users/documentation/case-studies/golf.html) and [PyMC3](https://docs.pymc.io/notebooks/putting_workflow.html) documentation. This notebook is based heavily on these two sources.", "_____no_output_____" ], [ "## 1.1 Data", "_____no_output_____" ] ], [ [ "# Putting data from Berry (1995)\ndata = pd.read_csv(\"golf_1995.csv\", sep=\",\")", "_____no_output_____" ], [ "data[\"p_hat\"] = data[\"successes\"] / data[\"tries\"]\ndata", "_____no_output_____" ] ], [ [ "The authors start by estimating the standard error of the estimated probability of success for each distance in order to get a sense of how closely the model should be expected to fit the data, given by\n\n$SE(\\hat{p}_i) = \\sqrt{\\dfrac{\\hat{p}_i(1 - \\hat{p}_i)}{n}}$", "_____no_output_____" ] ], [ [ "def se(data):\n \"\"\"Calculate standard error of estimator.\"\"\"\n p_hat = data[\"p_hat\"]\n n = data[\"tries\"]\n return np.sqrt(p_hat * (1 - p_hat) / n)\n\ndata[\"se\"] = se(data)", "_____no_output_____" ], [ "ax = plot_golf_data(data)\nax.set_title(\"Overview of data from Berry (1995)\")\nplt.show()", "_____no_output_____" ] ], [ [ "# 2. Baseline: Logit model", "_____no_output_____" ], [ "As a baseline model, we fit a simple logistic regression to the data, where the probability is give as a function of the distance $x_j$ from the hole. The data generating process for $y_j$ is assumed to be a [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution):\n\n$$y_j \\sim \\text{Binomial}(n_j, p_j),\\\\\np_j = \\dfrac{1}{1 + e^{-(a + bx_j)}}, \\quad \\text{for} j = 1 \\ldots J,\\\\\na, b \\sim \\text{Normal}(0, 1)$$ ", "_____no_output_____" ] ], [ [ "def logit_model(data):\n \"\"\"Logistic regression model.\"\"\"\n with pm.Model() as logit_binomial:\n # Priors\n a = pm.Normal('a', mu=0, tau=1)\n b = pm.Normal('b', mu=0, tau=1)\n\n # Logit link\n link = pm.math.invlogit(a + b*data[\"distance\"])\n \n # Likelihood\n success = pm.Binomial(\n 'success',\n n=data[\"tries\"],\n p=link,\n observed=data[\"successes\"]\n )\n return logit_binomial\n\n# Visualise model as graph\npm.model_to_graphviz(logit_model(data))", "_____no_output_____" ], [ "# Sampling from posterior\nwith logit_model(data):\n logit_trace = pm.sample(10000, tune=1000)", "_____no_output_____" ], [ "# Retrieving summaries from models\npm.summary(logit_trace)", "_____no_output_____" ], [ "# Plotting posterior distributions of a, b\npm.plot_posterior(logit_trace)\nplt.show()", "_____no_output_____" ] ], [ [ "Our estimates seem to make sense. As the distance $x_j \\rightarrow 0$, it seems intuitive that the probability of success is high. Conversely, if $x_j \\rightarrow \\infty$, the probability of success should be close to zero.", "_____no_output_____" ] ], [ [ "p_test = lambda x: scipy.special.expit(2.224 - 0.255*x)\nprint(f\" x = 0 --> p = {p_test(0)}\")\nprint(f\" x = really big --> p = {p_test(10**5)}\")", "_____no_output_____" ] ], [ [ "## 2.1 Baseline: Posterior predictive samples", "_____no_output_____" ], [ "We plot the our probability model by drawing 50 samples from the posterior distribution of $a$ and $b$ and calculating the inverse logit (expit) for each sample:", "_____no_output_____" ] ], [ [ "# Plotting\nax = plot_golf_data(data)\ndistances = np.linspace(0, data[\"distance\"].max(), 200)\n\n# Plotting individual predicted sigmoids for 50 random draws of (a, b)\nfor idx in np.random.randint(0, len(logit_trace), 50):\n post_logit = scipy.special.expit(logit_trace[\"a\"][idx] + logit_trace[\"b\"][idx] * distances)\n ax.plot(\n distances,\n post_logit,\n lw=1,\n color=\"tab:orange\",\n alpha=.7,\n )\n \n# Plotting average prediction over all sampled (a, b)\nlogit_average = scipy.special.expit(\n logit_trace[\"a\"].reshape(-1, 1) + logit_trace[\"b\"].reshape(-1, 1) * distances,\n).mean(axis=0)\n\nax.plot(\n distances,\n logit_average,\n label = \"Inverse logit mean\",\n color=\"k\",\n linestyle=\"--\",\n)\n\nax.set_title(\"Fitted logistic regression\")\nax.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "We see that:\n* The posterior uncertainty is relatively low.\n* The fit is OK, but we tend to overestimate the difficulty of making short putts and underestimate the probability of making long puts. ", "_____no_output_____" ], [ "# 3. Modelling from first principles", "_____no_output_____" ], [ "Not satisfied with the logistic regression, we contact a golf pro who also happens to have a background in mathematics. She suggests that as an alternative, we could build a model from first principles and fit it to the data.\n\nShe provides us with the following sketch (from the [Stan case study](https://mc-stan.org/users/documentation/case-studies/golf.html)):\n> The graph below shows a simplified sketch of a golf shot. The dotted line represents the angle within which the ball of radius r must be hit so that it falls within the hole of radius R. This threshold angle is $sin^{−1}\\Bigg(\\dfrac{R−r}{x}\\Bigg)$. The graph, which is not to scale, is intended to illustrate the geometry of the ball needing to go into the hole. \n\n![](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABUAAAAGACAYAAABsocicAAAEGWlDQ1BrQ0dDb2xvclNwYWNlR2VuZXJpY1JHQgAAOI2NVV1oHFUUPrtzZyMkzlNsNIV0qD8NJQ2TVjShtLp/3d02bpZJNtoi6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lUmkQUztTE6mx1EEPh7OmdqBtAvv8HdWpbrJS6tJj3n0CWdM6busNzRV3S9KTYhqvNiqWmuroiKgYhshMjmhTh9ptWhsF7970j/SbMrsPE1suR5z7DMC+P/Hs+y7ijrQAlhyAgccjbhjPygfeBTjzhNqy28EdkUh8C+DU9+z2v/oyeH791OncxHOs5y2AtTc7nb/f73TWPkD/qwBnjX8BoJ98VQNcC+8AAEAASURBVHgB7N0J3FRz///xTyoS9x3SJpGKpEWL0I4slaRFUUjdiizZKVsiktBiLRFJsi+torQqUalUKrQgFaW677Qp/t7f/+9cpmmuM3Nd11zXzJx5fR+PMcs5c873PM9xNfOZz/fzzffX381oCCCAAAIIIIAAAggggAACCCCAAAIIIIBAAAUOCuAxcUgIIIAAAggggAACCCCAAAIIIIAAAggggIATIADKhYAAAggggAACCCCAAAIIIIAAAggggAACgRUgABrYU8uBIYAAAggggAACCCCAAAIIIIAAAggggAABUK4BBBBAAAEEEEAAAQQQQAABBBBAAAEEEAisAAHQwJ5aDgwBBBBAAAEEEEAAAQQQQAABBBBAAAEECIByDSCAAAIIIIAAAggggAACCCCAAAIIIIBAYAUIgAb21HJgCCCAAAIIIIAAAggggAACCCCAAAIIIEAAlGsAAQQQQAABBBBAAAEEEEAAAQQQQAABBAIrQAA0sKeWA0MAAQQQQAABBBBAAAEEEEAAAQQQQAABAqBcAwgggAACCCCAAAIIIIAAAggggAACCCAQWAECoIE9tRwYAggggAACCCCAAAIIIIAAAggggAACCBAA5RpAAAEEEEAAAQQQQAABBBBAAAEEEEAAgcAKEAAN7KnlwBBAAAEEEEAAAQQQQAABBBBAAAEEEECAACjXAAIIIIAAAggggAACCCCAAAIIIIAAAggEVoAAaGBPLQeGAAIIIIAAAggggAACCCCAAAIIIIAAAgRAuQYQQAABBBBAAAEEEEAAAQQQQAABBBBAILACBEADe2o5MAQQQAABBBBAAAEEEEAAAQQQQAABBBAgAMo1gAACCCCAAAIIIIAAAggggAACCCCAAAKBFSAAGthTy4EhgAACCCC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QQAABBBBAAAEEEEAAAQQQQCCwAgRAA3tqOTAEEEAAAQQQQAABBBBAAAEEEEAAAQQQIADKNYAAAggggAACCCCAAAIIIIAAAggggAACgRUgABrYU8uBIYAAAggggAACCCCAAAIIIIAAAggggAABUK4BBBBAAAEEEEAAAQQQQAABBBBAAAEEEAisAAHQwJ5aDgwBBBBAAAEEEEAAAQQQQAABBBBAAAEECIByDSCAAAIIIIAAAggggAACCCCAAAIIIIBAYAUIgAb21HJgCCCAAAIIIIAAAggggAACCCCAAAIIIEAAlGsAAQQQQAABBBBAAAEEEEAAAQQQQAABBAIrQAA0sKeWA0MAAQQQQAABBBBAAAEEEEAAAQQQQAABAqBcAwgggAACCCCAAAIIIIAAAggggAACCCAQWAECoIE9tRwYAggggAACCCCAAAIIIIAAAggggAACCBAA5RpAAAEEEEAAAQQQQAABBBBAAAEEEEAAgcAKEAAN7KnlwBBAAAEEEEAAAQQQQAABBBBAAAEEEECAACjXAAIIIIAAAggggAACCCCAAAIIIIAAAggEVoAAaGBPLQeGAAIIIIAAAggggAACCCCAAAIIIIAAAgRAuQYQQAABBBBAAAEEEEAAAQQQQAABBBBAILACBEADe2o5MAQQQAABBBBAAAEEEEAAAQQQQAABBBAgAMo1gAACCCCAAAIIIIAAAggggAACCCCAAAKBFSAAGthTy4EhgAACCCCAAAIIIIAAAggggAACCCCAAAFQrgEEEEAAAQQQQAABBBBAAAEEEEAAAQQQCKwAAdDAnloODAEEEEAAAQQQQAABBBBAAAEEEEAAAQQIgHINIIAAAggggAACCCCAAAIIIIAAAggggEBgBQiABvbUcmAIIIAAAggggAACCCCAAAIIIIAAAgggQACUawABBBBAAAEEEEAAAQQQQAABBBBAAAEEAitAADSwp5YDQwABBBBAAAEEEEAAAQQQQAABBBBAAAECoFwDCCCAAAIIIIAAAggggAACCCCAAAIIIBBYAQKggT21HBgCCCCAAAIIIIAAAggggAACCCCAAAIIEADlGkAAAQQQQAABBBBAAAEEEEAAAQQQQACBwAoQAA3sqeXAEEAA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f7e6LFStmZcuWdbfjjz/eDj300JT1SbWOr1+/3ipVqmQ1a9a0Tz/9NNW6T39TXCDfX3+3FD8Guo8AAggggAACCCCAAAIIIIAAAikqoGDm4sWLM25ff/21ffvtt6YAaG62fPnyWYkSJVxQrmrVqlatWjV3q1KlCoHRXIDv2LGjjRw50m153rx5VqtWrVzYC5tEILIAAdDILryKAAIIIIAAAggggAACCCCAAAK5ILB8+XL77LPPMm4rV66MuJfDDz/cZWqecMIJpmxNZW+GZnNquZfpqfsCBQrYH3/8kZERqszQbdu2uWxRZY8q0Lpx40aXUarM0h9++MFljobvXNupUaOG1atXz93q169vJUuWDF+N51kQ0DmuXLmyKUtXTbazZs3KwhZYFYGcCRAAzZkf70YAAQQQQAABBBBAAAEEEEAAAR+B//73vzZ58mSbOHGiffTRR/bTTz/tt/Zhhx2WkX2pLExlY2qotIat52b7888/bd26dbZkyRJT1qmXhbps2TLbt2/ffrtWv5o2bepudevWdUPt91uBJ74CzZs3t/Hjx7t1FGBWIPT111+39u3b+76PhQjES4AAaLwk2Q4CCCCAAAIIIIAAAggggAACCDgBZVu+//779uabb9q0adMyMv+0UNmUDRs2zMiwPPXUU132ZrLQbd++3ebOnZuRoTp79mzTa15TXdGLLrrI2rVrZ02aNHFZqN4y7g8UUNBbwWNl7MqxdOnSLvBcpkwZUzZw4cKFD3wTryAQZwECoHEGZXMIIIAAAggggAACCCCAAAIIpKPArl277J133rFRo0a5jE9vuLMy/pQ16WVQKuCZSk0TLWm4tjJYdVu6dGlG94sUKWItW7Y01bc8++yzTXVFaf8I6BpQRq8CnXfccYc98cQTphqrmqhq/vz59sADD1jv3r3/eQOPEMglAQKguQTLZhFAAAEEEEAAAQQQQAABBBBIBwENHx82bJi99tprtmXLFnfICnqee+65LkuyVatWdsQRRwSGQrPSv/XWWy679auvvso4rvLly1uXLl2sU6dO1Az9P5VBgwbZrbfeaieddJKNHj3aTXykgOjzzz9vqq166KGHuuDocccdl+HIAwRyQ4AAaG6osk0EEEAAAQQQQAABBBBAAAEEAiyg+pljxoxxGX2a0MhrtWvXdkHANm3auAmLvNeDeq/Z6lXLcvjw4W5SJR2ngr9t27Z1GY81a9YM6qFHPS5NPHXiiSfa1q1bbdy4caYgp1fjVfVWO3To4IKil156qb3xxhtRt8cKCOREgABoTvR4LwIIIIAAAggggAACCCCAAAJpJLBz50575ZVXbODAgabgn5qyO6+44grr2rWrC3ClEUfGoSogPGnSJJcJO3bs2IyapxoWf/vtt9uFF16YsW66PLjuuutsyJAhrk6qSgcoUzg0APrjjz/aySefbDt27LCZM2e6jNB0seE4817goLzfJXtEAAEEEEAAAQQQQAABBBBAAIFUEti9e7c9/fTTpmHe119/vQt+litXzp566ik3q7uWKbiVru2ggw5yNU7fe+890xB51bvUZElTp041zYBeq1atjFnQ08VI9WALFizoguWRjlmTIN11111u0bvvvhtpFV5DIG4CZIDGjZINIYAAAggggAACCCCAAAIIIBAsAU1i89JLL9nDDz/sAp06utNOO8169Ohhqu2ZP3/+YB1wHI/mv//9r7344ov25JNP2s8//+y2fOaZZ1qfPn1cfdQ47iopN6XSCLp+GjVq5PoXngGqF//44w9XQqBJkyZWokSJpDwOOhUMAQKgwTiPHAUCCCCAAAIIIIAAAggggAACcRX46KOP3AQ2msFbTbO3P/TQQ9aiRYu47ifoG9u1a5eb9Kdfv372yy+/uMNt1qyZDRgwwCpWrBj0w884vkgB0IyFPEAglwUYAp/LwGweAQQQQAABBBBAAAEEEEAAgVQSWLFihatZ2bRpUzdDt2bwfvvtt00znhP8zPqZLFSokAska2i8gqBFihSxCRMmmGZD1wzpmiSIhgACuStAADR3fdk6AggggAACCCCAAAIIIIAAAikhsGfPHnvggQdcYE4BOgXqNHx7yZIldskll1i+fPlS4jiStZOFCxd2pQM0edQ111xj+/bts0GDBrmJgN56661k7Tb9QiAQAgRAA3EaOQgEEEAAAQQQQAABBBBAAAEEsi+geo3Vq1d3Q9xVt1EBOgXqbrvtNjeRTfa3zDvDBYoVK2ZDhw61BQsWWMOGDW3jxo126aWXuuzan376KXx1niOAQBwECIDGAZFNIIAAAggggAACCCCAAAIIIJCKAqpPefPNN1uDBg3sm2++cdmIM2fOdAE6BepouSegmqrTpk2zYcOG2RFHHGFjx461U045xYYPH557O2XLCKSpAAHQND3xHDYCCCCAAAIIIIAAAggggEB6CyxevNjN6P7UU09ZgQIF7P7777eFCxdavXr10hsmD49eZQW6dOliy5Yts9atW9v//vc/u/rqq13Jgd9++y0Pe8KuEAi2AAHQYJ9fjg4BBBBAAAEEEEAAAQQQQACBAwQGDx5sp59+ui1dutRlfc6dO9cNfz/kkEMOWJcXcl+gVKlS9u6779prr71m//73v93jatWq2dSpU3N/5+wBgTQQIACaBieZQ0QAAQQQQAABBBBAAAEEEEBAAsow1IRGt9xyi+3evdu6detm8+fPtxo1agCUBAKXX365LVq0yGXhrlu3zs477zw3c3wSdI0uIJDSAgRAU/r00XkEEEAAAQQQQAABBBBAAAEEYhNYvny5nXHGGS67UDO8f/DBB/b888+bZienJY9A2bJlbfr06darVy/7888/7e67784YHp88vaQnCKSWAAHQ1Dpf9BYBBBBAAAEEEEAAAQQQQACBLAtogh0NeddER1WrVrV58+bZxRdfnOXt8Ia8EcifP789+OCDbmIkTZD0/vvvW+3ate27777Lmw6wFwQCJkAANGAnlMNBAAEEEEAAAQQQQAABBBBAIFTgmWeesZYtW7rh7+3bt7c5c+ZYhQoVQlfhcZIKXHjhhS5YrXqgK1assDp16tjs2bOTtLd0C4HkFSAAmrznhp4hgAACCCCAAAIIIIAAAgggkG0BDZ++9dZbrXv37m4odZ8+fez111+3ww47LNvb5I15L1C+fHkX9GzevLlt2rTJGjdubG+99Vbed4Q9IpDCAgRAU/jk0XUEEEAAAQQQQAABBBBAAAEEIgn88ccfdtlll9mgQYPs4IMPdrOL33fffZFW5bUUEFDQWjVbb7jhBtu1a5c7t4MHD06BntNFBJJDgABocpwHeoEAAggggAACCCCAAAIIIIBAXAQUINOQ97fffttUP/Ljjz82zS5OS20B1QVVOYMnn3zSHcgtt9xiffv2Te2DovcI5JEAAdA8gmY3CCCAAAIIIIAAAggggAACCOS2wPbt261Zs2Y2YcIEK1asmE2dOtUaNWqU27tl+3kocNttt9lLL71kBx10kN177712zz335OHe2RUCqSlAADQ1zxu9RgABBBBAAAEEEEAAAQQQQGA/gR07dljTpk1d0POYY46x6dOnW/Xq1fdbhyfBEOjcubOr51qwYEF79NFH7a677grGgXEUCOSSAAHQXIJlswgggAACCCCAAAIIIIAAAgjklcDu3bvdsPdZs2bZcccdZzNnzrRKlSrl1e7ZTwIELr30Unv33XdNQdDHH3/cHnzwwQT0IvZdFipUyK3s3cf+TtZEIOcC+f76u+V8M2wBAQQQQAABBBBAAAEEEEAAAQQSIbB3715r06aNjRkzxkqWLGkzZsywE088MRFdYZ8JEFAQVMHQffv22RNPPGG33357AnoR2y5HjhxplStXtpo1a8b2BtZCIE4CBEDjBMlmEEAAAQQQQAABBBBAAAEEEEiEwJVXXulmeS9atKhNmzbNqlSpkohusM8ECiiweNVVV5ly3IYPH24aIk9DAIF/BBgC/48FjxBAAAEEEEAAAQQQQAABBBBIKYFevXq54Oe//vUvmzRpEsHPlDp78eusguDPPvus2+C1115rkydPjt/G2RICARAgAzQAJ5FDQAABBBBAAAEEEEAAAQQQSD+BV155xWX65c+f38aNG2dNmjRJPwSOeD+Bnj172mOPPWZFihQx1YMlG3g/Hp6ksQAB0DQ++Rw6AggggAACCCCAAAIIIIBAagpoqPv5559vf/zxhw0ZMsSU9UdDQEPg27dvb2+++aabDOvLL7+04sWLA4NA2gsQAE37SwAABBBAAAEEEEAAAQQQQACBVBL46aef3CQyv/76q915553Wv3//VOo+fc1lgd27d9s555xjs2fPtrPOOssNh1eWMA2BdBYgAJrOZ59jRwABBBBAAAEEEEAAAQQQSCmBPXv2WMOGDW3u3Ll2wQUX2IQJE+ygg9J7eo8dO3bYf//7X+dAtuP/v5w3bNjgguTr1693s8JrdvjcboMGDbJ+/fpF3U2+fPns8MMPt3//+99WsmRJq1Onjl188cVWtWrVqO9lBQSyK0AANLtyvA8BBBBAAAEEEEAAAQQQQACBPBbo1q2bDR061MqWLWvz58+3o446Ko97kDe7GzVqlK1cudJWrVrlMhkPO+wwF+RUoHPnzp2mQPCff/5pCqZp2LeaHs+YMcPq16+/XydXr15tffr0sWOOOcYqVark6mJWrlzZChQosN96QXviZYCqTIKGxLdr1y5XD/GRRx6x++67L1v7UBD/+uuvt8GDB6d9QD9bgLwpqkCw/2+PevisgAACCCCAAAIIIIAAAggggEBqCLz99tsu+FmoUCF77733kiL4qeDaxIkTbfPmzS5A+b///S8jUKlgZehzPVbGn2Yo1zFEanrPiBEj7Kabboq0+IDXFPw89NBDXTZhqVKlTLfwpv69/PLL+71cuHBhlyHZoEEDO/fcc61evXp2yCGH7LdOqj+pW7euDRgwwLp3725du3a1008/3QXO8+K4FGCuXbt2xF3pnKl8ww8//GDffPON7du3zwWzn3nmGXddPP744xHfx4sI5ESADNCc6PFeBBBAAAEEEEAAAQQQQAABBPJAQHU/q1WrZlu2bLHnn3/elAma1bZr1y5bunSpb4BSAUgvcNmqVSu74YYbfHejoJUCbLG2I444wpSRqftIrVGjRi6L01umrE5luSqgVr58eatQoYK7L1eunJ1wwgluO9EyORWk/eCDD2zJkiUu4LZw4UL79ttvvV24ewVEmzRpYq1bt3bDsTVEOyitbdu29s4777gg7/Tp0y236oGGZoDecccdFksgc/ny5XbrrbfaRx995Lh1vlesWGEnnnhiUPg5jiQRIAM0SU4E3UAAAQQQQAABBBBAAAEEEEDAE9Dw7t9++81lUG7dutWuvvpqF/ysWbOmGyKsmo5edqUmvbnttttccNB7f6R7zQ6uQGCsTYHDaAFQBQ2vuOIKN5xcNR11+9e//uXuIz1XhqaCjZm1Fi1amIa7axi7JvCpVatWjjMzCxYsaAoC6uY12aqO6qeffuoyUhctWuSyapVZq2zQWbNmeaum/L1KJnz++ef22WefmYKUvXr1SppjOvnkk527skUVnFd26LBhw5jYK2nOUHA6QgA0OOeSI0EAAQQQQAABBBBAAAEEEEiggIKWXlDSy6L0Miq95woOdu7c2dWrzKyrCmhWrFjR1q5de8AqCxYssGuvvfaA10uXLm333nvvAa+HvtC4cWNTJqn6EBqkzOyxgo/RmjIyR44cGW21mJfffvvtbtKemN+QzRWVVdq0aVN30yZ+/vlne//9923MmDEuAJrNzSbl23Ssr776qhvqr1qozZo1s9NOOy1p+qoSBldeeaX17NnT9enrr79Omr7RkeAIEAANzrnkSBBAAAEEEEAAAQQQQAABBLIh8Pvvv2cM+/YClgpkati1Anx+TcGali1b2saNG03biaUpi7N69eqZrqoJYY4++mjbvn27q2+5bt06lxmnoJWGgXuZlV62pQJcbdq0yXR73oIbb7zRdEtEU4BRGaXHH398InYfdZ+aIEnZrtEyXqNuKElXOPvss91Q8yeffNK6dOli8+bNS6pJoFQb1msq80BDIN4CBEDjLcr2EEAAAQQQQAABBBBAAAEEcl1As4B7wUrNCq6htNFqG2p4swJA27Ztywh4KtCpSVgiNdWY1Czkfm3Tpk22Zs0aN4mLApeqHRkeoPSeK9NS21QtT7+mIdsKUKmdd955LmtTw8zjmWnpt/94LlMw6+GHH7Znn33WDWXX0PNo5yme+2db/wgo+1NZrhrur/qcd9999z8LE/xIE2N5Tf8v0xCItwAB0HiLsj0EEEAAAQQQQAABBBBAAIGIAt5szwrwRWua6GfGjBmZDilXADS0KZjTt2/f0JcOeDxhwgSbPXv2Aa+rJqWXTekFK3WvIdLRmjLrFORT8FO1KzWJS7zaK6+84upTKht04MCB8dpsnmxH5QBeeOEFu+eeezJ8VMc0CMHPX375xR588EG75JJLTOc/VZqGmuucaNb7hx56yPU/GSYbWrx4sY0bNy6D8Ywzzsh4zAME4iVAADRekmwHAQQQQAABBBBAAAEEEEhDgb1795omWVFtyczqX3qva4h4oUKF3OQz0bIge/To4baXGenBBx+cUcdSM4rXrVs3s1UzXn/66aftmmuucZPweIFOZWXmNCinbcW7KUv1rrvucpsdNGiQGxIf733k1vZUFqBr167uPGsfymLt37+/77D/3OpLbmx36tSp9txzz7lbp06dXFaxyhCkQlMdWNWgff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4di9a8Oj3R1mM5AggggAACCCCAAAIIJJeAFzwqWrRowju2du1a1wdvcpuEd4gOHCCg748qE6bkmnXr1pkScRLVvGvWu4Zj7cdjjz1mY8aMsddff90lium7b2hT8FPfrVXj9KKLLgpdxGME4i4QuGjYihUrHFK0uodxl0zSDR566KF23HHHuUluVK9DQ51TuY0bN85N6vS///3PBSsV6Ax/rNqXXrv22mttyJAh3tOI95qwZ+zYsRGXHXLIIftlWiqAWadOHd/gpzakALz+kVIAVe/RH3q/gGnEnfMiAggggAACCCCAAAIIBEZAk36qedl0iTww1SJVS2RQLZHHnyr7VqKMAqA///xzQs+VSrbpe62+f2/bts004WwsTbVuNTHzQw895OaReOmllzLetmTJEvddXUlagwYNynidBwjklkBgA6DRiuzmFmgyblcWa/6ebVDB4bwMgL733numdP3wAKX+aHo3b5lqZI4fPz5qFuStt97qtunn7A0R1x/latWq+a3qlulXJ5UKUMZweIZmTmrzlCxZMuq+WQEBBBBAAAEEEEAAAQTSQ0CZbmpHHXVUwg9YAS21WL4vJbyzadwBjWhUy2rtzdwg03Wr7/G6jmMNgKofGv4+fPhwN5u9ko+8dsstt7gJklT/k1IMngr3uSkQuADoqlWrnFdeBvpy8wTFY9uymDRpknk24dvUkPFp06aZ0tn1B80LSmb2WMWLP/jgAzdxT/i2vOcKtqoGZqxNwUcFQaO10aNH2xdffHFAVmZoPczChQtH28x+y5Ulq5R7GgIIIIAAAggggAACCCCQWwKq56+WDKXabr/9drt0l4XhAABAAElEQVTwwgutcuXKuXW4bDcOAl62sGplJrp51613HcfaH30/11D4yy+/3AYPHuzepixSlS9UULV3796xbor1EMiRQOACoPofSU0TygSxaUj1999/f0AGZXhGpZ5r4p3WrVtnWHg24S6adU2/vsTalE26c+dO3wCogq5eXU1vCHh4dmXo81iHiGsG8lhmIY/1WFgPAQQQQAABBBBAAAEEEMgLgT179rjd5GSUWbz6qVFzBD/jpZl72/FqZipJKdHNu2696zgr/enQoYM9++yzNnv2bPe2DRs2uHsNjU+GjO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VMI77p/1785ZdfXB+9EgCxBHj9tscyBBBAAAEEEEAAgbwVKFeunNthVmrw51YPVdpKn0313XHXrl1u8tfc2hfbTW0B73r1rt/UPhp6n64CgQ2A1qpVy+rVq2eaCX7IkCF2++23p9U5fuSRR9zxduvWjTqIaXXmOdisCihTNZZsVQ3BVyA02lB97f+8886ztm3buqLyXhDVy1rVdhRs1c1r8+bNs379+lnx4sW9lw6437BhgytVoA+nXlONUy+IGl4DVf289957TQXuo7U///zTffiNth7LEUAAAQQQQAABBHImUKVKFbcBb4KbnG0tZ+/WvAIqF6f6/cpKbdq0ac42yLsDKbBv3z775ptv3Ez0lStXDuQxclDpIZDvr79bUA914sSJ1qxZMzdTmWpWpEu2lDLUqlevboceeqgrrh1LwCao1wDHhUCyCegDhAKpodmmRYsWtZNOOsm3qzt37rTWrVvbypUrM+qqavZQvzZ06FC75ppr/FZx29SEVd4Q/9CAanhQVc9btWplJ598su82WYgAAggggAACCCAQWUDfS5VFp9m0f/7558gr5eGrvXv3tgcffNCuu+46e+655/Jwz+wqVQQU/DzllFNcMsaqVatSpdv0E4EDBAKbAaoj1S9YKuy8YMECGzRokPXo0eMAgCC+0LNnT1Nc+9prr40pWy2IBhwTAskqoMmUjjjiCHfLSh/1g4Z+1AltCoB6GaahAVW9pqzONm3ahK4e8XGRIkXcBE/eEH9lmvq1WbNm2fjx4/1WsbFjx9ott9zihlGFB1EjBVirVq3qyhD4bpSFCCCAAAIIIIBAAARUQ1Gfh9avX+9GC+mH8ES2Fi1auADo559/nshusO8kFvCylfWZnYZAKgsEOgCqE9O/f38799xzTXX+OnToYGXKlEnl8xW17++9954Lkmg4w9133x11fVZAAIHUFdAQeGV45yTL++WXXzbdNDTfG6YfKaiqAOv27dvt4osvjgqmIulZ+XVY2fnap44ns6aSAV26dHF1WEODqKGPQ4OtGvpPjaLMNHkdAQQQQAABBBIlkC9fPtMw+Dlz5tjChQutcePGieqK268ShpT5WbFixYT2g50nr4CuU7Vq1aolbyfpGQIxCAQ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O2fO+TxvYvxyzj1pZmc6Fi1alB222mqrZqVYbdzz5s3L94udO3dunHvuuTFmzJjVPveGQLMJCECbreLGS4AAAQIECBAgQIAAAQINLZDu55g2B/rwww/jvPPOi6uuuqqhx6PzxQqkTbH233//fJuENAN02rRpeff3Yn9FawQaS6B5/5moseqktwQIECBAgAABAgQIECBAIAv06NEj7rjjjmhtbY2rr746L4lHQyAJrFixIu/4npa/p02i0t9Jukeqg0CzCwhAm/0vwPgJECBAgAABAgQIECBAoOEE0sy+m266Kfd7xIgRkXZjdxC44IILcuiZNny6//77wy0B/E0Q+H8BAai/BAIECBAgQIAAAQIECBAg0IACJ510Ulx00UWxbNmyvDt82hTJ0bwCf/vb3+LKK6/MM4MnTZoUu+22W/NiGDmBbwi4B+g3QLwlQIAAAQIECBAgQIAAAQKNJHDCCSfEhAkTYsstt4zHHntM8NVIxSuor7feemte+p6WwI8fPz5OPvnkglrWDIFqCAhAq1FHoyBAgAABAgQIECBAgACBJhVYunRpDB06NKZMmRLdu3eP6dOnR8+ePZtUo/mGfdddd8UxxxyTZwKn3d7Tru8OAgRWF7AEfnUP7wgQIECAAAECBAgQIECAQEMJtLS0xJ133hm/+c1vYt68eXHAAQfEW2+91VBj0NkfJjB16tQ49thjc/h5ySWXCD9/GKNvNYGAGaBNUGRDJECAAAECBAgQIECAAIHqCyxatCgOOuigeOKJJ2KbbbaJadOmRe/evas/8CYdYdrhPd3+YMmSJXHeeefFVVdd1aQShk3g+wXMAP1+I1cQIECAAAECBAgQIECAAIHSC2y66abx4IMPxqBBg+L999+P/fbbL55//vnS91sH117g5ptvjuOOOy6Hn2nnd+Hn2hv6RnMJCECbq95GS4AAAQIECBAgQIAAAQIVFujcuXM88MADccghh8T8+fNzGPr4449XeMTNN7Rrr702Tj311Fi+fHlcfvnlccUVVzQfghETWEsBAehagrmcAAECBAgQIECAAAECBAiUWWDjjTeOe++9N4466qj49NNP48ADD4yJEyeWucv6tgYCy5Yti9///ve1+3xed9118ac//WkNvukSA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KjzwTIFBSAQFoSQujWwQIECBAgAABAgQIECBAoAoCaSf0Rx99NB566KH8SLukr3qkHeRTCNq3b99ImyilR69evaJr166rXlb463Qf0/feey/SjM5Zs2bVHi+//HIsW7Zstd9LfVo5gzXNZm1tbV3tc28IECi3gAC03PXROwIECBAgQIAAAQIECBAgUCmBV199tTa7Ms2w/Oc//1l3fJ07d47tt98+fv7zn8d2220X3bp1i7SxUgpG03P6PM2+3HDDDfMjzSJdsmRJLF68ONKy9fS8YMGCSLNR//Of/+TnDz74IObMmRPpPp5p06J03TeP1E7//v1rM1T33Xdf9/T8JpL3BBpMQADaYAXTXQIECBAgQIAAAQIECBAgUCWBFFC+8MILkTZTSjMx03MKRVN42Z5Hul/n1ltvnWebrpx5mmahpscmm2zSnj+tbQIE1rOAAHQ9g/s5AgQIECBAgAABAgQIECBA4PsFPv300zxTM83YfOedd/IszpUzOVNounDhwtpszzSTc+nSpXlp+spZoel5s802q80YTTNH0yzSNJs0zSxNz4LO76+DKwhUQUAAWoUqGgMBAgQIECBAgAABAgQIECBAgAABAnUFOtY96yQBAgQIECBAgAABAgQIECBAgAABAgQqICAArUARDYEAAQIECBAgQIAAAQIECBAgQIAAgfoCAtD6Ls4SIECAAAECBAgQIECAAAECBAgQIFABAQFoBYpoCAQIECBAgAABAgQIECBAgAABAgQI1BcQgNZ3cZYAAQIECBAgQIAAAQIECBAgQIAAgQoICEArUERDIECAAAECBAgQIECAAAECBAgQIECgvoAAtL6LswQIECBAgAABAgQIECBAgAABAgQIVEBAAFqBIhoCAQIECBAgQIAAAQIECBAgQIAAAQL1BQSg9V2cJUCAAAECBAgQIECAAAECBAgQIECgAgIC0AoU0RAIECBAgAABAgQIECBAgAABAgQIEKgvIACt7+IsAQIECBAgQIAAAQIECBAgQIAAAQIVEBCAVqCIhkCAAAECBAgQIECAAAECBAgQIECAQH0BAWh9F2cJECBAgAABAgQIECBAgAABAgQIEKiAgAC0AkU0BAIECBAgQIAAAQIECBAgQIAAAQIE6gsIQOu7OEuAAAECBAgQIECAAAECBAgQIECAQAUEBKAVKKIhECBAgAABAgQIECBAgAABAgQIECBQX0AAWt/FWQIECBAgQIAAAQIECBAgQIAAAQIEKiAgAK1AEQ2BAAECBAgQIECAAAECBAgQIECAAIH6AgLQ+i7OEiBAgAABAgQIECBAgAABAgQIECBQAQEBaAWKaAgECBAgQIAAAQIECBAgQIAAAQIECNQXEIDWd3GWAAECBAgQIECAAAECBAgQIECAAIEKCAhAK1BEQyBAgAABAgQIECBAgAABAgQIECBAoL6AALS+i7MECBAgQIAAAQIECBAgQIAAAQIECFRAQABagSIaAgECBAgQIECAAAECBAgQIECAAAEC9QUEoPVdnCVAgAABAgQIECBAgAABAgQIECBAoAICAtAKFNEQCBAgQIAAAQIECBAgQIAAAQIECBCoLyAAre/iLAECBAgQIECAAAECBAgQIECAAAECFRAQgFagiIZAgAABAgQIECBAgAABAgQIECBAgEB9AQFofRdnCRAgQIAAAQIECBAgQIAAAQIECBCogIAAtAJFNAQCBAgQIECAAAECBAgQIECAAAECBOoLCEDruzhLgAABAgQIECBAgAABAgQIECBAgEAFBASgFSiiIRAgQIAAAQIECBAgQIAAAQIECBAgUF9AAFrfxVkCBAgQIECAAAECBAgQIECAAAECBCogIACtQBENgQABAgQIECBAgAABAgQIECBAgACB+gIt9U87S4AAAQIECBCorsAnn3wSF154YSxfvjwPsq2tLfbdd9+6A37jjTdizJgx+bMNNtggLrvssujSpUvda50kQIAAAQIECBAgQKB8AgLQ8tVEjwgQIECAAIF2Fthiiy2ic+fOcfXVV+dfevjhh+Oll16KTp06rfbLS5YsieOOOy6eeeaZfP6CCy4Qfq4m5A0BAgQIECBAgACB8gtYAl/+GukhAQIECBAg0A4Co0ePjt133z23PGfOnEjh5jePkSNH1sLPvffeO0aNGvXNS7wnQIAAAQIECBAgQKDkAh1W/N9R8j7qHgECBAgQIECgXQRmz54dAwYMiK+++io6dOgQ06dPry2Ff/zxx2P//ffPy+Q333zzeP7552O77bZrl35olAABAgQIECBAgACB9hMwA7T9bLVMgAABAgQIlFygT58+ceWVV+Zepn8THjZsWCxevDgWLFgQJ5xwQu0eoePGjRN+lryWukeAAAECBAgQIEDg2wTMAP02GecJECBAgACBphBIwefBBx8cjzzySB7vJZdcEmnjowkTJuT3w4cPj7FjxzaFhUESIECAAAECBAgQqKKAALQdq5o2U5g1a1aeSZKW1qUZJemxtq9Xfm/77bePa665ph17rGkCBAgQIFB+gbQcveil6HPnzo2+ffvGRx99FC0tLbF06dIMkc49/fTTsfHGGxcKk37n3XffLbRNjREgQIAAgUYTGD9+fEydOjU23HDD2GijjfIj/Td3bV6veu22224bgwYNajQG/SVAYD0ICEDbCfm9996LHj16tFPrmiVAgAABAs0rkO7VmXZl32OPPQpFuPvuu2Po0KG1NjfddNN49tlno3fv3rVzRbxI4erWW28dH3/8cRHNaYMAAQIECBBYRWDMmDFx7rnnrnLGSwIECES0QGgfga5du8Y222yTZ5IsX7480vK69Jwe63L069cvb9KwLm34LgECBAgQaGSBLbbYol3+kfHwww/PM0v//e9/Z56dd9450qPoI80wPfTQQ/MqkaLb1h4BAgQIEGgkgXTLmYULF/7gLnfs2DH//3F6To80G3Svvfb6we35IgEC1RUwA/RHqO2yZcviyy+/rD3SkvhV33/b6169ekX6nzMHAQIECBAgULzAqFGjYuTIkas1fOmll8bFF1+82jlvCBAgQIAAgWIEnnvuuXwP7rTsfZNNNvmfx7edT9e2trYW0wmtECDQFAIC0KYos0ESIECAAAEC3yWQ7vM5cODAfO/Pn/3sZ3nlxrx58/L9QGfMmBF77rnnd33dZwQIECBAgAABAgQIlFhAAFri4ugaAQIECBAg0P4Caeld//794/XXX88/NmXKlByEHnnkkfl9z549Y+bMmdGpU6f274xfIECAAAECBAgQIECgcIGOhbeoQQIECBAgQIBAAwmcffbZtfCzra0tBg8eHEOGDIljjjkmjyIFo+kaBwECBAgQIECAAAECjSlgBmhj1k2vCRAgQIAAgQIE0mzPlffXTkvfZ8+eHWmTpXTMnz8/+vTpk5/T+8mTJ8dhhx2WXjoIECBAgAABAgQIEGggATNAG6hYukqAAAECBAgUJ/DBBx/EsGHDag3eeOONtfAznezWrVvccMMNtc/Ttek7DgIECBAgQIAAAQIEGktAANpY9dJbAgQIECBAoCCBU045pTa7My19rze78+ijj46V9wJNM0LTdxwECBAgQIAAAQIECDSWgCXwjVUvvSVAgAABAgQKEBg7dmyMGDEit9S9e/e89L1Lly51W06zPnfdddf4+OOP8+fpu8OHD697rZMECBAgQIAAAQIECJRPQABavproEQECBAgQIECAAAECBAgQIECAAAECBQlYAl8QpGYIECBAgAABAgQIECBAgAABAgQIECifgAC0fDXRIwIECBAgQIAAAQIECBAgQIAAAQIEChIQgBYEqRkCBAgQIECAAAECBAgQIECAAAECBMonIAAtX030iAABAgQIECBAgAABAgQIECBAgACBggQEoAVBaoYAAQIECBAgQIAAAQIECBAgQIAAgfIJCEDLVxM9IkCAAAECBAgQIECAAAECBAgQIECgIAEBaEGQmiFAgAABAgQIECBAgAABAgQIECBAoHwCAtDy1USPCBAgQIAAAQIECBAgQIAAAQIECBAoSEAAWhCkZggQIECAAAECBAgQIECAAAECBAgQKJ+AALR8NdEjAgQIECBAgAABAgQIECBAgAABAgQKEhCAFgSpGQIECBAgQIAAAQIECBAgQIAAAQIEyicgAC1fTfSIAAECBAgQIECAAAECBAgQIECAAIGCBASgBUFqhgABAgQIECBAgAABAgQIECBAgACB8gkIQMtXEz0iQIAAAQIECBAgQIAAAQIECBAgQKAgAQFoQZCaIUCAAAECBAgQIECAAAECBAgQIECgfAIC0PLVRI8IECBAgAABAgQIECBAgAABAgQIEChIQABaEKRmCBAgQIAAAQIECBAgQIAAAQIECBAon4AAtHw10SMCBAgQIECAAAECBAgQIECAAAECBAoSEIAWBKkZAgQIECBAgAABAgQIECBAgAABAgTKJyAALV9N9IgAAQIECBAgQIAAAQIECBAgQIAAgYIEBKAFQWqGAAECBAgQIECAAAECBAgQIECAAIHyCQhAy1cTPSJAgAABAgQIECBAgAABAgQIECBAoCABAWhBkJohQIAAAQIECBAgQIAAAQIECBAgQKB8AgLQ8tVEjwgQIECAAAECBAgQIECAAAECBAgQKEhAAFoQpGYIECBAgAABAgQIECBAgAABAgQIECifgAC0fDXRIwIECBAgQIAAAQIECBAgQIAAAQIEChIQgBYEqRkCBAgQIECAAAECBAgQIECAAAECBMonIAAtX030iAABAgQIECBAgAABAgQIECBAgACBggQEoAVBaoYAAQIECBAgQIAAAQIECBAgQIAAgfIJCEDLVxM9IkCAAAECBAgQIECAAAECBAgQIECgIAEBaEGQmiFAgAABAgQIECBAgAABAgQIECBAoHwCekWcfQAAAiFJREFUAtDy1USPCBAgQIAAAQIECBAgQIAAAQIECBAoSEAAWhCkZggQIECAAAECBAgQIECAAAECBAgQKJ+AALR8NdEjAgQIECBAgAABAgQIECBAgAABAgQKEhCAFgSpGQIECBAgQIAAAQIECBAgQIAAAQIEyicgAC1fTfSIAAECBAgQIECAAAECBAgQIECAAIGCBASgBUFqhgABAgQIECBAgAABAgQIECBAgACB8gkIQMtXEz0iQIAAAQIECBAgQIAAAQIECBAgQKAgAQFoQZCaIUCAAAECBAgQIECAAAECBAgQIECgfAIC0PLVRI8IECBAgAABAgQIECBAgAABAgQIEChIQABaEKRmCBAgQIAAAQIECBAgQIAAAQIECBAon4AAtHw10SMCBAgQIECAAAECBAgQIECAAAECBAoSEIAWBKkZAgQIECBAgAABAgQIECBAgAABAgTKJyAALV9N9IgAAQIECBAgQIAAAQIECBAgQIAAgYIEBKAFQWqGAAECBAgQIECAAAECBAgQIECAAIHyCQhAy1cTPSJAgAABAgQIECBAgAABAgQIECBAoCABAWhBkJohQIAAAQIECBAgQIAAAQIECBAgQKB8AgLQ8tVEjwgQIECAAAECBAgQIECAAAECBAgQKEhAAFoQpGYIECBAgAABAgQIECBAgAABAgQIECifgAC0fDXRIwIECBAgQIAAAQIECBAgQIAAAQIEChL4Lxoahjy9Gq1AAAAAAElFTkSuQmCC)", "_____no_output_____" ], [ "If the angle is less (in absolute value) than the threshold, the show will go in the cup. The mathematically inclined golf pro suggests that we can assume that the putter will attempt to shoot perfectly straight, but that external factors will interfere with this goal. She suggests modelling this uncertainty using a normal distribution centered at 0 (i.e. assume that shots don't deviate systematically to the right or left) with some variance in angle (in radians) given by $\\sigma_{\\text{angle}}$.\n\nSince our golf expert is also a expert mathematician, she provides us with an expression for the probability that the ball goes in the cup (which is the probability that the angle is less than the threshold):\n\n$$p\\Bigg(\\vert\\text{angle}\\vert < sin^{−1}\\Bigg(\\dfrac{R−r}{x}\\Bigg)\\Bigg) = 2\\Theta\\Bigg(\\dfrac{1}{\\sigma_{\\text{angle}}}sin^{−1}\\Bigg(\\dfrac{R−r}{x}\\Bigg)\\Bigg) - 1,$$ \n\nwhere $\\Theta$ is the cumulative normal distribution function.\n\nThe full model is then given by\n\n$$y_j \\sim \\text{Binomial}(n_j, p_j)\\\\\np_j = 2\\Theta\\Bigg(\\dfrac{1}{\\sigma_{\\text{angle}}}sin^{−1}\\Bigg(\\dfrac{R−r}{x}\\Bigg)\\Bigg) - 1, \\quad \\text{for} j = 1 \\ldots J.$$\n\nPrior to fitting the model, our expert provides us with the appropriate measurements for the golf ball and cup radii. We also plot the probabilities given by the above expression for different values of $\\sigma_{\\text{angle}}$ to get a feel for the model:", "_____no_output_____" ] ], [ [ "def forward_angle_model(variance_of_shot, distance):\n \"\"\"Geometry-based probabilities.\"\"\"\n BALL_RADIUS = (1.68 / 2) / 12\n CUP_RADIUS = (4.25 / 2) / 12\n return 2 * st.norm(0, variance_of_shot).cdf(np.arcsin((CUP_RADIUS - BALL_RADIUS) / distance)) - 1\n\n# Plotting\nvariance_of_shot = (0.01, 0.02, 0.05, 0.1, 0.2, 1)\ndistances = np.linspace(0, data[\"distance\"].max(), 200)\nax = plot_golf_data(data)\n\nfor sigma in variance_of_shot:\n ax.plot(distances, forward_angle_model(sigma, distances), label=f\"$\\sigma$ = {sigma}\")\n\nax.set_title(\"Model prediction for selected amounts of variance\")\nax.legend()\nplt.show()", "_____no_output_____" ], [ "def phi(x):\n \"\"\"Calculates the standard normal CDF.\"\"\"\n return 0.5 + 0.5 * tt.erf(x / tt.sqrt(2.))\n\ndef angle_model(data):\n \"\"\"Geometry-based model.\"\"\"\n BALL_RADIUS = (1.68 / 2) / 12\n CUP_RADIUS = (4.25 / 2) / 12\n \n with pm.Model() as angle_model:\n variance_of_shot = pm.HalfNormal('variance_of_shot')\n prob = 2 * phi(tt.arcsin((CUP_RADIUS - BALL_RADIUS) / data[\"distance\"]) / variance_of_shot) - 1\n prob_success = pm.Deterministic('prob_success', prob)\n success = pm.Binomial('success', n=data[\"tries\"], p=prob_success, observed=data[\"successes\"])\n \n return angle_model\n\n# Plotting model as graph\npm.model_to_graphviz(angle_model(data))", "_____no_output_____" ] ], [ [ "## 3.1 Geometry-based model: Prior predictive checks", "_____no_output_____" ] ], [ [ "# Drawing 500 samples from the prior predictive distribution\nwith angle_model(data):\n angle_prior = pm.sample_prior_predictive(500)\n\n# Use these variances to sample an equivalent amount of random angles from a normal distribution\nangle_of_shot = np.random.normal(0, angle_prior['variance_of_shot'])\ndistance = 20\n\n# Calculate possible end positions\nend_positions = np.array([\n distance * np.cos(angle_of_shot),\n distance * np.sin(angle_of_shot)\n])\n\n# Plotting\nfig, ax = plt.subplots(figsize=(10, 6))\n\nfor endx, endy in end_positions.T:\n ax.plot([0, endx], [0, endy], 'k-o', lw=1, mfc='w', alpha=0.1);\n\nax.plot(0, 0, 'o', color=\"tab:blue\", label='Start', ms=10)\nax.plot(distance, 0, 'o', color=\"tab:orange\", label='Goal', ms=10)\n\nax.set_title(f\"Prior distribution of putts from {distance}ft away\")\nax.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "## 3.2 Fitting model", "_____no_output_____" ] ], [ [ "# Draw samples from posterior distribution\nwith angle_model(data):\n angle_trace = pm.sample(10000, tune=1000)", "_____no_output_____" ], [ "pm.summary(angle_trace)", "_____no_output_____" ], [ "# Plotting posterior distribution of angle variance\npm.plot_posterior(angle_trace[\"variance_of_shot\"])\npm.forestplot(angle_trace)\nplt.show()", "_____no_output_____" ] ], [ [ "## 3.3 Logistic regression vs. geometry-based model", "_____no_output_____" ] ], [ [ "# Plot model\nax = plot_golf_data(data)\ndistances = np.linspace(0, data[\"distance\"].max(), 200)\n\nfor idx in np.random.randint(0, len(angle_trace), 50):\n ax.plot(\n distances,\n forward_angle_model(angle_trace['variance_of_shot'][idx], distances),\n lw=1,\n color=\"tab:orange\",\n alpha=0.7,\n )\n\n# Average of angle model\nax.plot(\n distances,\n forward_angle_model(angle_trace['variance_of_shot'].mean(), distances),\n label='Geometry-based model',\n color=\"tab:blue\",\n)\n\n# Compare with average of logit model\nax.plot(distances, logit_average, color=\"tab:green\", label='Logit-binomial model (avg.)')\n\nax.set_title(\"Comparing the fit of geometry-based and logit-binomial model\")\nax.set_ylim([0, 1.05])\nax.legend()\nplt.show()", "_____no_output_____" ], [ "# Comparing models using WAIC (Watanabe-Akaike Information Criterion)\nmodels = {\n \"logit\": logit_trace,\n \"geometry\": angle_trace,\n}\npm.compare(models)", "_____no_output_____" ] ], [ [ "## 3.4 Geometry-based model: Posterior predictive check", "_____no_output_____" ] ], [ [ "# Randomly sample a sigma from the posterior distribution\nvariances = np.random.choice(angle_trace['variance_of_shot'].flatten())\n\n# Randomly sample 500 angles based on sample from posterior\nangle_of_shot = np.random.normal(0, variances, 500) # radians\ndistance = 20\n\n# Calculate end positions\nend_positions = np.array([\n distance * np.cos(angle_of_shot),\n distance * np.sin(angle_of_shot)\n])\n\n# Plotting\nfig, ax = plt.subplots(figsize=(10, 6))\n\nfor endx, endy in end_positions.T:\n ax.plot([0, endx], [0, endy], '-o', color=\"gray\", lw=1, mfc='w', alpha=0.05);\n\nax.plot(0, 0, 'o', color=\"tab:blue\", label='Start', ms=10)\nax.plot(distance, 0, 'o', color=\"tab:orange\", label='Goal', ms=10)\n\nax.set_xlim(-21, 21)\nax.set_ylim(-21, 21)\nax.set_title(f\"Posterior distribution of putts from {distance}ft.\")\n\nax.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "# 4. Further work ", "_____no_output_____" ], [ "The [official](https://docs.pymc.io/notebooks/putting_workflow.html) [docs](https://mc-stan.org/users/documentation/case-studies/golf.html) further extend the angle model by accounting for distance and distance plus dispersion. Furthermore, the [PyMC3 docs](https://docs.pymc.io/notebooks/putting_workflow.html) show how you can model the final position of the putt, given starting distance from the cup, e.g.:\n\n![](https://docs.pymc.io/_images/notebooks_putting_workflow_52_0.png)\n\n![](https://docs.pymc.io/_images/notebooks_putting_workflow_53_0.png)\n\nThe authors show how this information can be leveraged to\n\n> [...] work out how many putts a player may need to take from a given distance. This can influence strategic decisions like trying to reach the green in fewer shots, which may lead to a longer first putt, vs. a more conservative approach. We do this by simulating putts until they have all gone in.\n\n![](https://docs.pymc.io/_images/notebooks_putting_workflow_56_0.png)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
4a519e3ddceadb9af020527f69962501c9784db6
106,805
ipynb
Jupyter Notebook
P) RoadMap 16 - Classification 3 - Training & Validating [Custom CNN, Custom Dataset].ipynb
Charlottecuc/Pytorch_Tutorial
4146fcbcda4be132c1ed85164df8b1e7c0cb9e77
[ "Apache-2.0" ]
152
2019-12-26T21:12:45.000Z
2022-03-29T02:03:31.000Z
P) RoadMap 16 - Classification 3 - Training & Validating [Custom CNN, Custom Dataset].ipynb
ikonbethel/Pytorch_Tutorial
0cdf504ebfd530b6d32385429d4789a1a4602863
[ "Apache-2.0" ]
1
2020-03-12T12:40:38.000Z
2020-03-12T15:22:10.000Z
P) RoadMap 16 - Classification 3 - Training & Validating [Custom CNN, Custom Dataset].ipynb
ikonbethel/Pytorch_Tutorial
0cdf504ebfd530b6d32385429d4789a1a4602863
[ "Apache-2.0" ]
73
2019-12-26T20:38:39.000Z
2022-02-13T05:16:56.000Z
146.508916
86,608
0.87245
[ [ [ "# RoadMap 16 - Classification 3 - Training & Validating [Custom CNN, Custom Dataset]", "_____no_output_____" ] ], [ [ "import torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom torchvision import datasets", "_____no_output_____" ] ], [ [ "# [NOTE: - The network, transformation and training parameters are not suited for the dataset. Hence, the training does not converge]", "_____no_output_____" ], [ "# Steps to take\n\n1. Create a network\n - Arrange layers\n - Visualize layers\n - Creating loss function module\n - Creating optimizer module [Set learning rates here]\n \n \n2. Data prepraration\n - Creating a data transformer\n - Downloading and storing dataset\n - Applying transformation\n - Understanding dataset\n - Loading the transformed dataset [Set batch size and number of parallel processors here]\n \n \n3. Setting up data - plotters\n\n\n4. Training\n - Set Epoch\n - Train model\n \n \n5. Validating\n - Overall-accuracy validation\n - Class-wise accuracy validation\n\n ", "_____no_output_____" ] ], [ [ "# 1.1 Creating a custom neural network\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n'''\nNetwork arrangement\n\n Input -> Conv1 -> Relu -> Pool -> Conv2 -> Relu -> Pool -> FC1 -> Relu -> FC2 -> Relu -> FC3 -> Output \n\n'''\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(in_channels=3, out_channels=6, kernel_size=5)\n self.pool = nn.MaxPool2d(kernel_size=2, stride=2)\n self.relu = nn.ReLU() # Activation function\n self.conv2 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5)\n self.fc1 = nn.Linear(16 * 53 * 53, 120) # In-channels, Out-Channels\n self.fc2 = nn.Linear(120, 84) # In-channels, Out-Channels\n self.fc3 = nn.Linear(84, 2) # In-channels, Out-Channels\n\n def forward(self, x):\n x = self.relu(self.conv1(x))\n x = self.pool(x)\n x = self.relu(self.conv2(x))\n x = self.pool(x)\n x = x.view(-1, 16 * 53 * 53) #Reshaping - Like flatten in caffe \n x = self.fc1(x)\n x = self.fc2(x)\n x = self.fc3(x)\n return x\n\n\nnet = Net()", "_____no_output_____" ], [ "net.cuda()", "_____no_output_____" ], [ "# 1.2 Visualizing network\nfrom torchsummary import summary\nprint(\"Network - \")\nsummary(net, (3, 224, 224))", "Network - \n----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n Conv2d-1 [-1, 6, 220, 220] 456\n ReLU-2 [-1, 6, 220, 220] 0\n MaxPool2d-3 [-1, 6, 110, 110] 0\n Conv2d-4 [-1, 16, 106, 106] 2,416\n ReLU-5 [-1, 16, 106, 106] 0\n MaxPool2d-6 [-1, 16, 53, 53] 0\n Linear-7 [-1, 120] 5,393,400\n Linear-8 [-1, 84] 10,164\n Linear-9 [-1, 2] 170\n================================================================\nTotal params: 5,406,606\nTrainable params: 5,406,606\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.57\nForward/backward pass size (MB): 8.07\nParams size (MB): 20.62\nEstimated Total Size (MB): 29.27\n----------------------------------------------------------------\n" ], [ "# 1.3. Creating loss function module\ncross_entropy_loss = nn.CrossEntropyLoss()\n", "_____no_output_____" ], [ "# 1.4. Creating optimizer module\n\noptimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)", "_____no_output_____" ], [ "# 2.1. Creating data trasnformer\n\ndata_transform = transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ])", "_____no_output_____" ] ], [ [ "### 2.2 Storing downloaded dataset\n\n\n Data storage directory \n [NOTE: Directory and File names can be anything]\n Parent Directory [cat_dog]\n |\n |----Train\n | |\n | |----Class1 [cat]\n | | |----img1.png\n | | |----img2.png\n | |----Class2 [dog]\n | | |----img1.png\n | |----img2.png\n |-----Val\n | |\n | |----Class1 [cat]\n | | |----img1.png\n | | |----img2.png\n | |----Class2 [dog]\n | | |----img1.png\n | | |----img2.png\n \n\n", "_____no_output_____" ] ], [ [ "# 2.2. Applying transformations simultaneously\n\ntrainset = datasets.ImageFolder(root='cat_dog/train',\n transform=data_transform)\n\nvalset = datasets.ImageFolder(root='cat_dog/val',\n transform=data_transform)", "_____no_output_____" ], [ "print(dir(trainset))", "['__add__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_find_classes', '_format_transform_repr', '_repr_indent', 'class_to_idx', 'classes', 'extensions', 'extra_repr', 'imgs', 'loader', 'root', 'samples', 'target_transform', 'targets', 'transform', 'transforms']\n" ], [ "# 2.3. - Understanding dataset\n\nprint(\"Number of training images - \", len(trainset.imgs))\nprint(\"Number of testing images - \", len(valset.imgs))\nprint(\"Classes - \", trainset.classes)", "Number of training images - 200\nNumber of testing images - 50\nClasses - ['cat', 'dog']\n" ], [ "# 2.4. - Loading the transformed dataset\n\nbatch = 4\nparallel_processors = 3\n\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=batch,\n shuffle=True, num_workers=parallel_processors)\n\n\nvalloader = torch.utils.data.DataLoader(valset, batch_size=batch,\n shuffle=False, num_workers=parallel_processors)\n\n# Class list\nclasses = tuple(trainset.classes)", "_____no_output_____" ], [ "# 3. Setting up data plotters\n\ndef imshow(inp, title=None):\n \"\"\"Imshow for Tensor.\"\"\"\n inp = inp.numpy().transpose((1, 2, 0))\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n inp = std * inp + mean\n inp = np.clip(inp, 0, 1)\n plt.imshow(inp)\n if title is not None:\n plt.title(title)\n plt.pause(0.001) # pause a bit so that plots are updated\n\n\n# Get a batch of training data\ninputs, labels = next(iter(trainloader))\n\n# Make a grid from batch\nout = torchvision.utils.make_grid(inputs)\n\nimshow(out, title=[classes[x] for x in labels])", "_____no_output_____" ], [ "from tqdm.notebook import tqdm", "_____no_output_____" ], [ "# 4. Training\n\nnum_epochs = 2\n\nfor epoch in range(num_epochs): # loop over the dataset multiple times\n running_loss = 0.0\n pbar = tqdm(total=len(trainloader))\n for i, data in enumerate(trainloader):\n pbar.update();\n # get the inputs\n inputs, labels = data\n inputs = inputs.cuda()\n labels = labels.cuda()\n \n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(inputs)\n loss = cross_entropy_loss(outputs, labels)\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n if i % 10 == 9: # print every 2000 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / 2000))\n running_loss = 0.0\n\nprint('Finished Training')", "_____no_output_____" ], [ "# 5.1 Overall-accuracy Validation \ncorrect = 0\ntotal = 0\nwith torch.no_grad():\n for data in valloader:\n images, labels = data\n images = images.cuda()\n labels = labels.cuda()\n outputs = net(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\nprint('Accuracy of the network on the 10000 test images: %d %%' % (\n 100 * correct / total))", "Accuracy of the network on the 10000 test images: 54 %\n" ], [ "# 5.2 Classwise-accuracy Validation\nclass_correct = list(0. for i in range(2))\nclass_total = list(0. for i in range(2))\nwith torch.no_grad():\n for data in valloader:\n images, labels = data\n images = images.cuda()\n labels = labels.cuda()\n outputs = net(images)\n _, predicted = torch.max(outputs, 1)\n c = (predicted == labels).squeeze()\n for i in range(len(c)):\n label = labels[i]\n class_correct[label] += c[i].item()\n class_total[label] += 1\n\n\nfor i in range(2):\n print('Accuracy of %5s : %2d %%' % (\n classes[i], 100 * class_correct[i] / class_total[i]))", "Accuracy of cat : 96 %\nAccuracy of dog : 12 %\n" ] ], [ [ "## Author - Tessellate Imaging - https://www.tessellateimaging.com/\n\n## Monk Library - https://github.com/Tessellate-Imaging/monk_v1\n\n Monk is an opensource low-code tool for computer vision and deep learning\n\n### Monk features\n- low-code\n- unified wrapper over major deep learning framework - keras, pytorch, gluoncv\n- syntax invariant wrapper\n\n\n### Enables\n- to create, manage and version control deep learning experiments\n- to compare experiments across training metrics\n- to quickly find best hyper-parameters\n\n\n### At present it only supports transfer learning, but we are working each day to incorporate\n- GUI based custom model creation\n- various object detection and segmentation algorithms\n- deployment pipelines to cloud and local platforms\n- acceleration libraries such as TensorRT\n- preprocessing and post processing libraries\n\n## To contribute to Monk AI or Pytorch RoadMap repository raise an issue in the git-repo or dm us on linkedin \n - Abhishek - https://www.linkedin.com/in/abhishek-kumar-annamraju/\n - Akash - https://www.linkedin.com/in/akashdeepsingh01/", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
4a51a114c72ed7939ee70ccf81071ea13f2dd783
28,924
ipynb
Jupyter Notebook
notebooks/prepare_references.ipynb
apahl/cellpainting2
b0fd4adbca804b136e3dca9c1b466a6efb49cbd3
[ "MIT" ]
3
2018-12-09T18:21:22.000Z
2022-02-02T08:48:38.000Z
notebooks/prepare_references.ipynb
apahl/cellpainting
9b80c31444219b438224a1d79c05c08a15ea6f75
[ "MIT" ]
1
2018-04-11T13:37:43.000Z
2018-06-12T07:22:30.000Z
notebooks/prepare_references.ipynb
apahl/cellpainting2
b0fd4adbca804b136e3dca9c1b466a6efb49cbd3
[ "MIT" ]
1
2017-08-07T14:14:19.000Z
2017-08-07T14:14:19.000Z
36.155
188
0.453568
[ [ [ "%reload_ext autoreload\n%autoreload 2\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport os.path as op\nfrom collections import Counter\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# from tabulate import tabulate\n\nfrom rdkit.Chem import AllChem as Chem\nfrom rdkit.Chem import Draw\nfrom rdkit.Chem.Draw import IPythonConsole\nDraw.DrawingOptions.atomLabelFontFace = \"DejaVu Sans\"\nDraw.DrawingOptions.atomLabelFontSize = 18\n\nfrom misc_tools import nb_tools as nbt # , html_templates as html, apl_tools as apt\nfrom rdkit_ipynb_tools import tools # , bokeh_tools as bt, pipeline as p, clustering as cl\n\nfrom cellpainting import processing as cpp, tools as cpt\n\nimport ipywidgets as ipyw\nfrom IPython.core.display import HTML, display, clear_output #, Javascript, display_png, clear_output, display\n\nCOMAS = \"/home/pahl/comas/share/export_data_b64.tsv.gz\"", "> interactive IPython session.\n" ] ], [ [ "# Prepare References\nGenerate the references file.\n", "_____no_output_____" ] ], [ [ "REF_DIR = \"/home/pahl/comas/projects/painting/references\"\nPLATE_NAMES = [\"S0195\", \"S0198\", \"S0203\"] # \"S0195\", \"S0198\", \"S0203\"\nDATES = {\"S0195\": \"170523\", \"S0198\": \"170516\", \"S0203\": \"170512\"}\nkeep = [\"Compound_Id\", \"Container_Id\", \"Producer\", \"Conc_uM\", \"Activity\", \"Rel_Cell_Count\", \"Pure_Flag\", \"Toxic\", \n 'Trivial_Name', 'Known_Act', 'Act_Profile', \"Metadata_Well\", \"Plate\", 'Smiles']\ndata_keep = [\"Compound_Id\", \"Container_Id\", \"Producer\", \"Conc_uM\", \"Pure_Flag\", \"Activity\", \"Rel_Cell_Count\", \"Toxic\", \n 'Act_Profile', \"Metadata_Well\", \"Plate\", 'Smiles']\nds_list = []\npb = nbt.ProgressbarJS()\nnum_steps = 4 * len(PLATE_NAMES)\nstep = 0\nfor plate in PLATE_NAMES:\n for idx in range(1, 5):\n step += 1\n pb.update(100 * step / num_steps) \n path = op.join(REF_DIR, \"{}-{}\".format(plate, idx))\n print(\"\\nProcessing plate {}-{} ...\".format(plate, idx))\n ds_plate = cpp.load(op.join(path, \"Results.tsv\"))\n ds_plate = ds_plate.group_on_well()\n ds_plate = ds_plate.remove_skipped_echo_direct_transfer(op.join(path, \"*_print.xml\"))\n ds_plate = ds_plate.well_type_from_position()\n ds_plate = ds_plate.flag_toxic()\n ds_plate = ds_plate.activity_profile()\n ds_plate = ds_plate.join_layout_1536(plate, idx)\n ds_plate.data[\"Plate\"] = \"{}-{}-{}\".format(DATES[plate], plate, idx)\n ds_list.append(ds_plate.data)\npb.done()", "cellpainting.processing (commit: 7e77cd2 ( 2017-08-05 22:51:25 ))\n" ], [ "# *** ds_all <- concat(ds_list) ***\nds_all = cpp.DataSet()\nds_all.data = pd.concat(ds_list)\nds_all.print_log(\"concat data\")\ndel ds_list\nds_all.write_pkl(\"170630_references.pkl\")\n# ds_all = cpp.load_pkl(\"170630_references.pkl\")\n\n\n# *** ds_profile <- ds_all ***\nds_profile = ds_all.join_smiles()\n\n\n# *** ds_ref <- ds_profile ***\nds_ref, _ = ds_profile.remove_impure()\nds_ref, _ = ds_ref.remove_toxic()\nds_ref = ds_ref[ds_ref[\"Activity\"] >= 2.5]\nds_ref = ds_ref.join_annotations()\nds_ref.update_similar_refs(mode=\"ref\")\nds_ref = ds_ref[keep]\nds_ref.write_csv(\"references_act_prof.tsv\")\n\n\n# *** update DATASTORE ***\nds_profile.update_datastore(mode=\"ref\")", "* concat data: ( 4220 | 14)\n- loading resource: (SMILES)\n* join smiles: ( 3921 | 16)\n* remove impure: ( 3577 | 16) (344 removed)\n* remove toxic: ( 3460 | 16) (117 removed)\n* subset: ( 2476 | 16)\n- loading resource: (ANNOTATIONS)\n* join annotations: ( 2476 | 18)\n- loading resource: (REFERENCES)\n- loading resource: (SIM_REFS)\n* write sim_refs ( 1966 | -- )\n* update similar: ( 2476 | 18)\n* subset: ( 2476 | 14)\n- loading resource: (DATASTORE)\n* write datastore: ( 5328 | 13)\n* update datastore: ( 3921 | 16)\n" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4a51a3e3360fdcfd76a6ba1edd52d9a65287e21d
245,851
ipynb
Jupyter Notebook
Portfolio_planner. hw_final.ipynb
NinoslavVasic/Homework_api
628975b1f10fadb3d3c70192694e5189ac612cc3
[ "ADSL" ]
null
null
null
Portfolio_planner. hw_final.ipynb
NinoslavVasic/Homework_api
628975b1f10fadb3d3c70192694e5189ac612cc3
[ "ADSL" ]
null
null
null
Portfolio_planner. hw_final.ipynb
NinoslavVasic/Homework_api
628975b1f10fadb3d3c70192694e5189ac612cc3
[ "ADSL" ]
null
null
null
225.965993
136,288
0.902738
[ [ [ "import numpy as np\nimport pandas as pd\nimport os\nfrom datetime import datetime, timedelta\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "np.random.seed(42)", "_____no_output_____" ] ], [ [ "# Portfolio Planner\n\nIn this activity, you will use the iexfinance api to grab historical data for a 60/40 portfolio using `SPY` to represent the stock portion and `AGG` to represent the bonds.", "_____no_output_____" ] ], [ [ "#from iexfinance.stocks import get_historical_data\n#import iexfinance as iex\n#from iexfinance.stocks import get_historical_data\n#from iexfinance.refdata import get_symbols", "_____no_output_____" ] ], [ [ "# Data Collection\n\nIn this step, you will need to use the IEX api to fetch closing prices for the `SPY` and `AGG` tickers. Save the results as a pandas DataFrame", "_____no_output_____" ] ], [ [ "#IEX_TOKEN = os.getenv('IEX_TOKEN')\n\n\n#type(IEX_TOKEN)", "_____no_output_____" ], [ "list_of_tickers = [\"SPY\", \"AGG\"]\n# YOUR CODE HERE\nend_date = datetime.now()\nstart_date = end_date + timedelta(-365)\n\n#get one year historical data for 'SPY' and 'AGG'\n#portfolio_df = get_historical_data(list_of_tickers, start_date, end_date, close_only=True, output_format='pandas').astype(float)\n#portfolio_df.drop(columns='volume',level=1,inplace=True)\n#portfolio_df = portfolio_df.to_pickle('historic_data_homework_2')\nportfolio_df = pd.read_pickle('historic_data_homework_2')\n\nportfolio_df.plot(title=\"Stock prices in 1 year range\", figsize=(15,7))\n\nprint(portfolio_df.head())\n\n", " SPY AGG\n close close\ndate \n2019-01-28 263.76 106.62\n2019-01-29 263.41 106.90\n2019-01-30 267.58 107.14\n2019-01-31 269.93 107.46\n2019-02-01 270.06 106.97\n" ] ], [ [ "# Monte Carlo Simulation\n\nIn this step, you will run Monte Carlo Simulations for your portfolio to model portfolio performance at different retirement ages. \n\nComplete the following steps:\n1. Calculate the daily returns for the SPY and AGG closing prices.\n2. Calculate volatility for both the SPY and AGG closing prices.\n3. Find the last day's closing price for both stocks and save those as variables.\n4. Run a Monte Carlo Simulation of at least 500 iterations and generate at least 30 years of closing prices\n\n### HINTS:\nThere are 252 trading days per year, so the number of records to generate for each Monte Carlo run will be 252 days * 30 years", "_____no_output_____" ] ], [ [ "# Calculate the daily roi for the stocks\n# YOUR CODE HERE\ndaily_roi = portfolio_df.pct_change().dropna()\ndaily_roi.tail()", "_____no_output_____" ], [ "#calculate value of average daily roi as it is neccessary for roi simulation\navg_daily_roi_SPY = daily_roi.mean()['SPY']['close']\navg_daily_roi_AGG = daily_roi.mean()['AGG']['close']\n\nprint(f\"The level of daily return for SPY = {avg_daily_roi_SPY}\")\nprint(f\"The level of daily return for AGG = {avg_daily_roi_AGG}\")", "The level of daily return for SPY = 0.0008415062125783895\nThe level of daily return for AGG = 0.00027375476127896605\n" ], [ "# Calculate volatility\n# YOUR CODE HERE\nstd_daily_roi_SPY = daily_roi.std()['SPY']['close']\nstd_daily_roi_AGG = daily_roi.std()['AGG']['close']\n\nprint(f\"The level of daily standard deviation for SPY = {std_daily_roi_SPY}\")\nprint(f\"The level of daily standard deviation for AGG = {std_daily_roi_AGG}\")", "The level of daily standard deviation for SPY = 0.007456938669977417\nThe level of daily standard deviation for AGG = 0.002094524695851093\n" ], [ "# Save the last day's closing price for 'SPY' and 'AGG'\n# YOUR CODE HERE\n\nlast_price_SPY = portfolio_df['SPY']['close'][-1]\nlast_price_AGG = portfolio_df['AGG']['close'][-1]\n\n#print the last day closing price\nprint(f\"Last closing price for SPY is ${last_price_SPY}!\")\nprint(f\"Last closing price for AGG is ${last_price_AGG}!\")", "Last closing price for SPY is $323.5!\nLast closing price for AGG is $114.14!\n" ], [ "# Setup the Monte Carlo Parameters\nnumber_simulations = 500\nnumber_records = 252 * 30\n\n# Initialize empty DataFrame to hold simulated prices for each simulation\nsimulated_price_df = pd.DataFrame()\n\n# Initialize empty DataFrame to hold simulated prices for Monte Carlo simulation\nmonte_carlo = pd.DataFrame()\n", "_____no_output_____" ], [ "# Run the Monte Carlo Simulation\nfor x in range(number_simulations):\n #Initialize the simulated prices list with the last closing price \n simulated_prices_SPY = [last_price_SPY]\n simulated_prices_AGG = [last_price_AGG]\n \n #ROI simulation for 30 years * 252 trading days\n for i in range(number_records):\n \n # Calculate the simulated price using the last price within the list\n simulated_price_SPY = simulated_prices_SPY[-1] * (1 + np.random.normal(avg_daily_roi_SPY, std_daily_roi_SPY))\n simulated_price_AGG = simulated_prices_AGG[-1] * (1 + np.random.normal(avg_daily_roi_AGG, std_daily_roi_AGG))\n \n # Append the simulated price to the list\n simulated_prices_SPY.append(simulated_price_SPY)\n simulated_prices_AGG.append(simulated_price_AGG)\n \n # Append a simulated prices of each simulation to DataFrame\n simulated_price_df[\"SPY Prices\"] = pd.Series(simulated_prices_SPY)\n simulated_price_df[\"AGG Prices\"] = pd.Series(simulated_prices_AGG)\n \n # Calculate the daily returns of simulated prices\n simulated_roi_daily = simulated_price_df.pct_change()\n simulated_roi_daily[\"SPY Prices\"] = simulated_price_df[\"SPY Prices\"].pct_change()\n simulated_roi_daily[\"AGG Prices\"] = simulated_price_df[\"AGG Prices\"].pct_change()\n # Set the portfolio weights (60% SPY; 40% AGG)\n weight_SPY = [0.60]\n weight_AGG = [0.40]\n \n # With the weights to multiply weights with each column's simulated daily returns\n\n \n weighted_portfolio_roi_daily = weight_SPY * simulated_roi_daily[\"SPY Prices\"] + weight_AGG * simulated_roi_daily[\"AGG Prices\"]\n \n # Calculate the normalized, cumulative return series\n monte_carlo[x] = (1 + weighted_portfolio_roi_daily.fillna(0)).cumprod()\n \n # Print records from the DataFrame\n \nmonte_carlo.head()", "_____no_output_____" ], [ "# Visualize the Simulation\n# YOUR CODE HERE\nplot_title = f\"{number_simulations} Simulations of Cumulative Portfolio Return Trajectories \\n \\\n Over the Next {number_records} Trading Days (~30 years)\"\nmonte_carlo.plot(legend=None, title=plot_title, figsize=(12,7))", "_____no_output_____" ], [ "#simulated prices\nround(simulated_price_df.tail(),2)", "_____no_output_____" ], [ "# Select the last row for the cumulative returns (cumulative returns at 30 years)\n# YOUR CODE HERE\nending_roi_cumulative = monte_carlo.iloc[-1, :]\nround(ending_roi_cumulative.tail(),2)", "_____no_output_____" ], [ "# Select the last row for the cumulative returns (cumulative returns at 20 years)\n# YOUR CODE HERE\nround(ending_roi_cumulative.tail(1), 2)", "_____no_output_____" ], [ "# Display the 90% confidence interval for the ending returns\n# YOUR CODE HERE\n\nconf_interval = ending_roi_cumulative.quantile(q=[0.1, 0.9])\nconf_interval\n\n#`plot` function to create a probability distribution histogram of simulated ending prices\n\nplt.figure();\nending_roi_cumulative.plot(kind='hist', density=True, bins=50,figsize=(12,7))\nplt.axvline(conf_interval.iloc[0], color='r')\nplt.axvline(conf_interval.iloc[1], color='r')", "_____no_output_____" ], [ "# Visualize the distribution of the ending returns\n# YOUR CODE HERE\n\nending_roi_prob_distribution = ending_roi_cumulative.value_counts(bins=50) / len(ending_roi_cumulative)\nending_roi_prob_distribution.plot(figsize=(12,7))", "_____no_output_____" ] ], [ [ "---", "_____no_output_____" ], [ "# Retirement Analysis\n\nIn this section, you will use the monte carlo model to answer the following retirement planning questions:\n\n1. What are the expected cumulative returns at 30 years for the 10th, 50th, and 90th percentiles?\n2. Given an initial investment of `$20,000`, what is the expected portfolio return in dollars at the 10th, 50th, and 90th percentiles?\n3. Given the current projected annual income from the Plaid analysis, will a 4% withdraw rate from the retirement portfolio meet or exceed that value at the 10th percentile?\n4. How would a 50% increase in the initial investment amount affect the 4% retirement withdrawal?", "_____no_output_____" ], [ "### What are the expected cumulative returns at 30 years for the 10th, 50th, and 90th percentiles?", "_____no_output_____" ] ], [ [ "# YOUR CODE HERE\ninitial_investment = 20_000\n\nnew_conf_interval = ending_roi_cumulative.quantile(q=[0.1,0.5,0.9])\nround(new_conf_interval, 2)", "_____no_output_____" ], [ "expected_roi_10th_per = new_conf_interval.iloc[0]\nexpected_roi_50th_per = new_conf_interval.iloc[1]\nexpected_roi_90th_per = new_conf_interval.iloc[2]\n\nprint(f\"\"\"\nExpected cumulative percentage returns at 30 years:\n 10th percent {expected_roi_10th_per:,.2f} %\n 50th percent {expected_roi_50th_per:,.2f} %\n 90th percent {expected_roi_90th_per:,.2f} %\"\"\")", "\nExpected cumulative percentage returns at 30 years:\n 10th percent 58.92 %\n 50th percent 93.58 %\n 90th percent 151.76 %\n" ] ], [ [ "### Given an initial investment of `$20,000`, what is the expected portfolio return in dollars at the 10th, 50th, and 90th percentiles?", "_____no_output_____" ] ], [ [ "# YOUR CODE HERE\nexpected_roi_10th_usd = initial_investment * new_conf_interval.iloc[0]\nexpected_roi_50th_usd = initial_investment * new_conf_interval.iloc[1]\nexpected_roi_90th_usd = initial_investment * new_conf_interval.iloc[2]\n\nprint(f\"\"\"\nExpected cumulative returns at 30 years:\n 10th perc ${expected_roi_10th_usd:,.2f}\n 50th perc ${expected_roi_50th_usd:,.2f}\n 90th perc ${expected_roi_90th_usd:,.2f}\"\"\")", "\nExpected cumulative returns at 30 years:\n 10th perc $1,178,497.40\n 50th perc $1,871,642.95\n 90th perc $3,035,255.07\n" ] ], [ [ "### Given the current projected annual income from the Plaid analysis, will a 4% withdraw rate from the retirement portfolio meet or exceed that value at the 10th percentile?\n\nNote: This is effectively saying that 90% of the expected returns will be greater than the return at the 10th percentile, so this can help measure the uncertainty about having enough funds at retirement", "_____no_output_____" ] ], [ [ "# YOUR CODE HERE\n#gross income from Plaid analysis\nprev_year_gross_income = 6_000\n# withdrawall rate of 4% \nyearly_withdraw_rate = 0.04\n\nexpected_yearly_withdrawal = expected_roi_10th_usd * yearly_withdraw_rate\n\nif (expected_yearly_withdrawal > prev_year_gross_income):\n print(f\"Yearly withdrawal rate of 4% is equal to ${expected_yearly_withdrawal:,.2f} and it is higher than previous year's gross income of ${prev_year_gross_income:,.2f}.\")\nelse:\n print(f\"Yearly withdrawal rate of 4%is equal to ${expected_yearly_withdrawal:,.2f}and it is lower than previous year's gross income ${prev_year_gross_income:,.2f}.\")", "Yearly withdrawal rate of 4% is equal to $47,139.90 and it is higher than previous year's gross income of $6,000.00.\n" ] ], [ [ "### How would a 50% increase in the initial investment amount affect the 4% retirement withdrawal?", "_____no_output_____" ] ], [ [ "# YOUR CODE HERE\n#50% increase in initial investment\ninvest_increase = 0.50\n#initial_investment_2 = initial_investment * (1 + invest_increase)\n#effect of increase in initial investment \n\nexpected_yearly_withdrawal = expected_roi_10th_usd * yearly_withdraw_rate\n#New expected returns for 10th percentile in USD\n\nnew_expected_roi_10th_usd = (initial_investment * (1 + invest_increase)) * new_conf_interval.iloc[0]\n\nnew_expected_yearly_withdrawal = new_expected_roi_10th_usd * yearly_withdraw_rate\n# printint the effect of higher initial investment\n\nif (new_expected_yearly_withdrawal > expected_yearly_withdrawal):\n print(f\"Initial investment increase by 50% results with higher 4% retirement withdrawall for ${new_expected_yearly_withdrawal - expected_yearly_withdrawal:,.2f}!!!\")\nelse:\n print(f\"Initial investment increase by 50% results with lower 4% retirement withdrawall for ${new_expected_yearly_withdrawal - expected_yearly_withdrawal:,.2f}\")", "Initial investment increase by 50% results with higher 4% retirement withdrawall for $23,569.95!!!\n" ] ], [ [ "### Optional Challenge\n\nIn this section, you will calculate and plot the cumulative returns for the median and 90% confidence intervals. This plot shows the expected cumulative returns for any given day between the first day and the last day of investment. ", "_____no_output_____" ] ], [ [ "# YOUR CODE HERE\n#pseudocode: calculate the cumulative return based on new, increased amount of investment;\n #calculate new confidence interval for 50% and 90%,\n #then calculate new expected returns for confidence intervasl [0.5, 0.9], \n #next step is to plot the data for the whole investment range\n\n#new_initial_investment = 30_000\n#new_conf_interval = ending_roi_cumulative.quantile(q=[0.5,0.9])\n\n#new_expected_roi_50th_usd = new_initial_investment * new_conf_interval.iloc[0]\n#new_expected_roi_90th_usd = new_initial_investment * new_conf_interval.iloc[1]\n\n\n", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a51a76ffe47d02f6bd7c13720b1c8633b28b877
71,881
ipynb
Jupyter Notebook
notebooks/01-weekend_movie_trip.ipynb
daltonhahn/eecs731-weekend_movie_trip
462333b64971cc6ed370225cc67b6ef2a3d06971
[ "MIT" ]
null
null
null
notebooks/01-weekend_movie_trip.ipynb
daltonhahn/eecs731-weekend_movie_trip
462333b64971cc6ed370225cc67b6ef2a3d06971
[ "MIT" ]
null
null
null
notebooks/01-weekend_movie_trip.ipynb
daltonhahn/eecs731-weekend_movie_trip
462333b64971cc6ed370225cc67b6ef2a3d06971
[ "MIT" ]
null
null
null
39.735213
14,696
0.449757
[ [ [ "# Weekend Movie Trip\n\nDalton Hahn (2762306)", "_____no_output_____" ], [ "## MovieLens Datasets\n\nMovieLens Latest-Small Dataset\nhttp://files.grouplens.org/datasets/movielens/ml-latest-small.zip", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport datetime as dt\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport math\nfrom statistics import mean, stdev", "_____no_output_____" ] ], [ [ "## Read in the Data", "_____no_output_____" ] ], [ [ "df_links = pd.read_csv(\"../data/external/links.csv\")\ndf_links.head()", "_____no_output_____" ], [ "df_movies = pd.read_csv(\"../data/external/movies.csv\")\ndf_movies.head()", "_____no_output_____" ], [ "df_ratings = pd.read_csv(\"../data/external/ratings.csv\")\ndf_ratings.head()", "_____no_output_____" ], [ "df_tags = pd.read_csv(\"../data/external/tags.csv\")\ndf_tags.head()", "_____no_output_____" ] ], [ [ "## TO-DO List\n1. Separate movie title into title and a new column for year (df_movies)\n2. Separate movie genres into actual list instead of weird text with bars (19 unique genres - 18 + no genre) (df_movies)\n3. Timestamp may not be super relevant (may drop column)\n4. Correlate columns that are similar/the same, create one dataframe with all important features\n5. Links table almost completely useless, just correlates movies IDs to IMDB IDs and TheMovieDB IDs", "_____no_output_____" ], [ "## Data Processing", "_____no_output_____" ] ], [ [ "# 1. Separate movie title into title and year\n\ndf_movies['Year'] = df_movies.title.str.extract(pat='\\((\\d+)\\)')\ndf_movies.head()", "_____no_output_____" ], [ "one_hot = df_movies.genres.str.get_dummies()\ndf_movies = df_movies.join(one_hot)\ndf_movies.head()", "_____no_output_____" ], [ "# 2. Separate genres into a true list of genres\n\ngenres_full = []\n\nfor row in df_movies.iterrows():\n genre_list = row[1][\"genres\"].split(\"|\")\n genres_full.append(genre_list)\n \ndf_movies.insert(len(df_movies.columns), 'Genres', genres_full, True)\n\n# Kept all data, can safely drop the original genres column\ndf_movies = df_movies.drop(axis=1, columns='genres')\ndf_movies.head()", "_____no_output_____" ], [ "genre_lookup = {\"Action\": 1,\n \"Adventure\": 2,\n \"Animation\": 3,\n \"Children\": 4,\n \"Comedy\": 5,\n \"Crime\": 6,\n \"Documentary\": 7,\n \"Drama\": 8,\n \"Fantasy\": 9,\n \"Film-Noir\": 10,\n \"Horror\": 11,\n \"Musical\": 12,\n \"Mystery\": 13,\n \"Romance\": 14,\n \"Sci-Fi\": 15,\n \"Thriller\": 16,\n \"War\": 17,\n \"Western\": 18,\n \"IMAX\": 19,\n \"(no genres listed)\": 20\n }\n\ngenre_codes = []\nmovie_genre = []\n\nfor row in df_movies.iterrows():\n for genre in row[1]['Genres']:\n movie_genre.append(genre_lookup[genre])\n genre_codes.append(movie_genre)\n movie_genre = []\n \n \nnumeric_genres = pd.Series(genre_codes)\ndf_movies.insert(len(df_movies.columns), 'GenreCodes', numeric_genres, True)\n\ndf_movies.head()", "_____no_output_____" ], [ "# 3. Timestamp doesn't seem to be a relevant column, dropping\n\ndf_tags = df_tags.drop(axis=1, columns='timestamp')\ndf_tags.head()", "_____no_output_____" ], [ "# 3. Timestamp doesn't seem to be a relevant column, dropping\n\ndf_ratings = df_ratings.drop(axis=1, columns='timestamp')\ndf_ratings.head()", "_____no_output_____" ] ], [ [ "## Finding the distribution within genre", "_____no_output_____" ] ], [ [ "# CORRECTION FROM DOCUMENTATION - No \"Children's\" genre, actually \"Children\"\n# CORRECTION FROM DOCUMENTATION - Unaccounted genre: IMAX\n\ngenre_dict = { \"Action\": 0,\n \"Adventure\": 0,\n \"Animation\": 0,\n \"Children\": 0,\n \"Comedy\": 0,\n \"Crime\": 0,\n \"Documentary\": 0,\n \"Drama\": 0,\n \"Fantasy\": 0,\n \"Film-Noir\": 0,\n \"Horror\": 0,\n \"Musical\": 0,\n \"Mystery\": 0,\n \"Romance\": 0,\n \"Sci-Fi\": 0,\n \"Thriller\": 0,\n \"War\": 0,\n \"Western\": 0,\n \"IMAX\": 0,\n \"(no genres listed)\": 0\n }\n\nfor row in df_movies.iterrows():\n for genre in row[1][\"Genres\"]:\n genre_dict[genre] = genre_dict[genre] + 1\n \n#for genre, count in genre_dict.items(): \n# print(genre, \":\", count) \n\nplt.figure(figsize=(20,5))\nplt.bar(range(len(genre_dict)), list(genre_dict.values()), align='center')\nplt.xticks(range(len(genre_dict)), list(genre_dict.keys()))\nplt.show()", "_____no_output_____" ] ], [ [ "## NOTE: By removing the year portion of the df_movies dataframe originally, I created an issue with dictionaries because there are some movie remakes that create an issue. Will incorporate the year back into the title as well, but keep the year column separate still.", "_____no_output_____" ] ], [ [ "print(len(df_movies['title'].unique()))\nprint(len(df_movies['title']))", "9737\n9742\n" ] ], [ [ "### Even when trying to keep movie title unique according to title+year, still having duplicate values. Will remove these rows and continue on.", "_____no_output_____" ] ], [ [ "print(df_movies.shape)\ndf_movies = df_movies.drop_duplicates(subset=\"title\")\nprint(df_movies.shape)", "(9742, 25)\n(9737, 25)\n" ], [ "\n# Find average rating for each movie and create column\n\nmovie_rates = list()\n\nfor movie in df_movies.iterrows(): # movieId, Year, Title, Genres\n rel_ratings = df_ratings[df_ratings.movieId == movie[1]['movieId']]\n if len(rel_ratings['rating']) == 0:\n movie_rates.append(0)\n else:\n movie_rates.append(mean(rel_ratings['rating']))\n\n \n#numeric_genres = pd.Series(genre_codes)\ndf_movies.insert(len(df_movies.columns), 'AvRate', movie_rates, True)", "_____no_output_____" ] ], [ [ "## Dealing with tags being more of a headache than it's worth for the dataset, going to proceed with clustering based on year and genre list, but have tags in their string form", "_____no_output_____" ] ], [ [ "df_movies.head()", "_____no_output_____" ], [ "df_movies.to_csv(\"../data/processed/movies_processed.csv\")", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
4a51de5d52878af0640eb8561ebdee7aa891243f
24,289
ipynb
Jupyter Notebook
7.19.ipynb
zwj1111/python
da067f61262e4e075766adbcca27f85a04446a9b
[ "Apache-2.0" ]
null
null
null
7.19.ipynb
zwj1111/python
da067f61262e4e075766adbcca27f85a04446a9b
[ "Apache-2.0" ]
null
null
null
7.19.ipynb
zwj1111/python
da067f61262e4e075766adbcca27f85a04446a9b
[ "Apache-2.0" ]
null
null
null
17.116984
156
0.381201
[ [ [ "# 循环\n- 循环是一种控制语句块重复执行的结构\n- while 适用于广度遍历\n- for 开发中经常使用", "_____no_output_____" ], [ "## while 循环\n- 当一个条件保持真的时候while循环重复执行语句\n- while 循环一定要有结束条件,否则很容易进入死循环\n- while 循环的语法是:\n\n while loop-contunuation-conndition:\n\n Statement", "_____no_output_____" ] ], [ [ "master-works", "_____no_output_____" ], [ "i = 0\nwhile i<10:\n print('hahah')\n i += 1", "hahah\nhahah\nhahah\nhahah\nhahah\nhahah\nhahah\nhahah\nhahah\nhahah\n" ] ], [ [ "## 示例:\nsum = 0\n\ni = 1\n\nwhile i <10:\n\n sum = sum + i\n i = i + 1", "_____no_output_____" ], [ "## 错误示例:\nsum = 0\n\ni = 1\n\nwhile i <10:\n\n sum = sum + i\n\ni = i + 1\n- 一旦进入死循环可按 Ctrl + c 停止", "_____no_output_____" ], [ "## EP:\n![](../Photo/143.png)\n![](../Photo/144.png)", "_____no_output_____" ] ], [ [ "count = 0\nwhile count <100:\n print(count)", "_____no_output_____" ] ], [ [ "# 验证码\n- 随机产生四个字母的验证码,如果正确,输出验证码正确。如果错误,产生新的验证码,用户重新输入。\n- 验证码只能输入三次,如果三次都错,返回“别爬了,我们小网站没什么好爬的”\n- 密码登录,如果三次错误,账号被锁定\n", "_____no_output_____" ] ], [ [ "i=1\nwhile i<=10:\n print('ahahh')\n if i==5:\n break\n else:\n i += 1", "ahahh\nahahh\nahahh\nahahh\nahahh\n" ], [ "import random", "_____no_output_____" ], [ "h=random.randint(0,9)\nw=random.randint(0,9)\ny=random.randint(0,9)\no=random.randint(0,9)\nprint(h)\nprint(w)\nprint(y)\nprint(o)\nx1,x2,x3,x4=eval(input('输入四个数字验证码:'))\nwhile 1:\n if x1==h and x2==w and x3==y and x4==o:\n print('正确')\n break\n else:\n h=random.randint(0,9)\n w=random.randint(0,9)\n y=random.randint(0,9)\n o=random.randint(0,9)\n x1,x2,x3,x4=eval(input('输入四个数字验证码:'))\n \n \n \n \n ", "7\n1\n9\n8\n输入四个数字验证码:7,1,9,8\n正确\n" ], [ "shu=random", "_____no_output_____" ], [ "num=random.randint(1000,9999)\nprint(num)\nb=eval(input(\"请输入验证码\"))\nif num==b:\n print('正确')\nfor i in range(2):\n num=random.randint(1000,9999)\n b=eval(input(\"请输入验证码\"))\n if num==b:\n break\n else:\n num=random.randint(1000,9999)\n b=eval(input(\"请输入验证码\"))\n if num!=b:\n print('别爬了')\n break\n \n \n \n \n ", "1037\n请输入验证码9087\n请输入验证码8907\n请输入验证码6789\n别爬了\n" ] ], [ [ "###### ", "_____no_output_____" ] ], [ [ "for i in range(3):\n print(i)\n if i == 2:\n print('xxx')", "0\n1\n2\nxxx\n" ], [ "for i in range(10):\n print(i)\n if i == 5:\n break\nelse:\n print('hahahah')", "0\n1\n2\n3\n4\n5\n" ] ], [ [ "## 尝试死循环", "_____no_output_____" ], [ "## 实例研究:猜数字\n- 你将要编写一个能够随机生成一个0到10之间的且包括两者的数字程序,这个程序\n- 提示用户连续地输入数字直到正确,且提示用户输入的数字是过高还是过低", "_____no_output_____" ], [ "## 使用哨兵值来控制循环\n- 哨兵值来表明输入的结束\n- ![](../Photo/54.png)", "_____no_output_____" ], [ "## 警告\n![](../Photo/55.png)", "_____no_output_____" ], [ "## for 循环\n- Python的for 循环通过一个序列中的每个值来进行迭代\n- range(a,b,k), a,b,k 必须为整数\n- a: start\n- b: end\n- k: step\n- 注意for 是循环一切可迭代对象,而不是只能使用range", "_____no_output_____" ] ], [ [ "for i in range(10):\n print(i)", "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n" ], [ "for i in range(0,10,2):\n print(i)", "0\n2\n4\n6\n8\n" ], [ "for i in range(1,10,2):\n print(i)", "1\n3\n5\n7\n9\n" ], [ "for i in range(10,1,-1):\n print(i)", "10\n9\n8\n7\n6\n5\n4\n3\n2\n" ], [ "for i in range(9,0,-2):\n print(i)", "9\n7\n5\n3\n1\n" ], [ "for i in range(10):\n print('Joker is a man')", "Joker is a man\nJoker is a man\nJoker is a man\nJoker is a man\nJoker is a man\nJoker is a man\nJoker is a man\nJoker is a man\nJoker is a man\nJoker is a man\n" ], [ "a = 100\na.__ite\n", "_____no_output_____" ], [ "bb = 'Joker'\nbb.__iter__()", "_____no_output_____" ], [ "for i in bb:\n print(i)", "J\no\nk\ne\nr\n" ], [ "c = [1,2,3]\nc.__iter__()", "_____no_output_____" ], [ "for i in c:\n print(i)", "1\n2\n3\n" ] ], [ [ "# 在Python里面一切皆对象", "_____no_output_____" ] ], [ [ "sum = 0\ni = 0\nwhile i<1001:\n sum = sum + i\n i = i +1\nprint(sum)", "500500\n" ], [ "sum = 0\nfor i in range(10001):\n sum += i\n if sum>10000:\n break\nprint(sum)\n ", "10011\n" ] ], [ [ "sum ", "_____no_output_____" ], [ "## EP:\n- ![](../Photo/145.png)", "_____no_output_____" ], [ "## 嵌套循环\n- 一个循环可以嵌套另一个循环\n- 每次循环外层时,内层循环都会被刷新重新完成循环\n- 也就是说,大循环执行一次,小循环会全部执行一次\n- 注意:\n> - 多层循环非常耗时\n - 最多使用3层循环", "_____no_output_____" ], [ "## EP:\n- 使用多层循环完成9X9乘法表\n- 显示50以内所有的素数", "_____no_output_____" ] ], [ [ "\nfor i in range(1,10):\n for j in range(1,i+1):\n k=i*j\n print(i,'x',j,'=',k,end=' ')\n print()\n ", "1 x 1 = 1 \n2 x 1 = 2 2 x 2 = 4 \n3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 \n4 x 1 = 4 4 x 2 = 8 4 x 3 = 12 4 x 4 = 16 \n5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 \n6 x 1 = 6 6 x 2 = 12 6 x 3 = 18 6 x 4 = 24 6 x 5 = 30 6 x 6 = 36 \n7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 \n8 x 1 = 8 8 x 2 = 16 8 x 3 = 24 8 x 4 = 32 8 x 5 = 40 8 x 6 = 48 8 x 7 = 56 8 x 8 = 64 \n9 x 1 = 9 9 x 2 = 18 9 x 3 = 27 9 x 4 = 36 9 x 5 = 45 9 x 6 = 54 9 x 7 = 63 9 x 8 = 72 9 x 9 = 81 \n" ], [ " \nfor i in range(2,51):\n for j in range(2,i):\n if i%j == 0:\n break\np\n \n ", "_____no_output_____" ] ], [ [ "## 关键字 break 和 continue\n- break 跳出循环,终止循环\n- continue 跳出此次循环,继续执行", "_____no_output_____" ] ], [ [ "for i in range(10):\n if i == 5:\n break\nprint(i)", "5\n" ], [ "for i in range(10):\n if i == 5:\n break\n print(i)", "0\n1\n2\n3\n4\n" ], [ "for i in range(10):\n if i ==5:\n continue(跳过)\n print(i)", "0\n1\n2\n3\n4\n6\n7\n8\n9\n" ], [ "for i in range(10):\n if i ==5:\n continue\nprint(i)", "9\n" ], [ "for i in range(10):\n for j in range(10):\n print(i,j)", "0 0\n0 1\n0 2\n0 3\n0 4\n0 5\n0 6\n0 7\n0 8\n0 9\n1 0\n1 1\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n2 0\n2 1\n2 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n3 0\n3 1\n3 2\n3 3\n3 4\n3 5\n3 6\n3 7\n3 8\n3 9\n4 0\n4 1\n4 2\n4 3\n4 4\n4 5\n4 6\n4 7\n4 8\n4 9\n5 0\n5 1\n5 2\n5 3\n5 4\n5 5\n5 6\n5 7\n5 8\n5 9\n6 0\n6 1\n6 2\n6 3\n6 4\n6 5\n6 6\n6 7\n6 8\n6 9\n7 0\n7 1\n7 2\n7 3\n7 4\n7 5\n7 6\n7 7\n7 8\n7 9\n8 0\n8 1\n8 2\n8 3\n8 4\n8 5\n8 6\n8 7\n8 8\n8 9\n9 0\n9 1\n9 2\n9 3\n9 4\n9 5\n9 6\n9 7\n9 8\n9 9\n" ] ], [ [ "## 注意\n![](../Photo/56.png)\n![](../Photo/57.png)", "_____no_output_____" ], [ "# Homework\n- 1 \n![](../Photo/58.png)", "_____no_output_____" ], [ "- 2\n![](../Photo/59.png)", "_____no_output_____" ] ], [ [ "xuefei = 10000\nfor i in range(10):\n xuefei = xuefei + xuefei*(5/100)\n i = i +1\n if i>10:\n break\nprint(round(xuefei,3))\n\n", "16288.946\n" ] ], [ [ "- 4\n![](../Photo/60.png)", "_____no_output_____" ] ], [ [ "t=0\nfor i in range(100,1000):\n if i%5==0 and i%6==0:\n print(i,end=' ')\n t = t+1\n if t%10==0:\n print()\n", "120 150 180 210 240 270 300 330 360 390 \n420 450 480 510 540 570 600 630 660 690 \n720 750 780 810 840 870 900 930 960 990 \n" ] ], [ [ "- 5\n![](../Photo/61.png)", "_____no_output_____" ] ], [ [ "n=1\nwhile n*n<12000:\n n=n+1\n continue\nprint(n)", "110\n" ], [ "n=1\nwhile n*n*n<12000:\n n=n+1\n continue\nprint(n-1)", "22\n" ] ], [ [ "- 6\n![](../Photo/62.png)", "_____no_output_____" ] ], [ [ "daikuan=eval(input('Loan Amount:'))\nnian=eval(input('Number of Years:'))\n", "_____no_output_____" ] ], [ [ "- 7\n![](../Photo/63.png)", "_____no_output_____" ] ], [ [ "b=0\nfor i in range(1,50001,1):\n b=b+1/i\nprint(b)", "11.397003949278504\n" ], [ "b=0\nfor i in range(50000,0,-1):\n b=b+1/i\nprint(b)", "11.397003949278519\n" ] ], [ [ "- 8\n![](../Photo/64.png)", "_____no_output_____" ] ], [ [ "a=0\nfor i in range(3,100,2):\n a=a+(i-2)/i\nprint(a)", "45.124450303050196\n" ] ], [ [ "- 9\n![](../Photo/65.png)", "_____no_output_____" ] ], [ [ "b=0\nfor i in range()", "_____no_output_____" ] ], [ [ "- 10 \n![](../Photo/66.png)", "_____no_output_____" ] ], [ [ "for i in range(1,10000):\n a = 0\n for b in range(1,i):\n if i%b==0:\n a=a+b\n if a==i:\n print(i)ui", "6\n28\n496\n8128\n" ] ], [ [ "- 11\n![](../Photo/67.png)", "_____no_output_____" ] ], [ [ "for i in range(1,8):\n for j in range(1,8):\n print(i,j)", "1 1\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n2 1\n2 2\n2 3\n2 4\n2 5\n2 6\n2 7\n3 1\n3 2\n3 3\n3 4\n3 5\n3 6\n3 7\n4 1\n4 2\n4 3\n4 4\n4 5\n4 6\n4 7\n5 1\n5 2\n5 3\n5 4\n5 5\n5 6\n5 7\n6 1\n6 2\n6 3\n6 4\n6 5\n6 6\n6 7\n7 1\n7 2\n7 3\n7 4\n7 5\n7 6\n7 7\n" ] ], [ [ "- 12\n![](../Photo/68.png)", "_____no_output_____" ] ], [ [ "diyi=eval(input('Enter ten numbers;'))\ndier=eval(input(''))\ndisan=eval(input(''))\ndisi=eval(input(''))\ndiwu=eval(input(''))\ndiliu=eval(input(''))\ndiqi=eval(input(''))\ndiba=eval(input(''))\ndijiu=eval(input(''))\ndishi=eval(input(''))\njunzhi=(diyi+dier+disan+disi+diwu+diliu+diqi+diba+dijiu+dishi)/10\na=(diyi-junzhi)*(diyi-junzhi)+(dier-junzhi)*(dier-junzhi)+(disi-junzhi)*(disi-junzhi)+(disan-junzhi)*(disan-junzhi)+(diwu-junzhi)*(diwu-junzhi)\nb=(diliu-junzhi)*(diliu-junzhi)+(diqi-junzhi)*(diqi-junzhi)+(diba-junzhi)*(diba-junzhi)+(dijiu-junzhi)*(dijiu-junzhi)+(dishi-junzhi)*(dishi-junzhi)\nh=((1/9)*(a+b))**0.5\nprint('The mean is:',junzhi)\nprint('The standard deviation is:',round(h,2))", "Enter ten numbers;1\n2\n3\n5.5\n5.6\n6\n7\n8\n9\n10\nThe mean is: 5.71\nThe standard deviation is: 2.97\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a52022b50a4c2d049fcdced7e3753df58fa752b
83,674
ipynb
Jupyter Notebook
1.0-ak-extract-titanic-data.ipynb
britt78/titanic
42ff29a2f8f8fe8c60527cf12523e5a170febaff
[ "MIT" ]
null
null
null
1.0-ak-extract-titanic-data.ipynb
britt78/titanic
42ff29a2f8f8fe8c60527cf12523e5a170febaff
[ "MIT" ]
null
null
null
1.0-ak-extract-titanic-data.ipynb
britt78/titanic
42ff29a2f8f8fe8c60527cf12523e5a170febaff
[ "MIT" ]
null
null
null
66.513514
378
0.579917
[ [ [ "## Extracting Titanic Disaster Data From Kaggle", "_____no_output_____" ] ], [ [ "!pip install python-dotenv", "\u001b[33mDEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support\u001b[0m\nCollecting python-dotenv\n Downloading https://files.pythonhosted.org/packages/7f/ee/e0cd2d8ba548e4c3e8c9e70d76e423b3e8b8e4eec351f51292d828c735d2/python_dotenv-0.12.0-py2.py3-none-any.whl\nRequirement already satisfied: typing; python_version < \"3.5\" in /opt/anaconda2/lib/python2.7/site-packages (from python-dotenv) (3.7.4.1)\nInstalling collected packages: python-dotenv\nSuccessfully installed python-dotenv-0.12.0\n" ], [ "from dotenv import load_dotenv, find_dotenv", "_____no_output_____" ], [ "# find .env automatically by walking up directories until it's found\ndotenv_path = find_dotenv()\n# load up the entries as environment variables\nload_dotenv(dotenv_path)", "_____no_output_____" ], [ "# extracting environment variable using os.environ.get\nimport os\nKAGGLE_USERNAME = os.environ.get(\"KAGGLE_USERNAME\")\nprint(KAGGLE_USERNAME)", "ENTER_YOUR_USERNAME\n" ], [ "# imports\nimport requests\nfrom requests import session\nimport os\nfrom dotenv import load_dotenv, find_dotenv", "_____no_output_____" ], [ "# payload for post \npayload = {\n 'action': 'login',\n 'username': os.environ.get(\"KAGGLE_USERNAME\"),\n 'password': os.environ.get(\"KAGGLE_PASSWORD\")\n}\n\n# url for train file (get the link from Kaggle website)\nurl = 'https://www.kaggle.com/c/titanic/download/train.csv'\n\n\n# setup session\nwith session() as c:\n # post request\n c.post('https://www.kaggle.com/account/login', data=payload)\n # get request\n response = c.get(url)\n # print response text\n print(response.text)", "PassengerId,Survived,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked\r\n1,0,3,\"Braund, Mr. Owen Harris\",male,22,1,0,A/5 21171,7.25,,S\r\n2,1,1,\"Cumings, Mrs. John Bradley (Florence Briggs Thayer)\",female,38,1,0,PC 17599,71.2833,C85,C\r\n3,1,3,\"Heikkinen, Miss. Laina\",female,26,0,0,STON/O2. 3101282,7.925,,S\r\n4,1,1,\"Futrelle, Mrs. Jacques Heath (Lily May Peel)\",female,35,1,0,113803,53.1,C123,S\r\n5,0,3,\"Allen, Mr. William Henry\",male,35,0,0,373450,8.05,,S\r\n6,0,3,\"Moran, Mr. James\",male,,0,0,330877,8.4583,,Q\r\n7,0,1,\"McCarthy, Mr. Timothy J\",male,54,0,0,17463,51.8625,E46,S\r\n8,0,3,\"Palsson, Master. Gosta Leonard\",male,2,3,1,349909,21.075,,S\r\n9,1,3,\"Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)\",female,27,0,2,347742,11.1333,,S\r\n10,1,2,\"Nasser, Mrs. Nicholas (Adele Achem)\",female,14,1,0,237736,30.0708,,C\r\n11,1,3,\"Sandstrom, Miss. Marguerite Rut\",female,4,1,1,PP 9549,16.7,G6,S\r\n12,1,1,\"Bonnell, Miss. Elizabeth\",female,58,0,0,113783,26.55,C103,S\r\n13,0,3,\"Saundercock, Mr. William Henry\",male,20,0,0,A/5. 2151,8.05,,S\r\n14,0,3,\"Andersson, Mr. Anders Johan\",male,39,1,5,347082,31.275,,S\r\n15,0,3,\"Vestrom, Miss. Hulda Amanda Adolfina\",female,14,0,0,350406,7.8542,,S\r\n16,1,2,\"Hewlett, Mrs. (Mary D Kingcome) \",female,55,0,0,248706,16,,S\r\n17,0,3,\"Rice, Master. Eugene\",male,2,4,1,382652,29.125,,Q\r\n18,1,2,\"Williams, Mr. Charles Eugene\",male,,0,0,244373,13,,S\r\n19,0,3,\"Vander Planke, Mrs. Julius (Emelia Maria Vandemoortele)\",female,31,1,0,345763,18,,S\r\n20,1,3,\"Masselmani, Mrs. Fatima\",female,,0,0,2649,7.225,,C\r\n21,0,2,\"Fynney, Mr. Joseph J\",male,35,0,0,239865,26,,S\r\n22,1,2,\"Beesley, Mr. Lawrence\",male,34,0,0,248698,13,D56,S\r\n23,1,3,\"McGowan, Miss. Anna \"\"Annie\"\"\",female,15,0,0,330923,8.0292,,Q\r\n24,1,1,\"Sloper, Mr. William Thompson\",male,28,0,0,113788,35.5,A6,S\r\n25,0,3,\"Palsson, Miss. Torborg Danira\",female,8,3,1,349909,21.075,,S\r\n26,1,3,\"Asplund, Mrs. Carl Oscar (Selma Augusta Emilia Johansson)\",female,38,1,5,347077,31.3875,,S\r\n27,0,3,\"Emir, Mr. Farred Chehab\",male,,0,0,2631,7.225,,C\r\n28,0,1,\"Fortune, Mr. Charles Alexander\",male,19,3,2,19950,263,C23 C25 C27,S\r\n29,1,3,\"O'Dwyer, Miss. Ellen \"\"Nellie\"\"\",female,,0,0,330959,7.8792,,Q\r\n30,0,3,\"Todoroff, Mr. Lalio\",male,,0,0,349216,7.8958,,S\r\n31,0,1,\"Uruchurtu, Don. Manuel E\",male,40,0,0,PC 17601,27.7208,,C\r\n32,1,1,\"Spencer, Mrs. William Augustus (Marie Eugenie)\",female,,1,0,PC 17569,146.5208,B78,C\r\n33,1,3,\"Glynn, Miss. Mary Agatha\",female,,0,0,335677,7.75,,Q\r\n34,0,2,\"Wheadon, Mr. Edward H\",male,66,0,0,C.A. 24579,10.5,,S\r\n35,0,1,\"Meyer, Mr. Edgar Joseph\",male,28,1,0,PC 17604,82.1708,,C\r\n36,0,1,\"Holverson, Mr. Alexander Oskar\",male,42,1,0,113789,52,,S\r\n37,1,3,\"Mamee, Mr. Hanna\",male,,0,0,2677,7.2292,,C\r\n38,0,3,\"Cann, Mr. Ernest Charles\",male,21,0,0,A./5. 2152,8.05,,S\r\n39,0,3,\"Vander Planke, Miss. Augusta Maria\",female,18,2,0,345764,18,,S\r\n40,1,3,\"Nicola-Yarred, Miss. Jamila\",female,14,1,0,2651,11.2417,,C\r\n41,0,3,\"Ahlin, Mrs. Johan (Johanna Persdotter Larsson)\",female,40,1,0,7546,9.475,,S\r\n42,0,2,\"Turpin, Mrs. William John Robert (Dorothy Ann Wonnacott)\",female,27,1,0,11668,21,,S\r\n43,0,3,\"Kraeff, Mr. Theodor\",male,,0,0,349253,7.8958,,C\r\n44,1,2,\"Laroche, Miss. Simonne Marie Anne Andree\",female,3,1,2,SC/Paris 2123,41.5792,,C\r\n45,1,3,\"Devaney, Miss. Margaret Delia\",female,19,0,0,330958,7.8792,,Q\r\n46,0,3,\"Rogers, Mr. William John\",male,,0,0,S.C./A.4. 23567,8.05,,S\r\n47,0,3,\"Lennon, Mr. Denis\",male,,1,0,370371,15.5,,Q\r\n48,1,3,\"O'Driscoll, Miss. Bridget\",female,,0,0,14311,7.75,,Q\r\n49,0,3,\"Samaan, Mr. Youssef\",male,,2,0,2662,21.6792,,C\r\n50,0,3,\"Arnold-Franchi, Mrs. Josef (Josefine Franchi)\",female,18,1,0,349237,17.8,,S\r\n51,0,3,\"Panula, Master. Juha Niilo\",male,7,4,1,3101295,39.6875,,S\r\n52,0,3,\"Nosworthy, Mr. Richard Cater\",male,21,0,0,A/4. 39886,7.8,,S\r\n53,1,1,\"Harper, Mrs. Henry Sleeper (Myna Haxtun)\",female,49,1,0,PC 17572,76.7292,D33,C\r\n54,1,2,\"Faunthorpe, Mrs. Lizzie (Elizabeth Anne Wilkinson)\",female,29,1,0,2926,26,,S\r\n55,0,1,\"Ostby, Mr. Engelhart Cornelius\",male,65,0,1,113509,61.9792,B30,C\r\n56,1,1,\"Woolner, Mr. Hugh\",male,,0,0,19947,35.5,C52,S\r\n57,1,2,\"Rugg, Miss. Emily\",female,21,0,0,C.A. 31026,10.5,,S\r\n58,0,3,\"Novel, Mr. Mansouer\",male,28.5,0,0,2697,7.2292,,C\r\n59,1,2,\"West, Miss. Constance Mirium\",female,5,1,2,C.A. 34651,27.75,,S\r\n60,0,3,\"Goodwin, Master. William Frederick\",male,11,5,2,CA 2144,46.9,,S\r\n61,0,3,\"Sirayanian, Mr. Orsen\",male,22,0,0,2669,7.2292,,C\r\n62,1,1,\"Icard, Miss. Amelie\",female,38,0,0,113572,80,B28,\r\n63,0,1,\"Harris, Mr. Henry Birkhardt\",male,45,1,0,36973,83.475,C83,S\r\n64,0,3,\"Skoog, Master. Harald\",male,4,3,2,347088,27.9,,S\r\n65,0,1,\"Stewart, Mr. Albert A\",male,,0,0,PC 17605,27.7208,,C\r\n66,1,3,\"Moubarek, Master. Gerios\",male,,1,1,2661,15.2458,,C\r\n67,1,2,\"Nye, Mrs. (Elizabeth Ramell)\",female,29,0,0,C.A. 29395,10.5,F33,S\r\n68,0,3,\"Crease, Mr. Ernest James\",male,19,0,0,S.P. 3464,8.1583,,S\r\n69,1,3,\"Andersson, Miss. Erna Alexandra\",female,17,4,2,3101281,7.925,,S\r\n70,0,3,\"Kink, Mr. Vincenz\",male,26,2,0,315151,8.6625,,S\r\n71,0,2,\"Jenkin, Mr. Stephen Curnow\",male,32,0,0,C.A. 33111,10.5,,S\r\n72,0,3,\"Goodwin, Miss. Lillian Amy\",female,16,5,2,CA 2144,46.9,,S\r\n73,0,2,\"Hood, Mr. Ambrose Jr\",male,21,0,0,S.O.C. 14879,73.5,,S\r\n74,0,3,\"Chronopoulos, Mr. Apostolos\",male,26,1,0,2680,14.4542,,C\r\n75,1,3,\"Bing, Mr. Lee\",male,32,0,0,1601,56.4958,,S\r\n76,0,3,\"Moen, Mr. Sigurd Hansen\",male,25,0,0,348123,7.65,F G73,S\r\n77,0,3,\"Staneff, Mr. Ivan\",male,,0,0,349208,7.8958,,S\r\n78,0,3,\"Moutal, Mr. Rahamin Haim\",male,,0,0,374746,8.05,,S\r\n79,1,2,\"Caldwell, Master. Alden Gates\",male,0.83,0,2,248738,29,,S\r\n80,1,3,\"Dowdell, Miss. Elizabeth\",female,30,0,0,364516,12.475,,S\r\n81,0,3,\"Waelens, Mr. Achille\",male,22,0,0,345767,9,,S\r\n82,1,3,\"Sheerlinck, Mr. Jan Baptist\",male,29,0,0,345779,9.5,,S\r\n83,1,3,\"McDermott, Miss. Brigdet Delia\",female,,0,0,330932,7.7875,,Q\r\n84,0,1,\"Carrau, Mr. Francisco M\",male,28,0,0,113059,47.1,,S\r\n85,1,2,\"Ilett, Miss. Bertha\",female,17,0,0,SO/C 14885,10.5,,S\r\n86,1,3,\"Backstrom, Mrs. Karl Alfred (Maria Mathilda Gustafsson)\",female,33,3,0,3101278,15.85,,S\r\n87,0,3,\"Ford, Mr. William Neal\",male,16,1,3,W./C. 6608,34.375,,S\r\n88,0,3,\"Slocovski, Mr. Selman Francis\",male,,0,0,SOTON/OQ 392086,8.05,,S\r\n89,1,1,\"Fortune, Miss. Mabel Helen\",female,23,3,2,19950,263,C23 C25 C27,S\r\n90,0,3,\"Celotti, Mr. Francesco\",male,24,0,0,343275,8.05,,S\r\n91,0,3,\"Christmann, Mr. Emil\",male,29,0,0,343276,8.05,,S\r\n92,0,3,\"Andreasson, Mr. Paul Edvin\",male,20,0,0,347466,7.8542,,S\r\n93,0,1,\"Chaffee, Mr. Herbert Fuller\",male,46,1,0,W.E.P. 5734,61.175,E31,S\r\n94,0,3,\"Dean, Mr. Bertram Frank\",male,26,1,2,C.A. 2315,20.575,,S\r\n95,0,3,\"Coxon, Mr. Daniel\",male,59,0,0,364500,7.25,,S\r\n96,0,3,\"Shorney, Mr. Charles Joseph\",male,,0,0,374910,8.05,,S\r\n97,0,1,\"Goldschmidt, Mr. George B\",male,71,0,0,PC 17754,34.6542,A5,C\r\n98,1,1,\"Greenfield, Mr. William Bertram\",male,23,0,1,PC 17759,63.3583,D10 D12,C\r\n99,1,2,\"Doling, Mrs. John T (Ada Julia Bone)\",female,34,0,1,231919,23,,S\r\n100,0,2,\"Kantor, Mr. Sinai\",male,34,1,0,244367,26,,S\r\n101,0,3,\"Petranec, Miss. Matilda\",female,28,0,0,349245,7.8958,,S\r\n102,0,3,\"Petroff, Mr. Pastcho (\"\"Pentcho\"\")\",male,,0,0,349215,7.8958,,S\r\n103,0,1,\"White, Mr. Richard Frasar\",male,21,0,1,35281,77.2875,D26,S\r\n104,0,3,\"Johansson, Mr. Gustaf Joel\",male,33,0,0,7540,8.6542,,S\r\n105,0,3,\"Gustafsson, Mr. Anders Vilhelm\",male,37,2,0,3101276,7.925,,S\r\n106,0,3,\"Mionoff, Mr. Stoytcho\",male,28,0,0,349207,7.8958,,S\r\n107,1,3,\"Salkjelsvik, Miss. Anna Kristine\",female,21,0,0,343120,7.65,,S\r\n108,1,3,\"Moss, Mr. Albert Johan\",male,,0,0,312991,7.775,,S\r\n109,0,3,\"Rekic, Mr. Tido\",male,38,0,0,349249,7.8958,,S\r\n110,1,3,\"Moran, Miss. Bertha\",female,,1,0,371110,24.15,,Q\r\n111,0,1,\"Porter, Mr. Walter Chamberlain\",male,47,0,0,110465,52,C110,S\r\n112,0,3,\"Zabour, Miss. Hileni\",female,14.5,1,0,2665,14.4542,,C\r\n113,0,3,\"Barton, Mr. David John\",male,22,0,0,324669,8.05,,S\r\n114,0,3,\"Jussila, Miss. Katriina\",female,20,1,0,4136,9.825,,S\r\n115,0,3,\"Attalah, Miss. Malake\",female,17,0,0,2627,14.4583,,C\r\n116,0,3,\"Pekoniemi, Mr. Edvard\",male,21,0,0,STON/O 2. 3101294,7.925,,S\r\n117,0,3,\"Connors, Mr. Patrick\",male,70.5,0,0,370369,7.75,,Q\r\n118,0,2,\"Turpin, Mr. William John Robert\",male,29,1,0,11668,21,,S\r\n119,0,1,\"Baxter, Mr. Quigg Edmond\",male,24,0,1,PC 17558,247.5208,B58 B60,C\r\n120,0,3,\"Andersson, Miss. Ellis Anna Maria\",female,2,4,2,347082,31.275,,S\r\n121,0,2,\"Hickman, Mr. Stanley George\",male,21,2,0,S.O.C. 14879,73.5,,S\r\n122,0,3,\"Moore, Mr. Leonard Charles\",male,,0,0,A4. 54510,8.05,,S\r\n123,0,2,\"Nasser, Mr. Nicholas\",male,32.5,1,0,237736,30.0708,,C\r\n124,1,2,\"Webber, Miss. Susan\",female,32.5,0,0,27267,13,E101,S\r\n125,0,1,\"White, Mr. Percival Wayland\",male,54,0,1,35281,77.2875,D26,S\r\n126,1,3,\"Nicola-Yarred, Master. Elias\",male,12,1,0,2651,11.2417,,C\r\n127,0,3,\"McMahon, Mr. Martin\",male,,0,0,370372,7.75,,Q\r\n128,1,3,\"Madsen, Mr. Fridtjof Arne\",male,24,0,0,C 17369,7.1417,,S\r\n129,1,3,\"Peter, Miss. Anna\",female,,1,1,2668,22.3583,F E69,C\r\n130,0,3,\"Ekstrom, Mr. Johan\",male,45,0,0,347061,6.975,,S\r\n131,0,3,\"Drazenoic, Mr. Jozef\",male,33,0,0,349241,7.8958,,C\r\n132,0,3,\"Coelho, Mr. Domingos Fernandeo\",male,20,0,0,SOTON/O.Q. 3101307,7.05,,S\r\n133,0,3,\"Robins, Mrs. Alexander A (Grace Charity Laury)\",female,47,1,0,A/5. 3337,14.5,,S\r\n134,1,2,\"Weisz, Mrs. Leopold (Mathilde Francoise Pede)\",female,29,1,0,228414,26,,S\r\n135,0,2,\"Sobey, Mr. Samuel James Hayden\",male,25,0,0,C.A. 29178,13,,S\r\n136,0,2,\"Richard, Mr. Emile\",male,23,0,0,SC/PARIS 2133,15.0458,,C\r\n137,1,1,\"Newsom, Miss. Helen Monypeny\",female,19,0,2,11752,26.2833,D47,S\r\n138,0,1,\"Futrelle, Mr. Jacques Heath\",male,37,1,0,113803,53.1,C123,S\r\n139,0,3,\"Osen, Mr. Olaf Elon\",male,16,0,0,7534,9.2167,,S\r\n140,0,1,\"Giglio, Mr. Victor\",male,24,0,0,PC 17593,79.2,B86,C\r\n141,0,3,\"Boulos, Mrs. Joseph (Sultana)\",female,,0,2,2678,15.2458,,C\r\n142,1,3,\"Nysten, Miss. Anna Sofia\",female,22,0,0,347081,7.75,,S\r\n143,1,3,\"Hakkarainen, Mrs. Pekka Pietari (Elin Matilda Dolck)\",female,24,1,0,STON/O2. 3101279,15.85,,S\r\n144,0,3,\"Burke, Mr. Jeremiah\",male,19,0,0,365222,6.75,,Q\r\n145,0,2,\"Andrew, Mr. Edgardo Samuel\",male,18,0,0,231945,11.5,,S\r\n146,0,2,\"Nicholls, Mr. Joseph Charles\",male,19,1,1,C.A. 33112,36.75,,S\r\n147,1,3,\"Andersson, Mr. August Edvard (\"\"Wennerstrom\"\")\",male,27,0,0,350043,7.7958,,S\r\n148,0,3,\"Ford, Miss. Robina Maggie \"\"Ruby\"\"\",female,9,2,2,W./C. 6608,34.375,,S\r\n149,0,2,\"Navratil, Mr. Michel (\"\"Louis M Hoffman\"\")\",male,36.5,0,2,230080,26,F2,S\r\n150,0,2,\"Byles, Rev. Thomas Roussel Davids\",male,42,0,0,244310,13,,S\r\n151,0,2,\"Bateman, Rev. Robert James\",male,51,0,0,S.O.P. 1166,12.525,,S\r\n152,1,1,\"Pears, Mrs. Thomas (Edith Wearne)\",female,22,1,0,113776,66.6,C2,S\r\n153,0,3,\"Meo, Mr. Alfonzo\",male,55.5,0,0,A.5. 11206,8.05,,S\r\n154,0,3,\"van Billiard, Mr. Austin Blyler\",male,40.5,0,2,A/5. 851,14.5,,S\r\n155,0,3,\"Olsen, Mr. Ole Martin\",male,,0,0,Fa 265302,7.3125,,S\r\n156,0,1,\"Williams, Mr. Charles Duane\",male,51,0,1,PC 17597,61.3792,,C\r\n157,1,3,\"Gilnagh, Miss. Katherine \"\"Katie\"\"\",female,16,0,0,35851,7.7333,,Q\r\n158,0,3,\"Corn, Mr. Harry\",male,30,0,0,SOTON/OQ 392090,8.05,,S\r\n159,0,3,\"Smiljanic, Mr. Mile\",male,,0,0,315037,8.6625,,S\r\n160,0,3,\"Sage, Master. Thomas Henry\",male,,8,2,CA. 2343,69.55,,S\r\n161,0,3,\"Cribb, Mr. John Hatfield\",male,44,0,1,371362,16.1,,S\r\n162,1,2,\"Watt, Mrs. James (Elizabeth \"\"Bessie\"\" Inglis Milne)\",female,40,0,0,C.A. 33595,15.75,,S\r\n163,0,3,\"Bengtsson, Mr. John Viktor\",male,26,0,0,347068,7.775,,S\r\n164,0,3,\"Calic, Mr. Jovo\",male,17,0,0,315093,8.6625,,S\r\n165,0,3,\"Panula, Master. Eino Viljami\",male,1,4,1,3101295,39.6875,,S\r\n166,1,3,\"Goldsmith, Master. Frank John William \"\"Frankie\"\"\",male,9,0,2,363291,20.525,,S\r\n167,1,1,\"Chibnall, Mrs. (Edith Martha Bowerman)\",female,,0,1,113505,55,E33,S\r\n168,0,3,\"Skoog, Mrs. William (Anna Bernhardina Karlsson)\",female,45,1,4,347088,27.9,,S\r\n169,0,1,\"Baumann, Mr. John D\",male,,0,0,PC 17318,25.925,,S\r\n170,0,3,\"Ling, Mr. Lee\",male,28,0,0,1601,56.4958,,S\r\n171,0,1,\"Van der hoef, Mr. Wyckoff\",male,61,0,0,111240,33.5,B19,S\r\n172,0,3,\"Rice, Master. Arthur\",male,4,4,1,382652,29.125,,Q\r\n173,1,3,\"Johnson, Miss. Eleanor Ileen\",female,1,1,1,347742,11.1333,,S\r\n174,0,3,\"Sivola, Mr. Antti Wilhelm\",male,21,0,0,STON/O 2. 3101280,7.925,,S\r\n175,0,1,\"Smith, Mr. James Clinch\",male,56,0,0,17764,30.6958,A7,C\r\n176,0,3,\"Klasen, Mr. Klas Albin\",male,18,1,1,350404,7.8542,,S\r\n177,0,3,\"Lefebre, Master. Henry Forbes\",male,,3,1,4133,25.4667,,S\r\n178,0,1,\"Isham, Miss. Ann Elizabeth\",female,50,0,0,PC 17595,28.7125,C49,C\r\n179,0,2,\"Hale, Mr. Reginald\",male,30,0,0,250653,13,,S\r\n180,0,3,\"Leonard, Mr. Lionel\",male,36,0,0,LINE,0,,S\r\n181,0,3,\"Sage, Miss. Constance Gladys\",female,,8,2,CA. 2343,69.55,,S\r\n182,0,2,\"Pernot, Mr. Rene\",male,,0,0,SC/PARIS 2131,15.05,,C\r\n183,0,3,\"Asplund, Master. Clarence Gustaf Hugo\",male,9,4,2,347077,31.3875,,S\r\n184,1,2,\"Becker, Master. Richard F\",male,1,2,1,230136,39,F4,S\r\n185,1,3,\"Kink-Heilmann, Miss. Luise Gretchen\",female,4,0,2,315153,22.025,,S\r\n186,0,1,\"Rood, Mr. Hugh Roscoe\",male,,0,0,113767,50,A32,S\r\n187,1,3,\"O'Brien, Mrs. Thomas (Johanna \"\"Hannah\"\" Godfrey)\",female,,1,0,370365,15.5,,Q\r\n188,1,1,\"Romaine, Mr. Charles Hallace (\"\"Mr C Rolmane\"\")\",male,45,0,0,111428,26.55,,S\r\n189,0,3,\"Bourke, Mr. John\",male,40,1,1,364849,15.5,,Q\r\n190,0,3,\"Turcin, Mr. Stjepan\",male,36,0,0,349247,7.8958,,S\r\n191,1,2,\"Pinsky, Mrs. (Rosa)\",female,32,0,0,234604,13,,S\r\n192,0,2,\"Carbines, Mr. William\",male,19,0,0,28424,13,,S\r\n193,1,3,\"Andersen-Jensen, Miss. Carla Christine Nielsine\",female,19,1,0,350046,7.8542,,S\r\n194,1,2,\"Navratil, Master. Michel M\",male,3,1,1,230080,26,F2,S\r\n195,1,1,\"Brown, Mrs. James Joseph (Margaret Tobin)\",female,44,0,0,PC 17610,27.7208,B4,C\r\n196,1,1,\"Lurette, Miss. Elise\",female,58,0,0,PC 17569,146.5208,B80,C\r\n197,0,3,\"Mernagh, Mr. Robert\",male,,0,0,368703,7.75,,Q\r\n198,0,3,\"Olsen, Mr. Karl Siegwart Andreas\",male,42,0,1,4579,8.4042,,S\r\n199,1,3,\"Madigan, Miss. Margaret \"\"Maggie\"\"\",female,,0,0,370370,7.75,,Q\r\n200,0,2,\"Yrois, Miss. Henriette (\"\"Mrs Harbeck\"\")\",female,24,0,0,248747,13,,S\r\n201,0,3,\"Vande Walle, Mr. Nestor Cyriel\",male,28,0,0,345770,9.5,,S\r\n202,0,3,\"Sage, Mr. Frederick\",male,,8,2,CA. 2343,69.55,,S\r\n203,0,3,\"Johanson, Mr. Jakob Alfred\",male,34,0,0,3101264,6.4958,,S\r\n204,0,3,\"Youseff, Mr. Gerious\",male,45.5,0,0,2628,7.225,,C\r\n205,1,3,\"Cohen, Mr. Gurshon \"\"Gus\"\"\",male,18,0,0,A/5 3540,8.05,,S\r\n206,0,3,\"Strom, Miss. Telma Matilda\",female,2,0,1,347054,10.4625,G6,S\r\n207,0,3,\"Backstrom, Mr. Karl Alfred\",male,32,1,0,3101278,15.85,,S\r\n208,1,3,\"Albimona, Mr. Nassef Cassem\",male,26,0,0,2699,18.7875,,C\r\n209,1,3,\"Carr, Miss. Helen \"\"Ellen\"\"\",female,16,0,0,367231,7.75,,Q\r\n210,1,1,\"Blank, Mr. Henry\",male,40,0,0,112277,31,A31,C\r\n211,0,3,\"Ali, Mr. Ahmed\",male,24,0,0,SOTON/O.Q. 3101311,7.05,,S\r\n212,1,2,\"Cameron, Miss. Clear Annie\",female,35,0,0,F.C.C. 13528,21,,S\r\n213,0,3,\"Perkin, Mr. John Henry\",male,22,0,0,A/5 21174,7.25,,S\r\n214,0,2,\"Givard, Mr. Hans Kristensen\",male,30,0,0,250646,13,,S\r\n215,0,3,\"Kiernan, Mr. Philip\",male,,1,0,367229,7.75,,Q\r\n216,1,1,\"Newell, Miss. Madeleine\",female,31,1,0,35273,113.275,D36,C\r\n217,1,3,\"Honkanen, Miss. Eliina\",female,27,0,0,STON/O2. 3101283,7.925,,S\r\n218,0,2,\"Jacobsohn, Mr. Sidney Samuel\",male,42,1,0,243847,27,,S\r\n219,1,1,\"Bazzani, Miss. Albina\",female,32,0,0,11813,76.2917,D15,C\r\n220,0,2,\"Harris, Mr. Walter\",male,30,0,0,W/C 14208,10.5,,S\r\n221,1,3,\"Sunderland, Mr. Victor Francis\",male,16,0,0,SOTON/OQ 392089,8.05,,S\r\n222,0,2,\"Bracken, Mr. James H\",male,27,0,0,220367,13,,S\r\n223,0,3,\"Green, Mr. George Henry\",male,51,0,0,21440,8.05,,S\r\n224,0,3,\"Nenkoff, Mr. Christo\",male,,0,0,349234,7.8958,,S\r\n225,1,1,\"Hoyt, Mr. Frederick Maxfield\",male,38,1,0,19943,90,C93,S\r\n226,0,3,\"Berglund, Mr. Karl Ivar Sven\",male,22,0,0,PP 4348,9.35,,S\r\n227,1,2,\"Mellors, Mr. William John\",male,19,0,0,SW/PP 751,10.5,,S\r\n228,0,3,\"Lovell, Mr. John Hall (\"\"Henry\"\")\",male,20.5,0,0,A/5 21173,7.25,,S\r\n229,0,2,\"Fahlstrom, Mr. Arne Jonas\",male,18,0,0,236171,13,,S\r\n230,0,3,\"Lefebre, Miss. Mathilde\",female,,3,1,4133,25.4667,,S\r\n231,1,1,\"Harris, Mrs. Henry Birkhardt (Irene Wallach)\",female,35,1,0,36973,83.475,C83,S\r\n232,0,3,\"Larsson, Mr. Bengt Edvin\",male,29,0,0,347067,7.775,,S\r\n233,0,2,\"Sjostedt, Mr. Ernst Adolf\",male,59,0,0,237442,13.5,,S\r\n234,1,3,\"Asplund, Miss. Lillian Gertrud\",female,5,4,2,347077,31.3875,,S\r\n235,0,2,\"Leyson, Mr. Robert William Norman\",male,24,0,0,C.A. 29566,10.5,,S\r\n236,0,3,\"Harknett, Miss. Alice Phoebe\",female,,0,0,W./C. 6609,7.55,,S\r\n237,0,2,\"Hold, Mr. Stephen\",male,44,1,0,26707,26,,S\r\n238,1,2,\"Collyer, Miss. Marjorie \"\"Lottie\"\"\",female,8,0,2,C.A. 31921,26.25,,S\r\n239,0,2,\"Pengelly, Mr. Frederick William\",male,19,0,0,28665,10.5,,S\r\n240,0,2,\"Hunt, Mr. George Henry\",male,33,0,0,SCO/W 1585,12.275,,S\r\n241,0,3,\"Zabour, Miss. Thamine\",female,,1,0,2665,14.4542,,C\r\n242,1,3,\"Murphy, Miss. Katherine \"\"Kate\"\"\",female,,1,0,367230,15.5,,Q\r\n243,0,2,\"Coleridge, Mr. Reginald Charles\",male,29,0,0,W./C. 14263,10.5,,S\r\n244,0,3,\"Maenpaa, Mr. Matti Alexanteri\",male,22,0,0,STON/O 2. 3101275,7.125,,S\r\n245,0,3,\"Attalah, Mr. Sleiman\",male,30,0,0,2694,7.225,,C\r\n246,0,1,\"Minahan, Dr. William Edward\",male,44,2,0,19928,90,C78,Q\r\n247,0,3,\"Lindahl, Miss. Agda Thorilda Viktoria\",female,25,0,0,347071,7.775,,S\r\n248,1,2,\"Hamalainen, Mrs. William (Anna)\",female,24,0,2,250649,14.5,,S\r\n249,1,1,\"Beckwith, Mr. Richard Leonard\",male,37,1,1,11751,52.5542,D35,S\r\n250,0,2,\"Carter, Rev. Ernest Courtenay\",male,54,1,0,244252,26,,S\r\n251,0,3,\"Reed, Mr. James George\",male,,0,0,362316,7.25,,S\r\n252,0,3,\"Strom, Mrs. Wilhelm (Elna Matilda Persson)\",female,29,1,1,347054,10.4625,G6,S\r\n253,0,1,\"Stead, Mr. William Thomas\",male,62,0,0,113514,26.55,C87,S\r\n254,0,3,\"Lobb, Mr. William Arthur\",male,30,1,0,A/5. 3336,16.1,,S\r\n255,0,3,\"Rosblom, Mrs. Viktor (Helena Wilhelmina)\",female,41,0,2,370129,20.2125,,S\r\n256,1,3,\"Touma, Mrs. Darwis (Hanne Youssef Razi)\",female,29,0,2,2650,15.2458,,C\r\n257,1,1,\"Thorne, Mrs. Gertrude Maybelle\",female,,0,0,PC 17585,79.2,,C\r\n258,1,1,\"Cherry, Miss. Gladys\",female,30,0,0,110152,86.5,B77,S\r\n259,1,1,\"Ward, Miss. Anna\",female,35,0,0,PC 17755,512.3292,,C\r\n260,1,2,\"Parrish, Mrs. (Lutie Davis)\",female,50,0,1,230433,26,,S\r\n261,0,3,\"Smith, Mr. Thomas\",male,,0,0,384461,7.75,,Q\r\n262,1,3,\"Asplund, Master. Edvin Rojj Felix\",male,3,4,2,347077,31.3875,,S\r\n263,0,1,\"Taussig, Mr. Emil\",male,52,1,1,110413,79.65,E67,S\r\n264,0,1,\"Harrison, Mr. William\",male,40,0,0,112059,0,B94,S\r\n265,0,3,\"Henry, Miss. Delia\",female,,0,0,382649,7.75,,Q\r\n266,0,2,\"Reeves, Mr. David\",male,36,0,0,C.A. 17248,10.5,,S\r\n267,0,3,\"Panula, Mr. Ernesti Arvid\",male,16,4,1,3101295,39.6875,,S\r\n268,1,3,\"Persson, Mr. Ernst Ulrik\",male,25,1,0,347083,7.775,,S\r\n269,1,1,\"Graham, Mrs. William Thompson (Edith Junkins)\",female,58,0,1,PC 17582,153.4625,C125,S\r\n270,1,1,\"Bissette, Miss. Amelia\",female,35,0,0,PC 17760,135.6333,C99,S\r\n271,0,1,\"Cairns, Mr. Alexander\",male,,0,0,113798,31,,S\r\n272,1,3,\"Tornquist, Mr. William Henry\",male,25,0,0,LINE,0,,S\r\n273,1,2,\"Mellinger, Mrs. (Elizabeth Anne Maidment)\",female,41,0,1,250644,19.5,,S\r\n274,0,1,\"Natsch, Mr. Charles H\",male,37,0,1,PC 17596,29.7,C118,C\r\n275,1,3,\"Healy, Miss. Hanora \"\"Nora\"\"\",female,,0,0,370375,7.75,,Q\r\n276,1,1,\"Andrews, Miss. Kornelia Theodosia\",female,63,1,0,13502,77.9583,D7,S\r\n277,0,3,\"Lindblom, Miss. Augusta Charlotta\",female,45,0,0,347073,7.75,,S\r\n278,0,2,\"Parkes, Mr. Francis \"\"Frank\"\"\",male,,0,0,239853,0,,S\r\n279,0,3,\"Rice, Master. Eric\",male,7,4,1,382652,29.125,,Q\r\n280,1,3,\"Abbott, Mrs. Stanton (Rosa Hunt)\",female,35,1,1,C.A. 2673,20.25,,S\r\n281,0,3,\"Duane, Mr. Frank\",male,65,0,0,336439,7.75,,Q\r\n282,0,3,\"Olsson, Mr. Nils Johan Goransson\",male,28,0,0,347464,7.8542,,S\r\n283,0,3,\"de Pelsmaeker, Mr. Alfons\",male,16,0,0,345778,9.5,,S\r\n284,1,3,\"Dorking, Mr. Edward Arthur\",male,19,0,0,A/5. 10482,8.05,,S\r\n285,0,1,\"Smith, Mr. Richard William\",male,,0,0,113056,26,A19,S\r\n286,0,3,\"Stankovic, Mr. Ivan\",male,33,0,0,349239,8.6625,,C\r\n287,1,3,\"de Mulder, Mr. Theodore\",male,30,0,0,345774,9.5,,S\r\n288,0,3,\"Naidenoff, Mr. Penko\",male,22,0,0,349206,7.8958,,S\r\n289,1,2,\"Hosono, Mr. Masabumi\",male,42,0,0,237798,13,,S\r\n290,1,3,\"Connolly, Miss. Kate\",female,22,0,0,370373,7.75,,Q\r\n291,1,1,\"Barber, Miss. Ellen \"\"Nellie\"\"\",female,26,0,0,19877,78.85,,S\r\n292,1,1,\"Bishop, Mrs. Dickinson H (Helen Walton)\",female,19,1,0,11967,91.0792,B49,C\r\n293,0,2,\"Levy, Mr. Rene Jacques\",male,36,0,0,SC/Paris 2163,12.875,D,C\r\n294,0,3,\"Haas, Miss. Aloisia\",female,24,0,0,349236,8.85,,S\r\n295,0,3,\"Mineff, Mr. Ivan\",male,24,0,0,349233,7.8958,,S\r\n296,0,1,\"Lewy, Mr. Ervin G\",male,,0,0,PC 17612,27.7208,,C\r\n297,0,3,\"Hanna, Mr. Mansour\",male,23.5,0,0,2693,7.2292,,C\r\n298,0,1,\"Allison, Miss. Helen Loraine\",female,2,1,2,113781,151.55,C22 C26,S\r\n299,1,1,\"Saalfeld, Mr. Adolphe\",male,,0,0,19988,30.5,C106,S\r\n300,1,1,\"Baxter, Mrs. James (Helene DeLaudeniere Chaput)\",female,50,0,1,PC 17558,247.5208,B58 B60,C\r\n301,1,3,\"Kelly, Miss. Anna Katherine \"\"Annie Kate\"\"\",female,,0,0,9234,7.75,,Q\r\n302,1,3,\"McCoy, Mr. Bernard\",male,,2,0,367226,23.25,,Q\r\n303,0,3,\"Johnson, Mr. William Cahoone Jr\",male,19,0,0,LINE,0,,S\r\n304,1,2,\"Keane, Miss. Nora A\",female,,0,0,226593,12.35,E101,Q\r\n305,0,3,\"Williams, Mr. Howard Hugh \"\"Harry\"\"\",male,,0,0,A/5 2466,8.05,,S\r\n306,1,1,\"Allison, Master. Hudson Trevor\",male,0.92,1,2,113781,151.55,C22 C26,S\r\n307,1,1,\"Fleming, Miss. Margaret\",female,,0,0,17421,110.8833,,C\r\n308,1,1,\"Penasco y Castellana, Mrs. Victor de Satode (Maria Josefa Perez de Soto y Vallejo)\",female,17,1,0,PC 17758,108.9,C65,C\r\n309,0,2,\"Abelson, Mr. Samuel\",male,30,1,0,P/PP 3381,24,,C\r\n310,1,1,\"Francatelli, Miss. Laura Mabel\",female,30,0,0,PC 17485,56.9292,E36,C\r\n311,1,1,\"Hays, Miss. Margaret Bechstein\",female,24,0,0,11767,83.1583,C54,C\r\n312,1,1,\"Ryerson, Miss. Emily Borie\",female,18,2,2,PC 17608,262.375,B57 B59 B63 B66,C\r\n313,0,2,\"Lahtinen, Mrs. William (Anna Sylfven)\",female,26,1,1,250651,26,,S\r\n314,0,3,\"Hendekovic, Mr. Ignjac\",male,28,0,0,349243,7.8958,,S\r\n315,0,2,\"Hart, Mr. Benjamin\",male,43,1,1,F.C.C. 13529,26.25,,S\r\n316,1,3,\"Nilsson, Miss. Helmina Josefina\",female,26,0,0,347470,7.8542,,S\r\n317,1,2,\"Kantor, Mrs. Sinai (Miriam Sternin)\",female,24,1,0,244367,26,,S\r\n318,0,2,\"Moraweck, Dr. Ernest\",male,54,0,0,29011,14,,S\r\n319,1,1,\"Wick, Miss. Mary Natalie\",female,31,0,2,36928,164.8667,C7,S\r\n320,1,1,\"Spedden, Mrs. Frederic Oakley (Margaretta Corning Stone)\",female,40,1,1,16966,134.5,E34,C\r\n321,0,3,\"Dennis, Mr. Samuel\",male,22,0,0,A/5 21172,7.25,,S\r\n322,0,3,\"Danoff, Mr. Yoto\",male,27,0,0,349219,7.8958,,S\r\n323,1,2,\"Slayter, Miss. Hilda Mary\",female,30,0,0,234818,12.35,,Q\r\n324,1,2,\"Caldwell, Mrs. Albert Francis (Sylvia Mae Harbaugh)\",female,22,1,1,248738,29,,S\r\n325,0,3,\"Sage, Mr. George John Jr\",male,,8,2,CA. 2343,69.55,,S\r\n326,1,1,\"Young, Miss. Marie Grice\",female,36,0,0,PC 17760,135.6333,C32,C\r\n327,0,3,\"Nysveen, Mr. Johan Hansen\",male,61,0,0,345364,6.2375,,S\r\n328,1,2,\"Ball, Mrs. (Ada E Hall)\",female,36,0,0,28551,13,D,S\r\n329,1,3,\"Goldsmith, Mrs. Frank John (Emily Alice Brown)\",female,31,1,1,363291,20.525,,S\r\n330,1,1,\"Hippach, Miss. Jean Gertrude\",female,16,0,1,111361,57.9792,B18,C\r\n331,1,3,\"McCoy, Miss. Agnes\",female,,2,0,367226,23.25,,Q\r\n332,0,1,\"Partner, Mr. Austen\",male,45.5,0,0,113043,28.5,C124,S\r\n333,0,1,\"Graham, Mr. George Edward\",male,38,0,1,PC 17582,153.4625,C91,S\r\n334,0,3,\"Vander Planke, Mr. Leo Edmondus\",male,16,2,0,345764,18,,S\r\n335,1,1,\"Frauenthal, Mrs. Henry William (Clara Heinsheimer)\",female,,1,0,PC 17611,133.65,,S\r\n336,0,3,\"Denkoff, Mr. Mitto\",male,,0,0,349225,7.8958,,S\r\n337,0,1,\"Pears, Mr. Thomas Clinton\",male,29,1,0,113776,66.6,C2,S\r\n338,1,1,\"Burns, Miss. Elizabeth Margaret\",female,41,0,0,16966,134.5,E40,C\r\n339,1,3,\"Dahl, Mr. Karl Edwart\",male,45,0,0,7598,8.05,,S\r\n340,0,1,\"Blackwell, Mr. Stephen Weart\",male,45,0,0,113784,35.5,T,S\r\n341,1,2,\"Navratil, Master. Edmond Roger\",male,2,1,1,230080,26,F2,S\r\n342,1,1,\"Fortune, Miss. Alice Elizabeth\",female,24,3,2,19950,263,C23 C25 C27,S\r\n343,0,2,\"Collander, Mr. Erik Gustaf\",male,28,0,0,248740,13,,S\r\n344,0,2,\"Sedgwick, Mr. Charles Frederick Waddington\",male,25,0,0,244361,13,,S\r\n345,0,2,\"Fox, Mr. Stanley Hubert\",male,36,0,0,229236,13,,S\r\n346,1,2,\"Brown, Miss. Amelia \"\"Mildred\"\"\",female,24,0,0,248733,13,F33,S\r\n347,1,2,\"Smith, Miss. Marion Elsie\",female,40,0,0,31418,13,,S\r\n348,1,3,\"Davison, Mrs. Thomas Henry (Mary E Finck)\",female,,1,0,386525,16.1,,S\r\n349,1,3,\"Coutts, Master. William Loch \"\"William\"\"\",male,3,1,1,C.A. 37671,15.9,,S\r\n350,0,3,\"Dimic, Mr. Jovan\",male,42,0,0,315088,8.6625,,S\r\n351,0,3,\"Odahl, Mr. Nils Martin\",male,23,0,0,7267,9.225,,S\r\n352,0,1,\"Williams-Lambert, Mr. Fletcher Fellows\",male,,0,0,113510,35,C128,S\r\n353,0,3,\"Elias, Mr. Tannous\",male,15,1,1,2695,7.2292,,C\r\n354,0,3,\"Arnold-Franchi, Mr. Josef\",male,25,1,0,349237,17.8,,S\r\n355,0,3,\"Yousif, Mr. Wazli\",male,,0,0,2647,7.225,,C\r\n356,0,3,\"Vanden Steen, Mr. Leo Peter\",male,28,0,0,345783,9.5,,S\r\n357,1,1,\"Bowerman, Miss. Elsie Edith\",female,22,0,1,113505,55,E33,S\r\n358,0,2,\"Funk, Miss. Annie Clemmer\",female,38,0,0,237671,13,,S\r\n359,1,3,\"McGovern, Miss. Mary\",female,,0,0,330931,7.8792,,Q\r\n360,1,3,\"Mockler, Miss. Helen Mary \"\"Ellie\"\"\",female,,0,0,330980,7.8792,,Q\r\n361,0,3,\"Skoog, Mr. Wilhelm\",male,40,1,4,347088,27.9,,S\r\n362,0,2,\"del Carlo, Mr. Sebastiano\",male,29,1,0,SC/PARIS 2167,27.7208,,C\r\n363,0,3,\"Barbara, Mrs. (Catherine David)\",female,45,0,1,2691,14.4542,,C\r\n364,0,3,\"Asim, Mr. Adola\",male,35,0,0,SOTON/O.Q. 3101310,7.05,,S\r\n365,0,3,\"O'Brien, Mr. Thomas\",male,,1,0,370365,15.5,,Q\r\n366,0,3,\"Adahl, Mr. Mauritz Nils Martin\",male,30,0,0,C 7076,7.25,,S\r\n367,1,1,\"Warren, Mrs. Frank Manley (Anna Sophia Atkinson)\",female,60,1,0,110813,75.25,D37,C\r\n368,1,3,\"Moussa, Mrs. (Mantoura Boulos)\",female,,0,0,2626,7.2292,,C\r\n369,1,3,\"Jermyn, Miss. Annie\",female,,0,0,14313,7.75,,Q\r\n370,1,1,\"Aubart, Mme. Leontine Pauline\",female,24,0,0,PC 17477,69.3,B35,C\r\n371,1,1,\"Harder, Mr. George Achilles\",male,25,1,0,11765,55.4417,E50,C\r\n372,0,3,\"Wiklund, Mr. Jakob Alfred\",male,18,1,0,3101267,6.4958,,S\r\n373,0,3,\"Beavan, Mr. William Thomas\",male,19,0,0,323951,8.05,,S\r\n374,0,1,\"Ringhini, Mr. Sante\",male,22,0,0,PC 17760,135.6333,,C\r\n375,0,3,\"Palsson, Miss. Stina Viola\",female,3,3,1,349909,21.075,,S\r\n376,1,1,\"Meyer, Mrs. Edgar Joseph (Leila Saks)\",female,,1,0,PC 17604,82.1708,,C\r\n377,1,3,\"Landergren, Miss. Aurora Adelia\",female,22,0,0,C 7077,7.25,,S\r\n378,0,1,\"Widener, Mr. Harry Elkins\",male,27,0,2,113503,211.5,C82,C\r\n379,0,3,\"Betros, Mr. Tannous\",male,20,0,0,2648,4.0125,,C\r\n380,0,3,\"Gustafsson, Mr. Karl Gideon\",male,19,0,0,347069,7.775,,S\r\n381,1,1,\"Bidois, Miss. Rosalie\",female,42,0,0,PC 17757,227.525,,C\r\n382,1,3,\"Nakid, Miss. Maria (\"\"Mary\"\")\",female,1,0,2,2653,15.7417,,C\r\n383,0,3,\"Tikkanen, Mr. Juho\",male,32,0,0,STON/O 2. 3101293,7.925,,S\r\n384,1,1,\"Holverson, Mrs. Alexander Oskar (Mary Aline Towner)\",female,35,1,0,113789,52,,S\r\n385,0,3,\"Plotcharsky, Mr. Vasil\",male,,0,0,349227,7.8958,,S\r\n386,0,2,\"Davies, Mr. Charles Henry\",male,18,0,0,S.O.C. 14879,73.5,,S\r\n387,0,3,\"Goodwin, Master. Sidney Leonard\",male,1,5,2,CA 2144,46.9,,S\r\n388,1,2,\"Buss, Miss. Kate\",female,36,0,0,27849,13,,S\r\n389,0,3,\"Sadlier, Mr. Matthew\",male,,0,0,367655,7.7292,,Q\r\n390,1,2,\"Lehmann, Miss. Bertha\",female,17,0,0,SC 1748,12,,C\r\n391,1,1,\"Carter, Mr. William Ernest\",male,36,1,2,113760,120,B96 B98,S\r\n392,1,3,\"Jansson, Mr. Carl Olof\",male,21,0,0,350034,7.7958,,S\r\n393,0,3,\"Gustafsson, Mr. Johan Birger\",male,28,2,0,3101277,7.925,,S\r\n394,1,1,\"Newell, Miss. Marjorie\",female,23,1,0,35273,113.275,D36,C\r\n395,1,3,\"Sandstrom, Mrs. Hjalmar (Agnes Charlotta Bengtsson)\",female,24,0,2,PP 9549,16.7,G6,S\r\n396,0,3,\"Johansson, Mr. Erik\",male,22,0,0,350052,7.7958,,S\r\n397,0,3,\"Olsson, Miss. Elina\",female,31,0,0,350407,7.8542,,S\r\n398,0,2,\"McKane, Mr. Peter David\",male,46,0,0,28403,26,,S\r\n399,0,2,\"Pain, Dr. Alfred\",male,23,0,0,244278,10.5,,S\r\n400,1,2,\"Trout, Mrs. William H (Jessie L)\",female,28,0,0,240929,12.65,,S\r\n401,1,3,\"Niskanen, Mr. Juha\",male,39,0,0,STON/O 2. 3101289,7.925,,S\r\n402,0,3,\"Adams, Mr. John\",male,26,0,0,341826,8.05,,S\r\n403,0,3,\"Jussila, Miss. Mari Aina\",female,21,1,0,4137,9.825,,S\r\n404,0,3,\"Hakkarainen, Mr. Pekka Pietari\",male,28,1,0,STON/O2. 3101279,15.85,,S\r\n405,0,3,\"Oreskovic, Miss. Marija\",female,20,0,0,315096,8.6625,,S\r\n406,0,2,\"Gale, Mr. Shadrach\",male,34,1,0,28664,21,,S\r\n407,0,3,\"Widegren, Mr. Carl/Charles Peter\",male,51,0,0,347064,7.75,,S\r\n408,1,2,\"Richards, Master. William Rowe\",male,3,1,1,29106,18.75,,S\r\n409,0,3,\"Birkeland, Mr. Hans Martin Monsen\",male,21,0,0,312992,7.775,,S\r\n410,0,3,\"Lefebre, Miss. Ida\",female,,3,1,4133,25.4667,,S\r\n411,0,3,\"Sdycoff, Mr. Todor\",male,,0,0,349222,7.8958,,S\r\n412,0,3,\"Hart, Mr. Henry\",male,,0,0,394140,6.8583,,Q\r\n413,1,1,\"Minahan, Miss. Daisy E\",female,33,1,0,19928,90,C78,Q\r\n414,0,2,\"Cunningham, Mr. Alfred Fleming\",male,,0,0,239853,0,,S\r\n415,1,3,\"Sundman, Mr. Johan Julian\",male,44,0,0,STON/O 2. 3101269,7.925,,S\r\n416,0,3,\"Meek, Mrs. Thomas (Annie Louise Rowley)\",female,,0,0,343095,8.05,,S\r\n417,1,2,\"Drew, Mrs. James Vivian (Lulu Thorne Christian)\",female,34,1,1,28220,32.5,,S\r\n418,1,2,\"Silven, Miss. Lyyli Karoliina\",female,18,0,2,250652,13,,S\r\n419,0,2,\"Matthews, Mr. William John\",male,30,0,0,28228,13,,S\r\n420,0,3,\"Van Impe, Miss. Catharina\",female,10,0,2,345773,24.15,,S\r\n421,0,3,\"Gheorgheff, Mr. Stanio\",male,,0,0,349254,7.8958,,C\r\n422,0,3,\"Charters, Mr. David\",male,21,0,0,A/5. 13032,7.7333,,Q\r\n423,0,3,\"Zimmerman, Mr. Leo\",male,29,0,0,315082,7.875,,S\r\n424,0,3,\"Danbom, Mrs. Ernst Gilbert (Anna Sigrid Maria Brogren)\",female,28,1,1,347080,14.4,,S\r\n425,0,3,\"Rosblom, Mr. Viktor Richard\",male,18,1,1,370129,20.2125,,S\r\n426,0,3,\"Wiseman, Mr. Phillippe\",male,,0,0,A/4. 34244,7.25,,S\r\n427,1,2,\"Clarke, Mrs. Charles V (Ada Maria Winfield)\",female,28,1,0,2003,26,,S\r\n428,1,2,\"Phillips, Miss. Kate Florence (\"\"Mrs Kate Louise Phillips Marshall\"\")\",female,19,0,0,250655,26,,S\r\n429,0,3,\"Flynn, Mr. James\",male,,0,0,364851,7.75,,Q\r\n430,1,3,\"Pickard, Mr. Berk (Berk Trembisky)\",male,32,0,0,SOTON/O.Q. 392078,8.05,E10,S\r\n431,1,1,\"Bjornstrom-Steffansson, Mr. Mauritz Hakan\",male,28,0,0,110564,26.55,C52,S\r\n432,1,3,\"Thorneycroft, Mrs. Percival (Florence Kate White)\",female,,1,0,376564,16.1,,S\r\n433,1,2,\"Louch, Mrs. Charles Alexander (Alice Adelaide Slow)\",female,42,1,0,SC/AH 3085,26,,S\r\n434,0,3,\"Kallio, Mr. Nikolai Erland\",male,17,0,0,STON/O 2. 3101274,7.125,,S\r\n435,0,1,\"Silvey, Mr. William Baird\",male,50,1,0,13507,55.9,E44,S\r\n436,1,1,\"Carter, Miss. Lucile Polk\",female,14,1,2,113760,120,B96 B98,S\r\n437,0,3,\"Ford, Miss. Doolina Margaret \"\"Daisy\"\"\",female,21,2,2,W./C. 6608,34.375,,S\r\n438,1,2,\"Richards, Mrs. Sidney (Emily Hocking)\",female,24,2,3,29106,18.75,,S\r\n439,0,1,\"Fortune, Mr. Mark\",male,64,1,4,19950,263,C23 C25 C27,S\r\n440,0,2,\"Kvillner, Mr. Johan Henrik Johannesson\",male,31,0,0,C.A. 18723,10.5,,S\r\n441,1,2,\"Hart, Mrs. Benjamin (Esther Ada Bloomfield)\",female,45,1,1,F.C.C. 13529,26.25,,S\r\n442,0,3,\"Hampe, Mr. Leon\",male,20,0,0,345769,9.5,,S\r\n443,0,3,\"Petterson, Mr. Johan Emil\",male,25,1,0,347076,7.775,,S\r\n444,1,2,\"Reynaldo, Ms. Encarnacion\",female,28,0,0,230434,13,,S\r\n445,1,3,\"Johannesen-Bratthammer, Mr. Bernt\",male,,0,0,65306,8.1125,,S\r\n446,1,1,\"Dodge, Master. Washington\",male,4,0,2,33638,81.8583,A34,S\r\n447,1,2,\"Mellinger, Miss. Madeleine Violet\",female,13,0,1,250644,19.5,,S\r\n448,1,1,\"Seward, Mr. Frederic Kimber\",male,34,0,0,113794,26.55,,S\r\n449,1,3,\"Baclini, Miss. Marie Catherine\",female,5,2,1,2666,19.2583,,C\r\n450,1,1,\"Peuchen, Major. Arthur Godfrey\",male,52,0,0,113786,30.5,C104,S\r\n451,0,2,\"West, Mr. Edwy Arthur\",male,36,1,2,C.A. 34651,27.75,,S\r\n452,0,3,\"Hagland, Mr. Ingvald Olai Olsen\",male,,1,0,65303,19.9667,,S\r\n453,0,1,\"Foreman, Mr. Benjamin Laventall\",male,30,0,0,113051,27.75,C111,C\r\n454,1,1,\"Goldenberg, Mr. Samuel L\",male,49,1,0,17453,89.1042,C92,C\r\n455,0,3,\"Peduzzi, Mr. Joseph\",male,,0,0,A/5 2817,8.05,,S\r\n456,1,3,\"Jalsevac, Mr. Ivan\",male,29,0,0,349240,7.8958,,C\r\n457,0,1,\"Millet, Mr. Francis Davis\",male,65,0,0,13509,26.55,E38,S\r\n458,1,1,\"Kenyon, Mrs. Frederick R (Marion)\",female,,1,0,17464,51.8625,D21,S\r\n459,1,2,\"Toomey, Miss. Ellen\",female,50,0,0,F.C.C. 13531,10.5,,S\r\n460,0,3,\"O'Connor, Mr. Maurice\",male,,0,0,371060,7.75,,Q\r\n461,1,1,\"Anderson, Mr. Harry\",male,48,0,0,19952,26.55,E12,S\r\n462,0,3,\"Morley, Mr. William\",male,34,0,0,364506,8.05,,S\r\n463,0,1,\"Gee, Mr. Arthur H\",male,47,0,0,111320,38.5,E63,S\r\n464,0,2,\"Milling, Mr. Jacob Christian\",male,48,0,0,234360,13,,S\r\n465,0,3,\"Maisner, Mr. Simon\",male,,0,0,A/S 2816,8.05,,S\r\n466,0,3,\"Goncalves, Mr. Manuel Estanslas\",male,38,0,0,SOTON/O.Q. 3101306,7.05,,S\r\n467,0,2,\"Campbell, Mr. William\",male,,0,0,239853,0,,S\r\n468,0,1,\"Smart, Mr. John Montgomery\",male,56,0,0,113792,26.55,,S\r\n469,0,3,\"Scanlan, Mr. James\",male,,0,0,36209,7.725,,Q\r\n470,1,3,\"Baclini, Miss. Helene Barbara\",female,0.75,2,1,2666,19.2583,,C\r\n471,0,3,\"Keefe, Mr. Arthur\",male,,0,0,323592,7.25,,S\r\n472,0,3,\"Cacic, Mr. Luka\",male,38,0,0,315089,8.6625,,S\r\n473,1,2,\"West, Mrs. Edwy Arthur (Ada Mary Worth)\",female,33,1,2,C.A. 34651,27.75,,S\r\n474,1,2,\"Jerwan, Mrs. Amin S (Marie Marthe Thuillard)\",female,23,0,0,SC/AH Basle 541,13.7917,D,C\r\n475,0,3,\"Strandberg, Miss. Ida Sofia\",female,22,0,0,7553,9.8375,,S\r\n476,0,1,\"Clifford, Mr. George Quincy\",male,,0,0,110465,52,A14,S\r\n477,0,2,\"Renouf, Mr. Peter Henry\",male,34,1,0,31027,21,,S\r\n478,0,3,\"Braund, Mr. Lewis Richard\",male,29,1,0,3460,7.0458,,S\r\n479,0,3,\"Karlsson, Mr. Nils August\",male,22,0,0,350060,7.5208,,S\r\n480,1,3,\"Hirvonen, Miss. Hildur E\",female,2,0,1,3101298,12.2875,,S\r\n481,0,3,\"Goodwin, Master. Harold Victor\",male,9,5,2,CA 2144,46.9,,S\r\n482,0,2,\"Frost, Mr. Anthony Wood \"\"Archie\"\"\",male,,0,0,239854,0,,S\r\n483,0,3,\"Rouse, Mr. Richard Henry\",male,50,0,0,A/5 3594,8.05,,S\r\n484,1,3,\"Turkula, Mrs. (Hedwig)\",female,63,0,0,4134,9.5875,,S\r\n485,1,1,\"Bishop, Mr. Dickinson H\",male,25,1,0,11967,91.0792,B49,C\r\n486,0,3,\"Lefebre, Miss. Jeannie\",female,,3,1,4133,25.4667,,S\r\n487,1,1,\"Hoyt, Mrs. Frederick Maxfield (Jane Anne Forby)\",female,35,1,0,19943,90,C93,S\r\n488,0,1,\"Kent, Mr. Edward Austin\",male,58,0,0,11771,29.7,B37,C\r\n489,0,3,\"Somerton, Mr. Francis William\",male,30,0,0,A.5. 18509,8.05,,S\r\n490,1,3,\"Coutts, Master. Eden Leslie \"\"Neville\"\"\",male,9,1,1,C.A. 37671,15.9,,S\r\n491,0,3,\"Hagland, Mr. Konrad Mathias Reiersen\",male,,1,0,65304,19.9667,,S\r\n492,0,3,\"Windelov, Mr. Einar\",male,21,0,0,SOTON/OQ 3101317,7.25,,S\r\n493,0,1,\"Molson, Mr. Harry Markland\",male,55,0,0,113787,30.5,C30,S\r\n494,0,1,\"Artagaveytia, Mr. Ramon\",male,71,0,0,PC 17609,49.5042,,C\r\n495,0,3,\"Stanley, Mr. Edward Roland\",male,21,0,0,A/4 45380,8.05,,S\r\n496,0,3,\"Yousseff, Mr. Gerious\",male,,0,0,2627,14.4583,,C\r\n497,1,1,\"Eustis, Miss. Elizabeth Mussey\",female,54,1,0,36947,78.2667,D20,C\r\n498,0,3,\"Shellard, Mr. Frederick William\",male,,0,0,C.A. 6212,15.1,,S\r\n499,0,1,\"Allison, Mrs. Hudson J C (Bessie Waldo Daniels)\",female,25,1,2,113781,151.55,C22 C26,S\r\n500,0,3,\"Svensson, Mr. Olof\",male,24,0,0,350035,7.7958,,S\r\n501,0,3,\"Calic, Mr. Petar\",male,17,0,0,315086,8.6625,,S\r\n502,0,3,\"Canavan, Miss. Mary\",female,21,0,0,364846,7.75,,Q\r\n503,0,3,\"O'Sullivan, Miss. Bridget Mary\",female,,0,0,330909,7.6292,,Q\r\n504,0,3,\"Laitinen, Miss. Kristina Sofia\",female,37,0,0,4135,9.5875,,S\r\n505,1,1,\"Maioni, Miss. Roberta\",female,16,0,0,110152,86.5,B79,S\r\n506,0,1,\"Penasco y Castellana, Mr. Victor de Satode\",male,18,1,0,PC 17758,108.9,C65,C\r\n507,1,2,\"Quick, Mrs. Frederick Charles (Jane Richards)\",female,33,0,2,26360,26,,S\r\n508,1,1,\"Bradley, Mr. George (\"\"George Arthur Brayton\"\")\",male,,0,0,111427,26.55,,S\r\n509,0,3,\"Olsen, Mr. Henry Margido\",male,28,0,0,C 4001,22.525,,S\r\n510,1,3,\"Lang, Mr. Fang\",male,26,0,0,1601,56.4958,,S\r\n511,1,3,\"Daly, Mr. Eugene Patrick\",male,29,0,0,382651,7.75,,Q\r\n512,0,3,\"Webber, Mr. James\",male,,0,0,SOTON/OQ 3101316,8.05,,S\r\n513,1,1,\"McGough, Mr. James Robert\",male,36,0,0,PC 17473,26.2875,E25,S\r\n514,1,1,\"Rothschild, Mrs. Martin (Elizabeth L. Barrett)\",female,54,1,0,PC 17603,59.4,,C\r\n515,0,3,\"Coleff, Mr. Satio\",male,24,0,0,349209,7.4958,,S\r\n516,0,1,\"Walker, Mr. William Anderson\",male,47,0,0,36967,34.0208,D46,S\r\n517,1,2,\"Lemore, Mrs. (Amelia Milley)\",female,34,0,0,C.A. 34260,10.5,F33,S\r\n518,0,3,\"Ryan, Mr. Patrick\",male,,0,0,371110,24.15,,Q\r\n519,1,2,\"Angle, Mrs. William A (Florence \"\"Mary\"\" Agnes Hughes)\",female,36,1,0,226875,26,,S\r\n520,0,3,\"Pavlovic, Mr. Stefo\",male,32,0,0,349242,7.8958,,S\r\n521,1,1,\"Perreault, Miss. Anne\",female,30,0,0,12749,93.5,B73,S\r\n522,0,3,\"Vovk, Mr. Janko\",male,22,0,0,349252,7.8958,,S\r\n523,0,3,\"Lahoud, Mr. Sarkis\",male,,0,0,2624,7.225,,C\r\n524,1,1,\"Hippach, Mrs. Louis Albert (Ida Sophia Fischer)\",female,44,0,1,111361,57.9792,B18,C\r\n525,0,3,\"Kassem, Mr. Fared\",male,,0,0,2700,7.2292,,C\r\n526,0,3,\"Farrell, Mr. James\",male,40.5,0,0,367232,7.75,,Q\r\n527,1,2,\"Ridsdale, Miss. Lucy\",female,50,0,0,W./C. 14258,10.5,,S\r\n528,0,1,\"Farthing, Mr. John\",male,,0,0,PC 17483,221.7792,C95,S\r\n529,0,3,\"Salonen, Mr. Johan Werner\",male,39,0,0,3101296,7.925,,S\r\n530,0,2,\"Hocking, Mr. Richard George\",male,23,2,1,29104,11.5,,S\r\n531,1,2,\"Quick, Miss. Phyllis May\",female,2,1,1,26360,26,,S\r\n532,0,3,\"Toufik, Mr. Nakli\",male,,0,0,2641,7.2292,,C\r\n533,0,3,\"Elias, Mr. Joseph Jr\",male,17,1,1,2690,7.2292,,C\r\n534,1,3,\"Peter, Mrs. Catherine (Catherine Rizk)\",female,,0,2,2668,22.3583,,C\r\n535,0,3,\"Cacic, Miss. Marija\",female,30,0,0,315084,8.6625,,S\r\n536,1,2,\"Hart, Miss. Eva Miriam\",female,7,0,2,F.C.C. 13529,26.25,,S\r\n537,0,1,\"Butt, Major. Archibald Willingham\",male,45,0,0,113050,26.55,B38,S\r\n538,1,1,\"LeRoy, Miss. Bertha\",female,30,0,0,PC 17761,106.425,,C\r\n539,0,3,\"Risien, Mr. Samuel Beard\",male,,0,0,364498,14.5,,S\r\n540,1,1,\"Frolicher, Miss. Hedwig Margaritha\",female,22,0,2,13568,49.5,B39,C\r\n541,1,1,\"Crosby, Miss. Harriet R\",female,36,0,2,WE/P 5735,71,B22,S\r\n542,0,3,\"Andersson, Miss. Ingeborg Constanzia\",female,9,4,2,347082,31.275,,S\r\n543,0,3,\"Andersson, Miss. Sigrid Elisabeth\",female,11,4,2,347082,31.275,,S\r\n544,1,2,\"Beane, Mr. Edward\",male,32,1,0,2908,26,,S\r\n545,0,1,\"Douglas, Mr. Walter Donald\",male,50,1,0,PC 17761,106.425,C86,C\r\n546,0,1,\"Nicholson, Mr. Arthur Ernest\",male,64,0,0,693,26,,S\r\n547,1,2,\"Beane, Mrs. Edward (Ethel Clarke)\",female,19,1,0,2908,26,,S\r\n548,1,2,\"Padro y Manent, Mr. Julian\",male,,0,0,SC/PARIS 2146,13.8625,,C\r\n549,0,3,\"Goldsmith, Mr. Frank John\",male,33,1,1,363291,20.525,,S\r\n550,1,2,\"Davies, Master. John Morgan Jr\",male,8,1,1,C.A. 33112,36.75,,S\r\n551,1,1,\"Thayer, Mr. John Borland Jr\",male,17,0,2,17421,110.8833,C70,C\r\n552,0,2,\"Sharp, Mr. Percival James R\",male,27,0,0,244358,26,,S\r\n553,0,3,\"O'Brien, Mr. Timothy\",male,,0,0,330979,7.8292,,Q\r\n554,1,3,\"Leeni, Mr. Fahim (\"\"Philip Zenni\"\")\",male,22,0,0,2620,7.225,,C\r\n555,1,3,\"Ohman, Miss. Velin\",female,22,0,0,347085,7.775,,S\r\n556,0,1,\"Wright, Mr. George\",male,62,0,0,113807,26.55,,S\r\n557,1,1,\"Duff Gordon, Lady. (Lucille Christiana Sutherland) (\"\"Mrs Morgan\"\")\",female,48,1,0,11755,39.6,A16,C\r\n558,0,1,\"Robbins, Mr. Victor\",male,,0,0,PC 17757,227.525,,C\r\n559,1,1,\"Taussig, Mrs. Emil (Tillie Mandelbaum)\",female,39,1,1,110413,79.65,E67,S\r\n560,1,3,\"de Messemaeker, Mrs. Guillaume Joseph (Emma)\",female,36,1,0,345572,17.4,,S\r\n561,0,3,\"Morrow, Mr. Thomas Rowan\",male,,0,0,372622,7.75,,Q\r\n562,0,3,\"Sivic, Mr. Husein\",male,40,0,0,349251,7.8958,,S\r\n563,0,2,\"Norman, Mr. Robert Douglas\",male,28,0,0,218629,13.5,,S\r\n564,0,3,\"Simmons, Mr. John\",male,,0,0,SOTON/OQ 392082,8.05,,S\r\n565,0,3,\"Meanwell, Miss. (Marion Ogden)\",female,,0,0,SOTON/O.Q. 392087,8.05,,S\r\n566,0,3,\"Davies, Mr. Alfred J\",male,24,2,0,A/4 48871,24.15,,S\r\n567,0,3,\"Stoytcheff, Mr. Ilia\",male,19,0,0,349205,7.8958,,S\r\n568,0,3,\"Palsson, Mrs. Nils (Alma Cornelia Berglund)\",female,29,0,4,349909,21.075,,S\r\n569,0,3,\"Doharr, Mr. Tannous\",male,,0,0,2686,7.2292,,C\r\n570,1,3,\"Jonsson, Mr. Carl\",male,32,0,0,350417,7.8542,,S\r\n571,1,2,\"Harris, Mr. George\",male,62,0,0,S.W./PP 752,10.5,,S\r\n572,1,1,\"Appleton, Mrs. Edward Dale (Charlotte Lamson)\",female,53,2,0,11769,51.4792,C101,S\r\n573,1,1,\"Flynn, Mr. John Irwin (\"\"Irving\"\")\",male,36,0,0,PC 17474,26.3875,E25,S\r\n574,1,3,\"Kelly, Miss. Mary\",female,,0,0,14312,7.75,,Q\r\n575,0,3,\"Rush, Mr. Alfred George John\",male,16,0,0,A/4. 20589,8.05,,S\r\n576,0,3,\"Patchett, Mr. George\",male,19,0,0,358585,14.5,,S\r\n577,1,2,\"Garside, Miss. Ethel\",female,34,0,0,243880,13,,S\r\n578,1,1,\"Silvey, Mrs. William Baird (Alice Munger)\",female,39,1,0,13507,55.9,E44,S\r\n579,0,3,\"Caram, Mrs. Joseph (Maria Elias)\",female,,1,0,2689,14.4583,,C\r\n580,1,3,\"Jussila, Mr. Eiriik\",male,32,0,0,STON/O 2. 3101286,7.925,,S\r\n581,1,2,\"Christy, Miss. Julie Rachel\",female,25,1,1,237789,30,,S\r\n582,1,1,\"Thayer, Mrs. John Borland (Marian Longstreth Morris)\",female,39,1,1,17421,110.8833,C68,C\r\n583,0,2,\"Downton, Mr. William James\",male,54,0,0,28403,26,,S\r\n584,0,1,\"Ross, Mr. John Hugo\",male,36,0,0,13049,40.125,A10,C\r\n585,0,3,\"Paulner, Mr. Uscher\",male,,0,0,3411,8.7125,,C\r\n586,1,1,\"Taussig, Miss. Ruth\",female,18,0,2,110413,79.65,E68,S\r\n587,0,2,\"Jarvis, Mr. John Denzil\",male,47,0,0,237565,15,,S\r\n588,1,1,\"Frolicher-Stehli, Mr. Maxmillian\",male,60,1,1,13567,79.2,B41,C\r\n589,0,3,\"Gilinski, Mr. Eliezer\",male,22,0,0,14973,8.05,,S\r\n590,0,3,\"Murdlin, Mr. Joseph\",male,,0,0,A./5. 3235,8.05,,S\r\n591,0,3,\"Rintamaki, Mr. Matti\",male,35,0,0,STON/O 2. 3101273,7.125,,S\r\n592,1,1,\"Stephenson, Mrs. Walter Bertram (Martha Eustis)\",female,52,1,0,36947,78.2667,D20,C\r\n593,0,3,\"Elsbury, Mr. William James\",male,47,0,0,A/5 3902,7.25,,S\r\n594,0,3,\"Bourke, Miss. Mary\",female,,0,2,364848,7.75,,Q\r\n595,0,2,\"Chapman, Mr. John Henry\",male,37,1,0,SC/AH 29037,26,,S\r\n596,0,3,\"Van Impe, Mr. Jean Baptiste\",male,36,1,1,345773,24.15,,S\r\n597,1,2,\"Leitch, Miss. Jessie Wills\",female,,0,0,248727,33,,S\r\n598,0,3,\"Johnson, Mr. Alfred\",male,49,0,0,LINE,0,,S\r\n599,0,3,\"Boulos, Mr. Hanna\",male,,0,0,2664,7.225,,C\r\n600,1,1,\"Duff Gordon, Sir. Cosmo Edmund (\"\"Mr Morgan\"\")\",male,49,1,0,PC 17485,56.9292,A20,C\r\n601,1,2,\"Jacobsohn, Mrs. Sidney Samuel (Amy Frances Christy)\",female,24,2,1,243847,27,,S\r\n602,0,3,\"Slabenoff, Mr. Petco\",male,,0,0,349214,7.8958,,S\r\n603,0,1,\"Harrington, Mr. Charles H\",male,,0,0,113796,42.4,,S\r\n604,0,3,\"Torber, Mr. Ernst William\",male,44,0,0,364511,8.05,,S\r\n605,1,1,\"Homer, Mr. Harry (\"\"Mr E Haven\"\")\",male,35,0,0,111426,26.55,,C\r\n606,0,3,\"Lindell, Mr. Edvard Bengtsson\",male,36,1,0,349910,15.55,,S\r\n607,0,3,\"Karaic, Mr. Milan\",male,30,0,0,349246,7.8958,,S\r\n608,1,1,\"Daniel, Mr. Robert Williams\",male,27,0,0,113804,30.5,,S\r\n609,1,2,\"Laroche, Mrs. Joseph (Juliette Marie Louise Lafargue)\",female,22,1,2,SC/Paris 2123,41.5792,,C\r\n610,1,1,\"Shutes, Miss. Elizabeth W\",female,40,0,0,PC 17582,153.4625,C125,S\r\n611,0,3,\"Andersson, Mrs. Anders Johan (Alfrida Konstantia Brogren)\",female,39,1,5,347082,31.275,,S\r\n612,0,3,\"Jardin, Mr. Jose Neto\",male,,0,0,SOTON/O.Q. 3101305,7.05,,S\r\n613,1,3,\"Murphy, Miss. Margaret Jane\",female,,1,0,367230,15.5,,Q\r\n614,0,3,\"Horgan, Mr. John\",male,,0,0,370377,7.75,,Q\r\n615,0,3,\"Brocklebank, Mr. William Alfred\",male,35,0,0,364512,8.05,,S\r\n616,1,2,\"Herman, Miss. Alice\",female,24,1,2,220845,65,,S\r\n617,0,3,\"Danbom, Mr. Ernst Gilbert\",male,34,1,1,347080,14.4,,S\r\n618,0,3,\"Lobb, Mrs. William Arthur (Cordelia K Stanlick)\",female,26,1,0,A/5. 3336,16.1,,S\r\n619,1,2,\"Becker, Miss. Marion Louise\",female,4,2,1,230136,39,F4,S\r\n620,0,2,\"Gavey, Mr. Lawrence\",male,26,0,0,31028,10.5,,S\r\n621,0,3,\"Yasbeck, Mr. Antoni\",male,27,1,0,2659,14.4542,,C\r\n622,1,1,\"Kimball, Mr. Edwin Nelson Jr\",male,42,1,0,11753,52.5542,D19,S\r\n623,1,3,\"Nakid, Mr. Sahid\",male,20,1,1,2653,15.7417,,C\r\n624,0,3,\"Hansen, Mr. Henry Damsgaard\",male,21,0,0,350029,7.8542,,S\r\n625,0,3,\"Bowen, Mr. David John \"\"Dai\"\"\",male,21,0,0,54636,16.1,,S\r\n626,0,1,\"Sutton, Mr. Frederick\",male,61,0,0,36963,32.3208,D50,S\r\n627,0,2,\"Kirkland, Rev. Charles Leonard\",male,57,0,0,219533,12.35,,Q\r\n628,1,1,\"Longley, Miss. Gretchen Fiske\",female,21,0,0,13502,77.9583,D9,S\r\n629,0,3,\"Bostandyeff, Mr. Guentcho\",male,26,0,0,349224,7.8958,,S\r\n630,0,3,\"O'Connell, Mr. Patrick D\",male,,0,0,334912,7.7333,,Q\r\n631,1,1,\"Barkworth, Mr. Algernon Henry Wilson\",male,80,0,0,27042,30,A23,S\r\n632,0,3,\"Lundahl, Mr. Johan Svensson\",male,51,0,0,347743,7.0542,,S\r\n633,1,1,\"Stahelin-Maeglin, Dr. Max\",male,32,0,0,13214,30.5,B50,C\r\n634,0,1,\"Parr, Mr. William Henry Marsh\",male,,0,0,112052,0,,S\r\n635,0,3,\"Skoog, Miss. Mabel\",female,9,3,2,347088,27.9,,S\r\n636,1,2,\"Davis, Miss. Mary\",female,28,0,0,237668,13,,S\r\n637,0,3,\"Leinonen, Mr. Antti Gustaf\",male,32,0,0,STON/O 2. 3101292,7.925,,S\r\n638,0,2,\"Collyer, Mr. Harvey\",male,31,1,1,C.A. 31921,26.25,,S\r\n639,0,3,\"Panula, Mrs. Juha (Maria Emilia Ojala)\",female,41,0,5,3101295,39.6875,,S\r\n640,0,3,\"Thorneycroft, Mr. Percival\",male,,1,0,376564,16.1,,S\r\n641,0,3,\"Jensen, Mr. Hans Peder\",male,20,0,0,350050,7.8542,,S\r\n642,1,1,\"Sagesser, Mlle. Emma\",female,24,0,0,PC 17477,69.3,B35,C\r\n643,0,3,\"Skoog, Miss. Margit Elizabeth\",female,2,3,2,347088,27.9,,S\r\n644,1,3,\"Foo, Mr. Choong\",male,,0,0,1601,56.4958,,S\r\n645,1,3,\"Baclini, Miss. Eugenie\",female,0.75,2,1,2666,19.2583,,C\r\n646,1,1,\"Harper, Mr. Henry Sleeper\",male,48,1,0,PC 17572,76.7292,D33,C\r\n647,0,3,\"Cor, Mr. Liudevit\",male,19,0,0,349231,7.8958,,S\r\n648,1,1,\"Simonius-Blumer, Col. Oberst Alfons\",male,56,0,0,13213,35.5,A26,C\r\n649,0,3,\"Willey, Mr. Edward\",male,,0,0,S.O./P.P. 751,7.55,,S\r\n650,1,3,\"Stanley, Miss. Amy Zillah Elsie\",female,23,0,0,CA. 2314,7.55,,S\r\n651,0,3,\"Mitkoff, Mr. Mito\",male,,0,0,349221,7.8958,,S\r\n652,1,2,\"Doling, Miss. Elsie\",female,18,0,1,231919,23,,S\r\n653,0,3,\"Kalvik, Mr. Johannes Halvorsen\",male,21,0,0,8475,8.4333,,S\r\n654,1,3,\"O'Leary, Miss. Hanora \"\"Norah\"\"\",female,,0,0,330919,7.8292,,Q\r\n655,0,3,\"Hegarty, Miss. Hanora \"\"Nora\"\"\",female,18,0,0,365226,6.75,,Q\r\n656,0,2,\"Hickman, Mr. Leonard Mark\",male,24,2,0,S.O.C. 14879,73.5,,S\r\n657,0,3,\"Radeff, Mr. Alexander\",male,,0,0,349223,7.8958,,S\r\n658,0,3,\"Bourke, Mrs. John (Catherine)\",female,32,1,1,364849,15.5,,Q\r\n659,0,2,\"Eitemiller, Mr. George Floyd\",male,23,0,0,29751,13,,S\r\n660,0,1,\"Newell, Mr. Arthur Webster\",male,58,0,2,35273,113.275,D48,C\r\n661,1,1,\"Frauenthal, Dr. Henry William\",male,50,2,0,PC 17611,133.65,,S\r\n662,0,3,\"Badt, Mr. Mohamed\",male,40,0,0,2623,7.225,,C\r\n663,0,1,\"Colley, Mr. Edward Pomeroy\",male,47,0,0,5727,25.5875,E58,S\r\n664,0,3,\"Coleff, Mr. Peju\",male,36,0,0,349210,7.4958,,S\r\n665,1,3,\"Lindqvist, Mr. Eino William\",male,20,1,0,STON/O 2. 3101285,7.925,,S\r\n666,0,2,\"Hickman, Mr. Lewis\",male,32,2,0,S.O.C. 14879,73.5,,S\r\n667,0,2,\"Butler, Mr. Reginald Fenton\",male,25,0,0,234686,13,,S\r\n668,0,3,\"Rommetvedt, Mr. Knud Paust\",male,,0,0,312993,7.775,,S\r\n669,0,3,\"Cook, Mr. Jacob\",male,43,0,0,A/5 3536,8.05,,S\r\n670,1,1,\"Taylor, Mrs. Elmer Zebley (Juliet Cummins Wright)\",female,,1,0,19996,52,C126,S\r\n671,1,2,\"Brown, Mrs. Thomas William Solomon (Elizabeth Catherine Ford)\",female,40,1,1,29750,39,,S\r\n672,0,1,\"Davidson, Mr. Thornton\",male,31,1,0,F.C. 12750,52,B71,S\r\n673,0,2,\"Mitchell, Mr. Henry Michael\",male,70,0,0,C.A. 24580,10.5,,S\r\n674,1,2,\"Wilhelms, Mr. Charles\",male,31,0,0,244270,13,,S\r\n675,0,2,\"Watson, Mr. Ennis Hastings\",male,,0,0,239856,0,,S\r\n676,0,3,\"Edvardsson, Mr. Gustaf Hjalmar\",male,18,0,0,349912,7.775,,S\r\n677,0,3,\"Sawyer, Mr. Frederick Charles\",male,24.5,0,0,342826,8.05,,S\r\n678,1,3,\"Turja, Miss. Anna Sofia\",female,18,0,0,4138,9.8417,,S\r\n679,0,3,\"Goodwin, Mrs. Frederick (Augusta Tyler)\",female,43,1,6,CA 2144,46.9,,S\r\n680,1,1,\"Cardeza, Mr. Thomas Drake Martinez\",male,36,0,1,PC 17755,512.3292,B51 B53 B55,C\r\n681,0,3,\"Peters, Miss. Katie\",female,,0,0,330935,8.1375,,Q\r\n682,1,1,\"Hassab, Mr. Hammad\",male,27,0,0,PC 17572,76.7292,D49,C\r\n683,0,3,\"Olsvigen, Mr. Thor Anderson\",male,20,0,0,6563,9.225,,S\r\n684,0,3,\"Goodwin, Mr. Charles Edward\",male,14,5,2,CA 2144,46.9,,S\r\n685,0,2,\"Brown, Mr. Thomas William Solomon\",male,60,1,1,29750,39,,S\r\n686,0,2,\"Laroche, Mr. Joseph Philippe Lemercier\",male,25,1,2,SC/Paris 2123,41.5792,,C\r\n687,0,3,\"Panula, Mr. Jaako Arnold\",male,14,4,1,3101295,39.6875,,S\r\n688,0,3,\"Dakic, Mr. Branko\",male,19,0,0,349228,10.1708,,S\r\n689,0,3,\"Fischer, Mr. Eberhard Thelander\",male,18,0,0,350036,7.7958,,S\r\n690,1,1,\"Madill, Miss. Georgette Alexandra\",female,15,0,1,24160,211.3375,B5,S\r\n691,1,1,\"Dick, Mr. Albert Adrian\",male,31,1,0,17474,57,B20,S\r\n692,1,3,\"Karun, Miss. Manca\",female,4,0,1,349256,13.4167,,C\r\n693,1,3,\"Lam, Mr. Ali\",male,,0,0,1601,56.4958,,S\r\n694,0,3,\"Saad, Mr. Khalil\",male,25,0,0,2672,7.225,,C\r\n695,0,1,\"Weir, Col. John\",male,60,0,0,113800,26.55,,S\r\n696,0,2,\"Chapman, Mr. Charles Henry\",male,52,0,0,248731,13.5,,S\r\n697,0,3,\"Kelly, Mr. James\",male,44,0,0,363592,8.05,,S\r\n698,1,3,\"Mullens, Miss. Katherine \"\"Katie\"\"\",female,,0,0,35852,7.7333,,Q\r\n699,0,1,\"Thayer, Mr. John Borland\",male,49,1,1,17421,110.8833,C68,C\r\n700,0,3,\"Humblen, Mr. Adolf Mathias Nicolai Olsen\",male,42,0,0,348121,7.65,F G63,S\r\n701,1,1,\"Astor, Mrs. John Jacob (Madeleine Talmadge Force)\",female,18,1,0,PC 17757,227.525,C62 C64,C\r\n702,1,1,\"Silverthorne, Mr. Spencer Victor\",male,35,0,0,PC 17475,26.2875,E24,S\r\n703,0,3,\"Barbara, Miss. Saiide\",female,18,0,1,2691,14.4542,,C\r\n704,0,3,\"Gallagher, Mr. Martin\",male,25,0,0,36864,7.7417,,Q\r\n705,0,3,\"Hansen, Mr. Henrik Juul\",male,26,1,0,350025,7.8542,,S\r\n706,0,2,\"Morley, Mr. Henry Samuel (\"\"Mr Henry Marshall\"\")\",male,39,0,0,250655,26,,S\r\n707,1,2,\"Kelly, Mrs. Florence \"\"Fannie\"\"\",female,45,0,0,223596,13.5,,S\r\n708,1,1,\"Calderhead, Mr. Edward Pennington\",male,42,0,0,PC 17476,26.2875,E24,S\r\n709,1,1,\"Cleaver, Miss. Alice\",female,22,0,0,113781,151.55,,S\r\n710,1,3,\"Moubarek, Master. Halim Gonios (\"\"William George\"\")\",male,,1,1,2661,15.2458,,C\r\n711,1,1,\"Mayne, Mlle. Berthe Antonine (\"\"Mrs de Villiers\"\")\",female,24,0,0,PC 17482,49.5042,C90,C\r\n712,0,1,\"Klaber, Mr. Herman\",male,,0,0,113028,26.55,C124,S\r\n713,1,1,\"Taylor, Mr. Elmer Zebley\",male,48,1,0,19996,52,C126,S\r\n714,0,3,\"Larsson, Mr. August Viktor\",male,29,0,0,7545,9.4833,,S\r\n715,0,2,\"Greenberg, Mr. Samuel\",male,52,0,0,250647,13,,S\r\n716,0,3,\"Soholt, Mr. Peter Andreas Lauritz Andersen\",male,19,0,0,348124,7.65,F G73,S\r\n717,1,1,\"Endres, Miss. Caroline Louise\",female,38,0,0,PC 17757,227.525,C45,C\r\n718,1,2,\"Troutt, Miss. Edwina Celia \"\"Winnie\"\"\",female,27,0,0,34218,10.5,E101,S\r\n719,0,3,\"McEvoy, Mr. Michael\",male,,0,0,36568,15.5,,Q\r\n720,0,3,\"Johnson, Mr. Malkolm Joackim\",male,33,0,0,347062,7.775,,S\r\n721,1,2,\"Harper, Miss. Annie Jessie \"\"Nina\"\"\",female,6,0,1,248727,33,,S\r\n722,0,3,\"Jensen, Mr. Svend Lauritz\",male,17,1,0,350048,7.0542,,S\r\n723,0,2,\"Gillespie, Mr. William Henry\",male,34,0,0,12233,13,,S\r\n724,0,2,\"Hodges, Mr. Henry Price\",male,50,0,0,250643,13,,S\r\n725,1,1,\"Chambers, Mr. Norman Campbell\",male,27,1,0,113806,53.1,E8,S\r\n726,0,3,\"Oreskovic, Mr. Luka\",male,20,0,0,315094,8.6625,,S\r\n727,1,2,\"Renouf, Mrs. Peter Henry (Lillian Jefferys)\",female,30,3,0,31027,21,,S\r\n728,1,3,\"Mannion, Miss. Margareth\",female,,0,0,36866,7.7375,,Q\r\n729,0,2,\"Bryhl, Mr. Kurt Arnold Gottfrid\",male,25,1,0,236853,26,,S\r\n730,0,3,\"Ilmakangas, Miss. Pieta Sofia\",female,25,1,0,STON/O2. 3101271,7.925,,S\r\n731,1,1,\"Allen, Miss. Elisabeth Walton\",female,29,0,0,24160,211.3375,B5,S\r\n732,0,3,\"Hassan, Mr. Houssein G N\",male,11,0,0,2699,18.7875,,C\r\n733,0,2,\"Knight, Mr. Robert J\",male,,0,0,239855,0,,S\r\n734,0,2,\"Berriman, Mr. William John\",male,23,0,0,28425,13,,S\r\n735,0,2,\"Troupiansky, Mr. Moses Aaron\",male,23,0,0,233639,13,,S\r\n736,0,3,\"Williams, Mr. Leslie\",male,28.5,0,0,54636,16.1,,S\r\n737,0,3,\"Ford, Mrs. Edward (Margaret Ann Watson)\",female,48,1,3,W./C. 6608,34.375,,S\r\n738,1,1,\"Lesurer, Mr. Gustave J\",male,35,0,0,PC 17755,512.3292,B101,C\r\n739,0,3,\"Ivanoff, Mr. Kanio\",male,,0,0,349201,7.8958,,S\r\n740,0,3,\"Nankoff, Mr. Minko\",male,,0,0,349218,7.8958,,S\r\n741,1,1,\"Hawksford, Mr. Walter James\",male,,0,0,16988,30,D45,S\r\n742,0,1,\"Cavendish, Mr. Tyrell William\",male,36,1,0,19877,78.85,C46,S\r\n743,1,1,\"Ryerson, Miss. Susan Parker \"\"Suzette\"\"\",female,21,2,2,PC 17608,262.375,B57 B59 B63 B66,C\r\n744,0,3,\"McNamee, Mr. Neal\",male,24,1,0,376566,16.1,,S\r\n745,1,3,\"Stranden, Mr. Juho\",male,31,0,0,STON/O 2. 3101288,7.925,,S\r\n746,0,1,\"Crosby, Capt. Edward Gifford\",male,70,1,1,WE/P 5735,71,B22,S\r\n747,0,3,\"Abbott, Mr. Rossmore Edward\",male,16,1,1,C.A. 2673,20.25,,S\r\n748,1,2,\"Sinkkonen, Miss. Anna\",female,30,0,0,250648,13,,S\r\n749,0,1,\"Marvin, Mr. Daniel Warner\",male,19,1,0,113773,53.1,D30,S\r\n750,0,3,\"Connaghton, Mr. Michael\",male,31,0,0,335097,7.75,,Q\r\n751,1,2,\"Wells, Miss. Joan\",female,4,1,1,29103,23,,S\r\n752,1,3,\"Moor, Master. Meier\",male,6,0,1,392096,12.475,E121,S\r\n753,0,3,\"Vande Velde, Mr. Johannes Joseph\",male,33,0,0,345780,9.5,,S\r\n754,0,3,\"Jonkoff, Mr. Lalio\",male,23,0,0,349204,7.8958,,S\r\n755,1,2,\"Herman, Mrs. Samuel (Jane Laver)\",female,48,1,2,220845,65,,S\r\n756,1,2,\"Hamalainen, Master. Viljo\",male,0.67,1,1,250649,14.5,,S\r\n757,0,3,\"Carlsson, Mr. August Sigfrid\",male,28,0,0,350042,7.7958,,S\r\n758,0,2,\"Bailey, Mr. Percy Andrew\",male,18,0,0,29108,11.5,,S\r\n759,0,3,\"Theobald, Mr. Thomas Leonard\",male,34,0,0,363294,8.05,,S\r\n760,1,1,\"Rothes, the Countess. of (Lucy Noel Martha Dyer-Edwards)\",female,33,0,0,110152,86.5,B77,S\r\n761,0,3,\"Garfirth, Mr. John\",male,,0,0,358585,14.5,,S\r\n762,0,3,\"Nirva, Mr. Iisakki Antino Aijo\",male,41,0,0,SOTON/O2 3101272,7.125,,S\r\n763,1,3,\"Barah, Mr. Hanna Assi\",male,20,0,0,2663,7.2292,,C\r\n764,1,1,\"Carter, Mrs. William Ernest (Lucile Polk)\",female,36,1,2,113760,120,B96 B98,S\r\n765,0,3,\"Eklund, Mr. Hans Linus\",male,16,0,0,347074,7.775,,S\r\n766,1,1,\"Hogeboom, Mrs. John C (Anna Andrews)\",female,51,1,0,13502,77.9583,D11,S\r\n767,0,1,\"Brewe, Dr. Arthur Jackson\",male,,0,0,112379,39.6,,C\r\n768,0,3,\"Mangan, Miss. Mary\",female,30.5,0,0,364850,7.75,,Q\r\n769,0,3,\"Moran, Mr. Daniel J\",male,,1,0,371110,24.15,,Q\r\n770,0,3,\"Gronnestad, Mr. Daniel Danielsen\",male,32,0,0,8471,8.3625,,S\r\n771,0,3,\"Lievens, Mr. Rene Aime\",male,24,0,0,345781,9.5,,S\r\n772,0,3,\"Jensen, Mr. Niels Peder\",male,48,0,0,350047,7.8542,,S\r\n773,0,2,\"Mack, Mrs. (Mary)\",female,57,0,0,S.O./P.P. 3,10.5,E77,S\r\n774,0,3,\"Elias, Mr. Dibo\",male,,0,0,2674,7.225,,C\r\n775,1,2,\"Hocking, Mrs. Elizabeth (Eliza Needs)\",female,54,1,3,29105,23,,S\r\n776,0,3,\"Myhrman, Mr. Pehr Fabian Oliver Malkolm\",male,18,0,0,347078,7.75,,S\r\n777,0,3,\"Tobin, Mr. Roger\",male,,0,0,383121,7.75,F38,Q\r\n778,1,3,\"Emanuel, Miss. Virginia Ethel\",female,5,0,0,364516,12.475,,S\r\n779,0,3,\"Kilgannon, Mr. Thomas J\",male,,0,0,36865,7.7375,,Q\r\n780,1,1,\"Robert, Mrs. Edward Scott (Elisabeth Walton McMillan)\",female,43,0,1,24160,211.3375,B3,S\r\n781,1,3,\"Ayoub, Miss. Banoura\",female,13,0,0,2687,7.2292,,C\r\n782,1,1,\"Dick, Mrs. Albert Adrian (Vera Gillespie)\",female,17,1,0,17474,57,B20,S\r\n783,0,1,\"Long, Mr. Milton Clyde\",male,29,0,0,113501,30,D6,S\r\n784,0,3,\"Johnston, Mr. Andrew G\",male,,1,2,W./C. 6607,23.45,,S\r\n785,0,3,\"Ali, Mr. William\",male,25,0,0,SOTON/O.Q. 3101312,7.05,,S\r\n786,0,3,\"Harmer, Mr. Abraham (David Lishin)\",male,25,0,0,374887,7.25,,S\r\n787,1,3,\"Sjoblom, Miss. Anna Sofia\",female,18,0,0,3101265,7.4958,,S\r\n788,0,3,\"Rice, Master. George Hugh\",male,8,4,1,382652,29.125,,Q\r\n789,1,3,\"Dean, Master. Bertram Vere\",male,1,1,2,C.A. 2315,20.575,,S\r\n790,0,1,\"Guggenheim, Mr. Benjamin\",male,46,0,0,PC 17593,79.2,B82 B84,C\r\n791,0,3,\"Keane, Mr. Andrew \"\"Andy\"\"\",male,,0,0,12460,7.75,,Q\r\n792,0,2,\"Gaskell, Mr. Alfred\",male,16,0,0,239865,26,,S\r\n793,0,3,\"Sage, Miss. Stella Anna\",female,,8,2,CA. 2343,69.55,,S\r\n794,0,1,\"Hoyt, Mr. William Fisher\",male,,0,0,PC 17600,30.6958,,C\r\n795,0,3,\"Dantcheff, Mr. Ristiu\",male,25,0,0,349203,7.8958,,S\r\n796,0,2,\"Otter, Mr. Richard\",male,39,0,0,28213,13,,S\r\n797,1,1,\"Leader, Dr. Alice (Farnham)\",female,49,0,0,17465,25.9292,D17,S\r\n798,1,3,\"Osman, Mrs. Mara\",female,31,0,0,349244,8.6833,,S\r\n799,0,3,\"Ibrahim Shawah, Mr. Yousseff\",male,30,0,0,2685,7.2292,,C\r\n800,0,3,\"Van Impe, Mrs. Jean Baptiste (Rosalie Paula Govaert)\",female,30,1,1,345773,24.15,,S\r\n801,0,2,\"Ponesell, Mr. Martin\",male,34,0,0,250647,13,,S\r\n802,1,2,\"Collyer, Mrs. Harvey (Charlotte Annie Tate)\",female,31,1,1,C.A. 31921,26.25,,S\r\n803,1,1,\"Carter, Master. William Thornton II\",male,11,1,2,113760,120,B96 B98,S\r\n804,1,3,\"Thomas, Master. Assad Alexander\",male,0.42,0,1,2625,8.5167,,C\r\n805,1,3,\"Hedman, Mr. Oskar Arvid\",male,27,0,0,347089,6.975,,S\r\n806,0,3,\"Johansson, Mr. Karl Johan\",male,31,0,0,347063,7.775,,S\r\n807,0,1,\"Andrews, Mr. Thomas Jr\",male,39,0,0,112050,0,A36,S\r\n808,0,3,\"Pettersson, Miss. Ellen Natalia\",female,18,0,0,347087,7.775,,S\r\n809,0,2,\"Meyer, Mr. August\",male,39,0,0,248723,13,,S\r\n810,1,1,\"Chambers, Mrs. Norman Campbell (Bertha Griggs)\",female,33,1,0,113806,53.1,E8,S\r\n811,0,3,\"Alexander, Mr. William\",male,26,0,0,3474,7.8875,,S\r\n812,0,3,\"Lester, Mr. James\",male,39,0,0,A/4 48871,24.15,,S\r\n813,0,2,\"Slemen, Mr. Richard James\",male,35,0,0,28206,10.5,,S\r\n814,0,3,\"Andersson, Miss. Ebba Iris Alfrida\",female,6,4,2,347082,31.275,,S\r\n815,0,3,\"Tomlin, Mr. Ernest Portage\",male,30.5,0,0,364499,8.05,,S\r\n816,0,1,\"Fry, Mr. Richard\",male,,0,0,112058,0,B102,S\r\n817,0,3,\"Heininen, Miss. Wendla Maria\",female,23,0,0,STON/O2. 3101290,7.925,,S\r\n818,0,2,\"Mallet, Mr. Albert\",male,31,1,1,S.C./PARIS 2079,37.0042,,C\r\n819,0,3,\"Holm, Mr. John Fredrik Alexander\",male,43,0,0,C 7075,6.45,,S\r\n820,0,3,\"Skoog, Master. Karl Thorsten\",male,10,3,2,347088,27.9,,S\r\n821,1,1,\"Hays, Mrs. Charles Melville (Clara Jennings Gregg)\",female,52,1,1,12749,93.5,B69,S\r\n822,1,3,\"Lulic, Mr. Nikola\",male,27,0,0,315098,8.6625,,S\r\n823,0,1,\"Reuchlin, Jonkheer. John George\",male,38,0,0,19972,0,,S\r\n824,1,3,\"Moor, Mrs. (Beila)\",female,27,0,1,392096,12.475,E121,S\r\n825,0,3,\"Panula, Master. Urho Abraham\",male,2,4,1,3101295,39.6875,,S\r\n826,0,3,\"Flynn, Mr. John\",male,,0,0,368323,6.95,,Q\r\n827,0,3,\"Lam, Mr. Len\",male,,0,0,1601,56.4958,,S\r\n828,1,2,\"Mallet, Master. Andre\",male,1,0,2,S.C./PARIS 2079,37.0042,,C\r\n829,1,3,\"McCormack, Mr. Thomas Joseph\",male,,0,0,367228,7.75,,Q\r\n830,1,1,\"Stone, Mrs. George Nelson (Martha Evelyn)\",female,62,0,0,113572,80,B28,\r\n831,1,3,\"Yasbeck, Mrs. Antoni (Selini Alexander)\",female,15,1,0,2659,14.4542,,C\r\n832,1,2,\"Richards, Master. George Sibley\",male,0.83,1,1,29106,18.75,,S\r\n833,0,3,\"Saad, Mr. Amin\",male,,0,0,2671,7.2292,,C\r\n834,0,3,\"Augustsson, Mr. Albert\",male,23,0,0,347468,7.8542,,S\r\n835,0,3,\"Allum, Mr. Owen George\",male,18,0,0,2223,8.3,,S\r\n836,1,1,\"Compton, Miss. Sara Rebecca\",female,39,1,1,PC 17756,83.1583,E49,C\r\n837,0,3,\"Pasic, Mr. Jakob\",male,21,0,0,315097,8.6625,,S\r\n838,0,3,\"Sirota, Mr. Maurice\",male,,0,0,392092,8.05,,S\r\n839,1,3,\"Chip, Mr. Chang\",male,32,0,0,1601,56.4958,,S\r\n840,1,1,\"Marechal, Mr. Pierre\",male,,0,0,11774,29.7,C47,C\r\n841,0,3,\"Alhomaki, Mr. Ilmari Rudolf\",male,20,0,0,SOTON/O2 3101287,7.925,,S\r\n842,0,2,\"Mudd, Mr. Thomas Charles\",male,16,0,0,S.O./P.P. 3,10.5,,S\r\n843,1,1,\"Serepeca, Miss. Augusta\",female,30,0,0,113798,31,,C\r\n844,0,3,\"Lemberopolous, Mr. Peter L\",male,34.5,0,0,2683,6.4375,,C\r\n845,0,3,\"Culumovic, Mr. Jeso\",male,17,0,0,315090,8.6625,,S\r\n846,0,3,\"Abbing, Mr. Anthony\",male,42,0,0,C.A. 5547,7.55,,S\r\n847,0,3,\"Sage, Mr. Douglas Bullen\",male,,8,2,CA. 2343,69.55,,S\r\n848,0,3,\"Markoff, Mr. Marin\",male,35,0,0,349213,7.8958,,C\r\n849,0,2,\"Harper, Rev. John\",male,28,0,1,248727,33,,S\r\n850,1,1,\"Goldenberg, Mrs. Samuel L (Edwiga Grabowska)\",female,,1,0,17453,89.1042,C92,C\r\n851,0,3,\"Andersson, Master. Sigvard Harald Elias\",male,4,4,2,347082,31.275,,S\r\n852,0,3,\"Svensson, Mr. Johan\",male,74,0,0,347060,7.775,,S\r\n853,0,3,\"Boulos, Miss. Nourelain\",female,9,1,1,2678,15.2458,,C\r\n854,1,1,\"Lines, Miss. Mary Conover\",female,16,0,1,PC 17592,39.4,D28,S\r\n855,0,2,\"Carter, Mrs. Ernest Courtenay (Lilian Hughes)\",female,44,1,0,244252,26,,S\r\n856,1,3,\"Aks, Mrs. Sam (Leah Rosen)\",female,18,0,1,392091,9.35,,S\r\n857,1,1,\"Wick, Mrs. George Dennick (Mary Hitchcock)\",female,45,1,1,36928,164.8667,,S\r\n858,1,1,\"Daly, Mr. Peter Denis \",male,51,0,0,113055,26.55,E17,S\r\n859,1,3,\"Baclini, Mrs. Solomon (Latifa Qurban)\",female,24,0,3,2666,19.2583,,C\r\n860,0,3,\"Razi, Mr. Raihed\",male,,0,0,2629,7.2292,,C\r\n861,0,3,\"Hansen, Mr. Claus Peter\",male,41,2,0,350026,14.1083,,S\r\n862,0,2,\"Giles, Mr. Frederick Edward\",male,21,1,0,28134,11.5,,S\r\n863,1,1,\"Swift, Mrs. Frederick Joel (Margaret Welles Barron)\",female,48,0,0,17466,25.9292,D17,S\r\n864,0,3,\"Sage, Miss. Dorothy Edith \"\"Dolly\"\"\",female,,8,2,CA. 2343,69.55,,S\r\n865,0,2,\"Gill, Mr. John William\",male,24,0,0,233866,13,,S\r\n866,1,2,\"Bystrom, Mrs. (Karolina)\",female,42,0,0,236852,13,,S\r\n867,1,2,\"Duran y More, Miss. Asuncion\",female,27,1,0,SC/PARIS 2149,13.8583,,C\r\n868,0,1,\"Roebling, Mr. Washington Augustus II\",male,31,0,0,PC 17590,50.4958,A24,S\r\n869,0,3,\"van Melkebeke, Mr. Philemon\",male,,0,0,345777,9.5,,S\r\n870,1,3,\"Johnson, Master. Harold Theodor\",male,4,1,1,347742,11.1333,,S\r\n871,0,3,\"Balkic, Mr. Cerin\",male,26,0,0,349248,7.8958,,S\r\n872,1,1,\"Beckwith, Mrs. Richard Leonard (Sallie Monypeny)\",female,47,1,1,11751,52.5542,D35,S\r\n873,0,1,\"Carlsson, Mr. Frans Olof\",male,33,0,0,695,5,B51 B53 B55,S\r\n874,0,3,\"Vander Cruyssen, Mr. Victor\",male,47,0,0,345765,9,,S\r\n875,1,2,\"Abelson, Mrs. Samuel (Hannah Wizosky)\",female,28,1,0,P/PP 3381,24,,C\r\n876,1,3,\"Najib, Miss. Adele Kiamie \"\"Jane\"\"\",female,15,0,0,2667,7.225,,C\r\n877,0,3,\"Gustafsson, Mr. Alfred Ossian\",male,20,0,0,7534,9.8458,,S\r\n878,0,3,\"Petroff, Mr. Nedelio\",male,19,0,0,349212,7.8958,,S\r\n879,0,3,\"Laleff, Mr. Kristo\",male,,0,0,349217,7.8958,,S\r\n880,1,1,\"Potter, Mrs. Thomas Jr (Lily Alexenia Wilson)\",female,56,0,1,11767,83.1583,C50,C\r\n881,1,2,\"Shelley, Mrs. William (Imanita Parrish Hall)\",female,25,0,1,230433,26,,S\r\n882,0,3,\"Markun, Mr. Johann\",male,33,0,0,349257,7.8958,,S\r\n883,0,3,\"Dahlberg, Miss. Gerda Ulrika\",female,22,0,0,7552,10.5167,,S\r\n884,0,2,\"Banfield, Mr. Frederick James\",male,28,0,0,C.A./SOTON 34068,10.5,,S\r\n885,0,3,\"Sutehall, Mr. Henry Jr\",male,25,0,0,SOTON/OQ 392076,7.05,,S\r\n886,0,3,\"Rice, Mrs. William (Margaret Norton)\",female,39,0,5,382652,29.125,,Q\r\n887,0,2,\"Montvila, Rev. Juozas\",male,27,0,0,211536,13,,S\r\n888,1,1,\"Graham, Miss. Margaret Edith\",female,19,0,0,112053,30,B42,S\r\n889,0,3,\"Johnston, Miss. Catherine Helen \"\"Carrie\"\"\",female,,1,2,W./C. 6607,23.45,,S\r\n890,1,1,\"Behr, Mr. Karl Howell\",male,26,0,0,111369,30,C148,C\r\n891,0,3,\"Dooley, Mr. Patrick\",male,32,0,0,370376,7.75,,Q\r\n\n" ], [ "from requests import session\n# payload\npayload = {\n 'action': 'login',\n 'username': os.environ.get(\"KAGGLE_USERNAME\"),\n 'password': os.environ.get(\"KAGGLE_PASSWORD\")\n}\n\n\ndef extract_data(url, file_path):\n '''\n extract data from kaggle\n '''\n # setup session\n with session() as c:\n c.post('https://www.kaggle.com/account/login', data=payload)\n # oppen file to write\n with open(file_path, 'w') as handle:\n response = c.get(url, stream=True)\n for block in response.iter_content(1024):\n handle.write(block)\n", "_____no_output_____" ], [ "# urls\ntrain_url = 'https://www.kaggle.com/c/titanic/download/train.csv'\ntest_url = 'https://www.kaggle.com/c/titanic/download/test.csv'\n\n# file paths\nraw_data_path = os.path.join(os.path.pardir,'data','raw')\ntrain_data_path = os.path.join(raw_data_path, 'train.csv')\ntest_data_path = os.path.join(raw_data_path, 'test.csv')\n\n# extract data\nextract_data(train_url,train_data_path)\nextract_data(test_url,test_data_path)", "_____no_output_____" ], [ "!ls -l ../data/raw", "total 48\r\n-rw-r--r--@ 1 datascienceprojects staff 9168 Apr 5 18:30 test.csv\r\n-rw-r--r--@ 1 datascienceprojects staff 9233 Apr 5 18:30 train.csv\r\n" ] ], [ [ "### Builiding the file script", "_____no_output_____" ] ], [ [ "get_raw_data_script_file = os.path.join(os.path.pardir,'src','data','get_raw_data.py')", "_____no_output_____" ], [ "%%writefile $get_raw_data_script_file\n# -*- coding: utf-8 -*-\nimport os\nfrom dotenv import find_dotenv, load_dotenv\nfrom requests import session\nimport logging\n\n\n# payload for login to kaggle\npayload = {\n 'action': 'login',\n 'username': os.environ.get(\"KAGGLE_USERNAME\"),\n 'password': os.environ.get(\"KAGGLE_PASSWORD\")\n}\n\n\ndef extract_data(url, file_path):\n '''\n method to extract data\n '''\n with session() as c:\n c.post('https://www.kaggle.com/account/login', data=payload)\n with open(file_path, 'w') as handle:\n response = c.get(url, stream=True)\n for block in response.iter_content(1024):\n handle.write(block)\n\n\n \ndef main(project_dir):\n '''\n main method\n '''\n # get logger\n logger = logging.getLogger(__name__)\n logger.info('getting raw data')\n \n # urls\n train_url = 'https://www.kaggle.com/c/titanic/download/train.csv'\n test_url = 'https://www.kaggle.com/c/titanic/download/test.csv'\n\n # file paths\n raw_data_path = os.path.join(project_dir,'data','raw')\n train_data_path = os.path.join(raw_data_path, 'train.csv')\n test_data_path = os.path.join(raw_data_path, 'test.csv')\n\n # extract data\n extract_data(train_url,train_data_path)\n extract_data(test_url,test_data_path)\n logger.info('downloaded raw training and test data')\n\n\nif __name__ == '__main__':\n # getting root directory\n project_dir = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)\n \n # setup logger\n log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n logging.basicConfig(level=logging.INFO, format=log_fmt)\n\n # find .env automatically by walking up directories until it's found\n dotenv_path = find_dotenv()\n # load up the entries as environment variables\n load_dotenv(dotenv_path)\n\n # call the main\n main(project_dir)\n", "Overwriting ../src/data/get_raw_data.py\n" ], [ "!python $get_raw_data_script_file", "2020-04-05 18:32:46,062 - __main__ - INFO - getting raw data\n2020-04-05 18:32:47,092 - __main__ - INFO - downloaded raw training and test data\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4a52031ec713c35eba541baadfc9a6f866b8a2d2
13,224
ipynb
Jupyter Notebook
cpp_recursion.ipynb
kalz2q/myjupyternotebooks
daab7169bd6e515c94207371471044bd5992e009
[ "MIT" ]
null
null
null
cpp_recursion.ipynb
kalz2q/myjupyternotebooks
daab7169bd6e515c94207371471044bd5992e009
[ "MIT" ]
null
null
null
cpp_recursion.ipynb
kalz2q/myjupyternotebooks
daab7169bd6e515c94207371471044bd5992e009
[ "MIT" ]
null
null
null
27.378882
509
0.435269
[ [ [ "<a href=\"https://colab.research.google.com/github/kalz2q/mycolabnotebooks/blob/master/cpp_recursion.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# メモ\n再帰は簡単かと思っていたら云々。\n1. ややこしい問題、atcoder の問題を解くのに再帰を使うにはコツがありそう\n1. すぐに stack overflow になるので再帰ができたらすぐに末尾再帰 tail recursion に書き直す\n\nrecursion pdf\n* thinking recursively by eric s. roberts\n* Introduction to Recursive Programming", "_____no_output_____" ] ], [ [ "# apg4b a programmer's guide for beginers", "_____no_output_____" ], [ "# sum with recursion\n# 0 から 与えられた数宇までの合計を算出する\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nint sum (int n){\n if (n == 1) return 1;\n else return (n + sum(n-1));\n}\n \nint main() {\n int n; cin >> n;\n cout << sum(n) << endl;\n}", "Overwriting temp.cpp\n" ], [ "!g++ temp.cpp; echo 10 |./a.out\n!g++ temp.cpp; echo 1000 |./a.out #=> ちょっと大きい数字でエラーになる", "55\n5050\n" ], [ "# factorial with recursion\n# 与えられた数宇の階乗を計算する\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nunsigned long long factorial (int n){\n if (n == 1) return 1;\n else return (n * factorial(n-1));\n}\n \nint main() {\n int n; cin >> n;\n cout << factorial(n) << endl;\n}", "Overwriting temp.cpp\n" ], [ "!g++ temp.cpp; echo 5 |./a.out\n!g++ temp.cpp; echo 10 |./a.out\n!g++ temp.cpp; echo 50 |./a.out", "120\n3628800\n15188249005818642432\n" ], [ "# 大きな数を扱うネットにあった例\n# 入力に 250 を使っていた\n# 出力は 500桁近い\n# そのままでは動かなかったので書き直してみる\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n long k = 1; cin >> k;\n\n if (k <= 33) {\n unsigned long long fact = 1;\n fact = 1;\n for (int b = k; b >= 1; b--) {\n fact = fact * b;\n }\n cout << \"\\nThe factorial of \" << k << \" is \" << fact << endl;\n }\n else {\n int numArr[10000];\n int total, rem = 0, count;\n register int i; //int i;\n for (i = 0; i < 10000; i++) numArr[i] = 0;\n numArr[10000] = 1;\n for (count = 2; count <= k; count++) {\n while (i > 0) {\n total = numArr[i] * count + rem;\n rem = 0;\n if (total > 9) {\n numArr[i] = total % 10;\n rem = total / 10;\n }\n else {\n numArr[i] = total;\n }\n i--;\n }\n rem = 0;\n total = 0;\n i = 10000;\n }\n cout << \"The factorial of \" << k << \" is \" << endl;\n for (i = 0;i < 10000;i++) {\n if (numArr[i] != 0 || count == 1) {\n cout << numArr[i];\n count = 1;\n }\n }\n cout << endl;\n }\n cout << endl;\n}", "Overwriting temp.cpp\n" ], [ "# 動くようになった\n!g++ temp.cpp; echo 10 |./a.out\n!g++ temp.cpp; echo 50 |./a.out\n!g++ temp.cpp; echo 250 |./a.out", "\nThe factorial of 10 is 3628800\n\nThe factorial of 50 is \n3041409320171337804361260816606476884437764156896051200000000000\n\nThe factorial of 250 is \n323285626090910773232081455202436847099484371767378066674794242711282374755511120948881791537102819945092850735318943292673093171280899082279103027907128192167652724018926473321804118626100683292536513367893908956993571353017504051317876007724793306540233900616482555224881943657258605739922264125483298220484913772177665064127685880715312897877767295191399084437747870258917297325515028324178732065818848206247858265980884882554880000000000000000000000000000000000000000000000000000000000000\n\n" ], [ "# haskell で計算した結果 10 50 250\n# 合っている\n# 3628800\n# 30414093201713378043612608166064768844377641568960512000000000000\n# 3232856260909107732320814552024368470994843717673780666747942427112823747555111209488817915371028199450928507353189432926730931712808990822791030279071281921676527240189264733218041186261006832925365133678939089569935713530175040513178760077247933065402339006164825552248819436572586057399222641254832982204849137721776650641276858807153128978777672951913990844377478702589172973255150283241787320658188482062478582659808848825548800000000000000000000000000000000000000000000000000000000000000\n", "_____no_output_____" ], [ "# フィボナッチ数を計算する\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nunsigned long long fibonacci (int n){\n if (n == 0) return 0;\n else if (n == 1) return 1;\n else return (fibonacci(n-1) + fibonacci(n-2));\n}\n \nint main() {\n int n; cin >> n;\n cout << fibonacci(n) << endl;\n}", "Overwriting temp.cpp\n" ], [ "!g++ temp.cpp; echo 1 |./a.out\n!g++ temp.cpp; echo 2 |./a.out\n!g++ temp.cpp; echo 3 |./a.out\n!g++ temp.cpp; echo 4 |./a.out\n!g++ temp.cpp; echo 5 |./a.out\n!g++ temp.cpp; echo 6 |./a.out", "1\n1\n2\n3\n5\n8\n" ], [ "# Write the binary representation\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nvoid base2(int n){\n if (n==1) cout << n;\n else {\n base2(n/2);\n cout << n%2;\n }\n}\n\nint main() {\n int n; cin >> n;\n base2(n);\n cout << endl; \n}", "Overwriting temp.cpp\n" ], [ "!g++ temp.cpp; echo 1 |./a.out\n!g++ temp.cpp; echo 2 |./a.out\n!g++ temp.cpp; echo 3 |./a.out\n!g++ temp.cpp; echo 4 |./a.out\n!g++ temp.cpp; echo 5 |./a.out\n!g++ temp.cpp; echo 6 |./a.out", "1\n10\n11\n100\n101\n110\n" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ] ], [ [ "# いまここ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
4a520921dbe75ac75bcc9c162b736e4a63a21192
1,966
ipynb
Jupyter Notebook
Research/tmp1.ipynb
shew91/Retropy
9feb34855b997c48d93a5343a9842788d19582e6
[ "MIT" ]
13
2018-06-02T09:11:15.000Z
2020-08-29T01:01:19.000Z
Research/tmp1.ipynb
shew91/Retropy
9feb34855b997c48d93a5343a9842788d19582e6
[ "MIT" ]
1
2021-01-17T14:03:13.000Z
2021-01-17T14:03:13.000Z
Research/tmp1.ipynb
shew91/Retropy
9feb34855b997c48d93a5343a9842788d19582e6
[ "MIT" ]
6
2018-06-02T16:20:47.000Z
2021-12-30T22:26:54.000Z
19.858586
65
0.534588
[ [ [ "%run retropy.ipynb", "_____no_output_____" ], [ "x = shiller_snp500(taxes=True, inf_adj=True, tax_rate=1)\ny = shiller_snp500(taxes=False, inf_adj=False)\nshow_dd(y, x)", "_____no_output_____" ], [ "publish()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
4a520b827cd48388d9cf19593933b72a24d7b979
2,360
ipynb
Jupyter Notebook
3 Machine Learning Life Cycle/28. Outlier Treatment in Python/Outlier Treatment in Python.ipynb
IamVaibhavsar/Machine_Learning_Files
1831166269f81cd738366382fd59bcc1857eb16e
[ "MIT" ]
null
null
null
3 Machine Learning Life Cycle/28. Outlier Treatment in Python/Outlier Treatment in Python.ipynb
IamVaibhavsar/Machine_Learning_Files
1831166269f81cd738366382fd59bcc1857eb16e
[ "MIT" ]
null
null
null
3 Machine Learning Life Cycle/28. Outlier Treatment in Python/Outlier Treatment in Python.ipynb
IamVaibhavsar/Machine_Learning_Files
1831166269f81cd738366382fd59bcc1857eb16e
[ "MIT" ]
null
null
null
16.978417
56
0.499153
[ [ [ "#importing libraries\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline ", "_____no_output_____" ], [ "#reading the dataset into pandas\n\ndf=pd.read_csv(\"data.csv\")", "_____no_output_____" ], [ "#first few rows of the dataset\n\ndf.head()", "_____no_output_____" ] ], [ [ "# Univariate outlier detection", "_____no_output_____" ] ], [ [ "df['Age'].plot.box()", "_____no_output_____" ] ], [ [ "# Bivariate outlier detection", "_____no_output_____" ] ], [ [ "df.plot.scatter('Age', 'Fare')", "_____no_output_____" ] ], [ [ "# Removing outlier from the dateset", "_____no_output_____" ] ], [ [ "df=df[df['Fare']<300]", "_____no_output_____" ] ], [ [ "# Replacing outlier in age with the mean age value", "_____no_output_____" ] ], [ [ "df.loc[df['Age']>65, 'Age']=np.mean(df['Age'])", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a5216e2024ab95e18c8f3a52bf44e9db9a67342
37,602
ipynb
Jupyter Notebook
notebooks/20220512analyze_unaugmented_cnns.ipynb
arokem/afq-deep-learning
61d7746f03914d63c56253d10d0f6a21e6c78e90
[ "BSD-3-Clause" ]
null
null
null
notebooks/20220512analyze_unaugmented_cnns.ipynb
arokem/afq-deep-learning
61d7746f03914d63c56253d10d0f6a21e6c78e90
[ "BSD-3-Clause" ]
null
null
null
notebooks/20220512analyze_unaugmented_cnns.ipynb
arokem/afq-deep-learning
61d7746f03914d63c56253d10d0f6a21e6c78e90
[ "BSD-3-Clause" ]
2
2021-12-01T17:04:39.000Z
2022-01-20T22:53:40.000Z
151.620968
17,040
0.900777
[ [ [ "models= [\"cnn_lenet\", \"mlp4\", \"cnn_vgg\", \"lstm1v0\", \"lstm1\", \"lstm2\", \"blstm1\", \"blstm2\", \"lstm_fcn\", \"cnn_resnet\"]", "_____no_output_____" ], [ "import pandas as pd\n\nresults = [pd.read_pickle(f'results_{model}.pickle') for model in models]", "_____no_output_____" ], [ "import numpy as np", "_____no_output_____" ], [ "lengths = [len(r) for r in results]", "_____no_output_____" ], [ "print(lengths)", "[10, 10, 10, 10, 10, 10, 10, 10, 10, 10]\n" ], [ "model_column = np.concatenate([[model] * 10 for model in models[:]])", "_____no_output_____" ], [ "np.array(results[0]).shape", "_____no_output_____" ], [ "results_data = pd.DataFrame(np.array(results).reshape(-1, 5), columns=[\"MSE\", \"RMSE\", \"MAE\", \"MAD\", \"R2\"])", "_____no_output_____" ], [ "results_data[\"model\"] = model_column", "_____no_output_____" ], [ "melted = pd.melt(results_data, id_vars=[\"model\"])", "_____no_output_____" ], [ "import seaborn as sns", "_____no_output_____" ], [ "ff = sns.catplot(data=melted[(melted[\"variable\"]==\"MAE\") | (melted[\"variable\"]==\"MAD\")], kind=\"bar\", ci=\"sd\", y=\"value\", hue=\"variable\", x=\"model\")\nff.figure.set_size_inches([12, 10])\nff.axes[0][0].hlines(1.45, *ff.axes[0][0].get_xlim(), 'k')", "_____no_output_____" ], [ "ff = sns.catplot(data=melted[melted[\"variable\"]==\"R2\"], kind=\"bar\", ci=\"sd\", y=\"value\", hue=\"variable\", x=\"model\")\nff.figure.set_size_inches([12, 10])\nff.axes[0][0].hlines(0.57, *ff.axes[0][0].get_xlim(), 'k')", "_____no_output_____" ], [ "# BLSTM with FCN? \n# Control experiments with SGL or LASSO PCR: what's the generalization profile of these algorithms?\n# \n# Run generalization experiments with/without augmentation\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a5216f3e720ddfd4d1bc3e4795c042560352645
1,942
ipynb
Jupyter Notebook
notebooks/Analyze Current Buoy Data.ipynb
yipstar/surf_python
60bb52c89de8d00afe9a1e51cc69639344c4c807
[ "Apache-2.0" ]
null
null
null
notebooks/Analyze Current Buoy Data.ipynb
yipstar/surf_python
60bb52c89de8d00afe9a1e51cc69639344c4c807
[ "Apache-2.0" ]
3
2021-05-20T18:59:03.000Z
2022-02-26T08:44:03.000Z
notebooks/Analyze Current Buoy Data.ipynb
yipstar/surf_python
60bb52c89de8d00afe9a1e51cc69639344c4c807
[ "Apache-2.0" ]
null
null
null
24.582278
329
0.538105
[ [ [ "%load_ext autoreload\n%autoreload 2\n%matplotlib inline", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\nimport os", "_____no_output_____" ], [ "import sys\nsys.path.append(\"../\")", "_____no_output_____" ], [ "from huey.data import get_data", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
4a521c6b23e77510d524df73a46f58914cf0829b
11,916
ipynb
Jupyter Notebook
tutorial014.ipynb
psychdatascience/PsychDataScienceOne
9ae6e27622f6898d6827e6d366f71c041e621992
[ "MIT" ]
8
2022-01-13T02:50:17.000Z
2022-03-03T01:35:13.000Z
tutorial014.ipynb
psychdatascience/PsychDataScienceOne
9ae6e27622f6898d6827e6d366f71c041e621992
[ "MIT" ]
1
2022-01-12T21:12:13.000Z
2022-01-12T21:12:13.000Z
tutorial014.ipynb
psychdatascience/PsychDataScienceOne
9ae6e27622f6898d6827e6d366f71c041e621992
[ "MIT" ]
3
2022-02-14T05:40:07.000Z
2022-03-07T18:59:15.000Z
33.192201
513
0.595754
[ [ [ "## Some fundamental elements of programming III\n### Understanding and creating correlated datasets and how to create functions", "_____no_output_____" ], [ "As we said before, the core of data science is computer programming. \n\nTo really explore data, we need to be able to write code to \n\n (1) wrangle or even generate data that has the properties needed for analysis and \n \n (2) do actual data analysis and visualization.\n\nIf data science didn't involve programming – if it only involved clicking buttons in a statistics program like SPSS – it wouldn't be called data *science*. In fact, it wouldn't even be a \"thing\" at all.", "_____no_output_____" ], [ "Learning goals:\n \n - Understand how to generate correlated variables.\n \n - More indexing\n \n - More experiments with loops", "_____no_output_____" ], [ "#### Generate correlated datasets\n\nIn thispart of the tutorial we will learn how generate datasets that are 'related.' While doing that we will practice a few things learned recently in previous tutorials:\n\n - Plotting with matplotlib\n - generating numpy arrays\n - indexing into arrays\n - using `while` loops", "_____no_output_____" ], [ "First thing first, we will import the basic libraries we need.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "After that we will create a few datasets. More specifically, we will create `n` datasets each called `x` (say 5 datasets, where `n=5`). Each dataset will have the length of `m` (where for example, `m` could be 100), this means for example that each dataset will have the shape of (m,1) or in our example (100,1).\n\nAfter that, we will create another group of `n` datasets called `y` of the same shape of `x`. Each one of the `y` datasets will have a corresponding `x` dataset that it will be correlated with.\n\nThis means that for each dataset in `x` there will be a dataset in `y` that is correlated with it.\n\nLet's get started with a hands on method. Forst we will make the example of a single dataset `x` and a correlated dataset `y`.", "_____no_output_____" ] ], [ [ "# We first build the dataset `x`, \n# we will use our standard method\n# based on randn\nm = 1000\nmu = 5\nsd = 1\nx = mu + sd*np.random.randn(m,1)\n\n# let take a look at it\nplt.hist(x, 60)", "_____no_output_____" ] ], [ [ "OK. After generating the first dataset we will generate a second dataset, let's call it `y`. This second dataset will be correlated to the first.\n\nTo generate a dataset correlated to `x` we will indeed use `x` as our base for the data and add on top of `x` a small amount of noise, let's call it `noise`. `noise` represents the small (or larger) difference between `x` and `y`. ", "_____no_output_____" ] ], [ [ "err = np.random.randn(m,1)\ny = x + err\nplt.hist(y,60)", "_____no_output_____" ] ], [ [ "OK. The two histograms seem similar (similar range and height), but it is difficult to judge if `x` and `y` are indeed correlated. To do that we need to make a scatter plot.\n\n`matplotlib` has a convenient function for scatter plots, `plt.scatter()`, we will use that function to take a look at whether the two datasets are correlated.", "_____no_output_____" ] ], [ [ "plt.scatter(x,y)", "_____no_output_____" ] ], [ [ "Great, the symbols should be aligned along the major diagonal. This means that they are indeed correlated. To get to understand more what we did above, let's think about `err`.\n\nImagine, if there were no error, e.g., no `err`. That would mean that there would be no difference between `x` and `y`. Literally, the two datasets would be identical.\n\nWe can do that with the code above by setting `err` to `0`.", "_____no_output_____" ] ], [ [ "err = 0\ny = x + err\nplt.scatter(x,y)", "_____no_output_____" ] ], [ [ "The symbols should all lay on the major diagonal. So, `err` effectively controls the level of correlation between `x` and `y`. So if we set it to something small, in other words if we add only a small amount of error then the two arrays (`x` and `y`) would be very similar. For example, let's try setting it up to 10% of the original `err`.", "_____no_output_____" ] ], [ [ "err = np.random.randn(m,1);\nerr = err*0.1 # 0.1 -> scaling factor\ny = x + err\nplt.scatter(x,y)", "_____no_output_____" ] ], [ [ "OK. It should have worked. The error added is not large, the symbols should lay almost on the diagonal, but not quite.\n\nAs we increase the `err` the symbols should move away from the diagonal.", "_____no_output_____" ] ], [ [ "err = np.random.randn(m,1);\nscaling_factor = 0.9\nerr = err*scaling_factor \ny = x + err\nplt.scatter(x,y)", "_____no_output_____" ] ], [ [ "One way to think about the scaling factor and `err` is that they are related to correlation. Indeed, they are not directly related to correlation (not a one-to-one relationship, but a proxy). \n\nThe scaling factor is inversely related to correlation because as the scaling factor increases the correlation decreases. Furthermore, they are not directly related to correlation because they both depend on a couple of variables, for example, the variance of the distributions (both `err` and `x` will affect the relationship between the correlation and the scaling factor).", "_____no_output_____" ], [ "Python has a method to generate couples of correlated arrays. We will now briefly explore it, but leave a deeper dive on each function to you. You are suggested to further explore the code below and its implications. It might come helpful to us later down the road, you never know!", "_____no_output_____" ], [ "#### A more principled way to make correlated datasets\n\nNumPy has a function called `multivariate_normal` that generates pairs of correlated datasets. The correlation values can be specified conveniently. A little bit of thinking is required, though. The function uses the covariance matrix. The covariance matrix is composed of 4 numbers. Two of the numbers describe the variances of the two datasamples we want to generate. The other two values describe the correlation between the samples and are generally called `covariances` (co-variations or co-relations).", "_____no_output_____" ] ], [ [ "from numpy.random import multivariate_normal # we import the function\nx_mu = 0; # we set up the mean of the first set of data points \ny_mu = 0; # we set up the mean of the second sample\nx_var = 1; # the variance of the first sample\ny_var = 1; # the variance of the second sample\ncov = 0.9; # this is the covariance (can be thought of as correlation)\n\n# the function multivariate_normal will need a matrix to control\n# the relation between the samples, this matrix is called covariance matrix\ncov_m = [[x_var, cov],\n [cov, y_var]]\n\n# we now create the two data sets by setting the the proper\n# means and passing the covariance matrix, we also pass the\n# requested size of the sample\ndata = multivariate_normal([x_mu, y_mu], cov_m, size=1000)\n\n# We can plot the two data sets\nx, y = data[:,0], data[:,1]\nplt.scatter(x, y)", "_____no_output_____" ] ], [ [ "#### Creating many correlated datasets\n\nImagine now if we were asked to create a series of correlated datasets. Not one, nottwo, more than that.\n\nOnce the basic code used to build one is known. The rest of the datasets can be generated reusing the same code and putting the code inside a loop. Below we will show how to create 5 datasets using a `while` loop.", "_____no_output_____" ] ], [ [ "counter = 0;\nn_datasets = 5;\nsiz_datasets = 1000;\n\nx_mu = 1; # mean of the first dataset \ny_mu = 1; # mean of the second dataset\nx_var = 2; # the variance of the first dataset\ny_var = 2; # the variance of the second dataset\ncov = 0.85; # this is the covariance (can be thought of as correlation)\n\n# covariance matrix\ncov_m = [[x_var, cov],\n [cov, y_var]]\n\nwhile counter < n_datasets :\n data = multivariate_normal([x_mu, y_mu], \n cov_m, \n size=siz_datasets)\n x, y = data[:,0], data[:,1]\n counter = counter + 1\n\n # Make a plot, show it, wait some time\n print(\"Plotting dataset: \", counter)\n plt.scatter(x, y);\n plt.show() ;\n plt.pause(0.05)\n\nelse:\n print(\"DONE Plotting datasets!\")", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a521f74f191a54bb12c31af156eae4b60311dd4
483,995
ipynb
Jupyter Notebook
logo/CWInPy_logo.ipynb
duncanmmacleod/cwinpy
fe4c2002f9fd129e6a4eece32b888e1f3e58327e
[ "MIT" ]
null
null
null
logo/CWInPy_logo.ipynb
duncanmmacleod/cwinpy
fe4c2002f9fd129e6a4eece32b888e1f3e58327e
[ "MIT" ]
null
null
null
logo/CWInPy_logo.ipynb
duncanmmacleod/cwinpy
fe4c2002f9fd129e6a4eece32b888e1f3e58327e
[ "MIT" ]
null
null
null
730.007541
157,316
0.947128
[ [ [ "%matplotlib inline\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.patches import Circle, Wedge, Ellipse, Arc\nfrom matplotlib.collections import PatchCollection\n\nimport numpy as np\nimport subprocess as sp", "_____no_output_____" ], [ "fig = plt.figure(figsize=(4, 4), dpi=200)\nax = fig.add_subplot(111, aspect='equal')\n\nsw = 50\new = 10\ncw = 3\nwedge1 = Wedge((0, 0), 1, sw, ew, width=0.7, facecolor=\"darkgreen\", alpha=0.7)\nwedge2 = Wedge((0, 0), 1.08, ew+180-cw, sw+180+cw, width=0.8, facecolor=\"none\", edgecolor=(0,0,0,0.4))\nwedge3 = Wedge((0, 0), 1.08, ew-cw, sw+cw, width=0.8, facecolor=\"none\", edgecolor=(0,0,0,0.4))\n\n#ax.axis(\"equal\")\nax.add_artist(wedge1)\nax.add_artist(wedge2)\nax.add_artist(wedge3)\nax.set_xlim([-2, 2])\nax.set_ylim([-2, 2])\n\nf = 1.8\nphi0 = -0.5\nxstart = 0.4\nxend = xstart + (1 / f) * 2\nxvalues = np.linspace(xstart, xend, 1000)\noffset = -0.7\nscale = 0.3\ndoubleu = offset + scale * np.cos(2.0 * np.pi * f * (xvalues - xvalues[0]) + phi0)\nax.plot(\n xvalues,\n doubleu,\n 'k',\n solid_capstyle='round',\n lw=7,\n)\n\nangle = 39\nell = Ellipse((xvalues[0], doubleu[0]), 0.25, 0.15, angle=angle, facecolor=\"k\")\nax.add_artist(ell)\n\ntonguelen = 0.15\nyv = tonguelen * np.arcsin(np.deg2rad(angle))\ntongueend = (xvalues[0] - tonguelen, doubleu[0] - yv)\nax.plot([tongueend[0], xvalues[0]], [tongueend[1], doubleu[0]], \"k\", linewidth=1)\nax.plot([tongueend[0] - 0.03, tongueend[0]], [tongueend[1], tongueend[1]], \"k\", linewidth=1, solid_capstyle=\"round\")\n\ntonguevec = [-0.03, 0]\n\nvec1 = [xvalues[0] - tongueend[0], doubleu[0] - tongueend[1]]\nvec2 = [-0.03, 0]\nprint(vec1, vec2)\n\nangle = np.arccos(np.dot(vec1, vec2)/(np.linalg.norm(vec1) * np.linalg.norm(vec2)))\nprint(np.rad2deg(angle))\nrotangle = 2 * (np.pi - angle)\n\nR = np.array([[np.cos(rotangle), -np.sin(rotangle)], [np.sin(rotangle), np.cos(rotangle)]])\nrvec = np.dot(R, tonguevec)\nprint(rvec)\nax.plot([tongueend[0] + rvec[0], tongueend[0]], [tongueend[1] + rvec[1], tongueend[1]], \"k\", linewidth=1, solid_capstyle=\"round\")\n\nax.text(xvalues[int(len(xvalues)//2)]+0.15, -0.25, \"InPy\", fontsize=45, fontstretch=\"ultra-condensed\")\nplt.tight_layout()\n\nax.axis(\"off\");", "[0.15000000000000002, 0.08964606185918872] [-0.03, 0]\n149.13575461381234\n[-0.01420951 -0.02642139]\n" ], [ "fig = plt.figure(figsize=(4, 4), dpi=200)\nax = fig.add_subplot(111, aspect='equal')\n\nsw = 50\new = 10\ncw = 3\nwedge1 = Wedge((0, 0), 1, sw, ew, width=0.7, facecolor=\"darkgreen\", alpha=0.7)\nwedge2 = Wedge((0, 0), 1.08, ew+180-cw, sw+180+cw, width=0.8, facecolor=\"none\", edgecolor=(0,0,0,0.4))\nwedge3 = Wedge((0, 0), 1.08, ew-cw, sw+cw, width=0.8, facecolor=\"none\", edgecolor=(0,0,0,0.4))\n\n#ax.axis(\"equal\")\nax.add_artist(wedge1)\nax.add_artist(wedge2)\nax.add_artist(wedge3)\nax.set_xlim([-2, 2])\nax.set_ylim([-2, 2])\n\nf = 1.8\nphi0 = -0.5\nxstart = 0.4\nxend = xstart + (1 / f) * 2\nxvalues = np.linspace(xstart, xend, 1000)\noffset = -0.7\nscale = 0.3\ndoubleu = offset + scale * np.cos(2.0 * np.pi * f * (xvalues - xvalues[0]) + phi0)\nax.plot(\n xvalues,\n doubleu,\n 'k',\n solid_capstyle='round',\n lw=7,\n)\n\nax.text(xvalues[-1]+0.1, offset - 0.1, \"InPy\", fontsize=45, fontstretch=\"ultra-condensed\")\nplt.tight_layout()\n\nax.axis(\"off\");", "_____no_output_____" ], [ "fig = plt.figure(figsize=(4, 4), dpi=300)\nax = fig.add_subplot(111, aspect='equal')\n#fig, ax = plt.subplots(figsize=(7,5), dpi=200)\n\n# Move things over\nXOFFSET = -0.7\n\n# create \"C\"\nsw = 50\new = 10\ncw = 3\nwedge1 = Wedge((XOFFSET, 0), 1, sw, ew, width=0.7, facecolor=\"forestgreen\", edgecolor=(0,0,0,1), lw=0.5)\n\n# create beams\nwedge2 = Wedge((XOFFSET, 0), 1.08, ew+180 + cw, sw+180 - cw, width=0.8, facecolor=(1,1,1,0.6), edgecolor=(0,0,0,0.7), lw=1)\nwedge3 = Wedge((XOFFSET, 0), 1.08, ew + cw, sw - cw, width=0.8, facecolor=\"none\", edgecolor=(0,0,0,0.7), lw=1)\n\n# create \"waves\"\nring1 = Wedge((XOFFSET, 0), 0.57, sw+cw, ew+180, width=0.1, facecolor=\"darkgreen\", alpha=0.25)\nring2 = Wedge((XOFFSET, 0), 0.82, sw+cw, ew+180, width=0.1, facecolor=\"darkgreen\", alpha=0.25)\n\noring1 = Wedge((XOFFSET, 0), 0.57, sw+180, ew+2*180-cw, width=0.1, facecolor=\"darkgreen\", alpha=0.25)\noring2 = Wedge((XOFFSET, 0), 0.82, sw+180, ew+2*180-cw, width=0.1, facecolor=\"darkgreen\", alpha=0.25)\n\n# add \"C\"\nax.add_artist(wedge1)\n\n# add beams\nax.add_artist(wedge2)\nax.add_artist(wedge3)\n\n# add waves\nax.add_artist(ring1)\nax.add_artist(ring2)\n\n# opposite side waves\nax.add_artist(oring1)\nax.add_artist(oring2)\n\n# star\ncirc = Circle((XOFFSET, 0), 0.28, facecolor=(0,0,0,0.1), edgecolor=(0,0,0,1), lw=1)\nax.add_artist(circ)\n\n# spin\narc1 = Arc(\n (XOFFSET, 0),\n width=0.69,\n height=0.07,\n angle=345,\n theta1=176,\n theta2=364.0,\n edgecolor=(0,0,0,1),\n lw=1,\n)\n\nax.add_artist(arc1)\n\n# add \"W\"\nf = 1.8\nphi0 = -0.5\nxstart = 0.4 + XOFFSET\nxend = xstart + (1 / f) * 2\nxvalues = np.linspace(xstart, xend, 1000)\noffset = -0.7\nscale = 0.3\ndoubleu = offset + scale * np.cos(2.0 * np.pi * f * (xvalues - xvalues[0]) + phi0)\nax.plot(\n xvalues,\n doubleu,\n 'k',\n solid_capstyle='round',\n lw=9,\n)\n\n# add snake head\nangle = 44\nell = Ellipse((xvalues[0], doubleu[0]), 0.23, 0.14, angle=angle, facecolor=\"k\")\nax.add_artist(ell)\n\n# add snake tongue\ntonguelen = 0.12\nyv = tonguelen * np.arcsin(np.deg2rad(angle))\ntongueend = (xvalues[0] - tonguelen, doubleu[0] - yv)\nax.plot([tongueend[0], xvalues[0]], [tongueend[1], doubleu[0]], \"k\", linewidth=1)\n\n# add tongue fork\nax.plot(\n [tongueend[0] - 0.03, tongueend[0]],\n [tongueend[1], tongueend[1]],\n \"k\",\n linewidth=1,\n solid_capstyle=\"round\"\n)\ntonguevec = [-0.03, 0]\nvec1 = [xvalues[0] - tongueend[0], doubleu[0] - tongueend[1]]\nvec2 = [-0.03, 0]\n\nangle = np.arccos(np.dot(vec1, vec2)/(np.linalg.norm(vec1) * np.linalg.norm(vec2)))\nrotangle = 2 * (np.pi - angle)\n\nR = np.array([[np.cos(rotangle), -np.sin(rotangle)], [np.sin(rotangle), np.cos(rotangle)]])\nrvec = np.dot(R, tonguevec)\nax.plot(\n [tongueend[0] + rvec[0], tongueend[0]],\n [tongueend[1] + rvec[1], tongueend[1]],\n \"k\",\n linewidth=1,\n solid_capstyle=\"round\"\n)\n\n# add stripe on snake\nax.plot(\n xvalues,\n doubleu,\n 'darkgray',\n solid_capstyle='round',\n lw=2,\n alpha=0.5,\n)\n\n# add \"InPy\" text\nax.text(xvalues[int(len(xvalues)//2)]+0.25, -0.25, \"InPy\", fontsize=55, fontstretch=\"ultra-condensed\")\n\nax.set_xlim([-2, 2])\nax.set_ylim([-2, 2])\nax.axis(\"off\");\n\nplt.tight_layout()\nfig.savefig(\"logo.png\", bbox_inches=\"tight\", pad_inches=0)\nfig.savefig(\"logo_white.png\", bbox_inches=\"tight\", pad_inches=0, facecolor=\"linen\")\nfig.savefig(\"logo.svg\", bbox_inches=\"tight\", pad_inches=0)\n\n# use convert to crop empty space\nsp.run([\"convert\", \"logo.png\", \"-trim\", \"logo.png\"]);\nsp.run([\"convert\", \"logo_white.png\", \"-trim\", \"logo_white.png\"]);", "_____no_output_____" ], [ "fig = plt.figure(figsize=(4, 4), dpi=300)\nax = fig.add_subplot(111, aspect='equal')\n#fig, ax = plt.subplots(figsize=(7,5), dpi=200)\n\n# Move things over\nXOFFSET = -0.7\n\n# create \"C\"\nsw = 50\new = 10\ncw = 3\nwedge1 = Wedge((XOFFSET, 0), 1, sw, ew, width=0.7, facecolor=\"mediumblue\", edgecolor=(1, 1, 1, 0.5), lw=0.5)\n\n# create beams\nwedge2 = Wedge((XOFFSET, 0), 1.08, ew+180-cw, sw+180+cw, width=0.8, facecolor=\"none\", edgecolor=(1,1,1,0.7), lw=1.5)\nwedge3 = Wedge((XOFFSET, 0), 1.08, ew-cw, sw+cw, width=0.8, facecolor=\"none\", edgecolor=(1,1,1,0.7), lw=1.5)\n\n# create \"waves\"\nrcolor = \"black\"\nring1 = Wedge((XOFFSET, 0), 0.47, sw+2*cw, ew+180-2*cw, width=0.01, facecolor=rcolor, alpha=1)\nring2 = Wedge((XOFFSET, 0), 0.67, sw+2*cw, ew+180-2*cw, width=0.01, facecolor=rcolor, alpha=1)\nring3 = Wedge((XOFFSET, 0), 0.87, sw+2*cw, ew+180-2*cw, width=0.01, facecolor=rcolor, alpha=1)\n\noring1 = Wedge((XOFFSET, 0), 0.47, sw+2*cw+180, ew+2*180-2*cw, width=0.01, facecolor=rcolor, alpha=1)\noring2 = Wedge((XOFFSET, 0), 0.67, sw+2*cw+180, ew+2*180-2*cw, width=0.01, facecolor=rcolor, alpha=1)\noring3 = Wedge((XOFFSET, 0), 0.87, sw+2*cw+180, ew+2*180-2*cw, width=0.01, facecolor=rcolor, alpha=1)\n\n# add \"C\"\nax.add_artist(wedge1)\n\n# add beams\nax.add_artist(wedge2)\nax.add_artist(wedge3)\n\n# add waves\nax.add_artist(ring1)\nax.add_artist(ring2)\nax.add_artist(ring3)\n\n# opposite side waves\nax.add_artist(oring1)\nax.add_artist(oring2)\nax.add_artist(oring3)\n\n# spin\narc1 = Arc(\n (XOFFSET, 0),\n width=0.69,\n height=0.07,\n angle=345,\n theta1=175,\n theta2=365.0,\n edgecolor=(1,1,1,0.7),\n lw=1.5,\n)\n\nax.add_artist(arc1)\n\n# add \"W\"\nf = 1.8\nphi0 = -0.5\nxstart = 0.4 + XOFFSET\nxend = xstart + (1 / f) * 2\nxvalues = np.linspace(xstart, xend, 1000)\noffset = -0.7\nscale = 0.3\ndoubleu = offset + scale * np.cos(2.0 * np.pi * f * (xvalues - xvalues[0]) + phi0)\nax.plot(\n xvalues,\n doubleu,\n 'linen',\n solid_capstyle='round',\n lw=7,\n)\n\n# add snake head\nangle = 44\nell = Ellipse((xvalues[0], doubleu[0]), 0.23, 0.14, angle=angle, facecolor=\"linen\")\nax.add_artist(ell)\n\n# add snake tongue\ntonguelen = 0.12\nyv = tonguelen * np.arcsin(np.deg2rad(angle))\ntongueend = (xvalues[0] - tonguelen, doubleu[0] - yv)\nax.plot([tongueend[0], xvalues[0]], [tongueend[1], doubleu[0]], \"linen\", linewidth=1)\n\n# add tongue fork\nax.plot(\n [tongueend[0] - 0.03, tongueend[0]],\n [tongueend[1], tongueend[1]],\n \"linen\",\n linewidth=1,\n solid_capstyle=\"round\"\n)\ntonguevec = [-0.03, 0]\nvec1 = [xvalues[0] - tongueend[0], doubleu[0] - tongueend[1]]\nvec2 = [-0.03, 0]\n\nangle = np.arccos(np.dot(vec1, vec2)/(np.linalg.norm(vec1) * np.linalg.norm(vec2)))\nrotangle = 2 * (np.pi - angle)\n\nR = np.array([[np.cos(rotangle), -np.sin(rotangle)], [np.sin(rotangle), np.cos(rotangle)]])\nrvec = np.dot(R, tonguevec)\nax.plot(\n [tongueend[0] + rvec[0], tongueend[0]],\n [tongueend[1] + rvec[1], tongueend[1]],\n \"linen\",\n linewidth=1,\n solid_capstyle=\"round\"\n)\n\n# add stripe on snake\nax.plot(\n xvalues,\n doubleu,\n 'darkgray',\n solid_capstyle='round',\n lw=1,\n)\n\n# add \"InPy\" text\nax.text(xvalues[int(len(xvalues)//2)]+0.25, -0.25, \"InPy\", fontsize=45, fontstretch=\"ultra-condensed\", color=\"linen\")\n\nax.set_xlim([-2, 2])\nax.set_ylim([-2, 2])\nax.axis(\"off\");\n\nplt.tight_layout()\nfig.savefig(\"logo_inverse.png\", bbox_inches=\"tight\", pad_inches=0)\n#fig.savefig(\"logo_white.png\", bbox_inches=\"tight\", pad_inches=0, facecolor=\"linen\")\n#fig.savefig(\"logo.svg\", bbox_inches=\"tight\", pad_inches=0)\n\n# use convert to crop empty space\nsp.run([\"convert\", \"logo_inverse.png\", \"-trim\", \"logo_inverse.png\"]);\n#sp.run([\"convert\", \"logo_white.png\", \"-trim\", \"logo_white.png\"]);", "_____no_output_____" ], [ "fig = plt.figure(figsize=(4, 4), dpi=300)\nax = fig.add_subplot(111, aspect='equal')\n#fig, ax = plt.subplots(figsize=(7,5), dpi=200)\n\n# Move things over\nXOFFSET = -0.2\n\n# create \"C\"\nsw = 50\new = 10\ncw = 3\nwedge1 = Wedge((XOFFSET, 0), 1, sw, ew, width=0.7, facecolor=\"forestgreen\", edgecolor=(0,0,0,1), lw=0.5)\n\n# create beams\nwedge2 = Wedge((XOFFSET, 0), 1.08, ew+180 + cw, sw+180 - cw, width=0.8, facecolor=(1,1,1,0.6), edgecolor=(0,0,0,0.7), lw=1)\nwedge3 = Wedge((XOFFSET, 0), 1.08, ew + cw, sw - cw, width=0.8, facecolor=\"none\", edgecolor=(0,0,0,0.7), lw=1)\n\n# create \"waves\"\nring1 = Wedge((XOFFSET, 0), 0.57, sw+cw, ew+180, width=0.1, facecolor=\"darkgreen\", alpha=0.25)\nring2 = Wedge((XOFFSET, 0), 0.82, sw+cw, ew+180, width=0.1, facecolor=\"darkgreen\", alpha=0.25)\n\noring1 = Wedge((XOFFSET, 0), 0.57, sw+180, ew+2*180-cw, width=0.1, facecolor=\"darkgreen\", alpha=0.25)\noring2 = Wedge((XOFFSET, 0), 0.82, sw+180, ew+2*180-cw, width=0.1, facecolor=\"darkgreen\", alpha=0.25)\n\n# add \"C\"\nax.add_artist(wedge1)\n\n# add beams\nax.add_artist(wedge2)\nax.add_artist(wedge3)\n\n# add waves\nax.add_artist(ring1)\nax.add_artist(ring2)\n\n# opposite side waves\nax.add_artist(oring1)\nax.add_artist(oring2)\n\n# star\ncirc = Circle((XOFFSET, 0), 0.28, facecolor=(0,0,0,0.1), edgecolor=(0,0,0,1), lw=1)\nax.add_artist(circ)\n\n# spin\narc1 = Arc(\n (XOFFSET, 0),\n width=0.69,\n height=0.07,\n angle=345,\n theta1=176,\n theta2=364.0,\n edgecolor=(0,0,0,1),\n lw=1,\n)\n\nax.add_artist(arc1)\n\n# add \"W\"\nf = 1.8\nphi0 = -0.5\nxstart = 0.4 + XOFFSET\nxend = xstart + (1 / f) * 2\nxvalues = np.linspace(xstart, xend, 1000)\noffset = -0.7\nscale = 0.3\ndoubleu = offset + scale * np.cos(2.0 * np.pi * f * (xvalues - xvalues[0]) + phi0)\nax.plot(\n xvalues,\n doubleu,\n 'k',\n solid_capstyle='round',\n lw=13,\n)\n\n# add snake head\nangle = 44\nell = Ellipse((xvalues[0], doubleu[0]), 0.23, 0.14, angle=angle, facecolor=\"k\")\nax.add_artist(ell)\n\n# add snake tongue\ntonguelen = 0.12\nyv = tonguelen * np.arcsin(np.deg2rad(angle))\ntongueend = (xvalues[0] - tonguelen, doubleu[0] - yv)\nax.plot([tongueend[0], xvalues[0]], [tongueend[1], doubleu[0]], \"k\", linewidth=1)\n\n# add tongue fork\nax.plot(\n [tongueend[0] - 0.03, tongueend[0]],\n [tongueend[1], tongueend[1]],\n \"k\",\n linewidth=1,\n solid_capstyle=\"round\"\n)\ntonguevec = [-0.03, 0]\nvec1 = [xvalues[0] - tongueend[0], doubleu[0] - tongueend[1]]\nvec2 = [-0.03, 0]\n\nangle = np.arccos(np.dot(vec1, vec2)/(np.linalg.norm(vec1) * np.linalg.norm(vec2)))\nrotangle = 2 * (np.pi - angle)\n\nR = np.array([[np.cos(rotangle), -np.sin(rotangle)], [np.sin(rotangle), np.cos(rotangle)]])\nrvec = np.dot(R, tonguevec)\nax.plot(\n [tongueend[0] + rvec[0], tongueend[0]],\n [tongueend[1] + rvec[1], tongueend[1]],\n \"k\",\n linewidth=1,\n solid_capstyle=\"round\"\n)\n\n# add stripe on snake\nax.plot(\n xvalues,\n doubleu,\n 'darkgray',\n solid_capstyle='round',\n lw=2,\n alpha=0.5,\n)\n\nax.set_xlim([-1.35, 1.4])\nax.set_ylim([-1.35, 1.4])\nax.axis(\"off\");\nax.axis(\"off\");\n\nplt.tight_layout()\nfig.savefig(\"logo_cw.png\", bbox_inches=\"tight\", pad_inches=0)\nfig.savefig(\"logo_cw.svg\", bbox_inches=\"tight\", pad_inches=0)\n\n# use convert to crop empty space\nsp.run([\"convert\", \"logo_cw.png\", \"-trim\", \"logo_cw.png\"]);", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
4a52265f31dc5ff519f5d58bf61235a7539296db
39,825
ipynb
Jupyter Notebook
wikitext/01_gather_preprocess_wikitext.ipynb
geohci/wikipedia-language-agnostic-topic-classification
eed1d0021e15739f8a7580afa0f641517e287812
[ "MIT" ]
6
2020-05-19T07:02:14.000Z
2022-03-30T20:46:08.000Z
wikitext/01_gather_preprocess_wikitext.ipynb
geohci/wikipedia-language-agnostic-topic-classification
eed1d0021e15739f8a7580afa0f641517e287812
[ "MIT" ]
1
2021-03-21T13:29:13.000Z
2021-03-24T16:15:20.000Z
wikitext/01_gather_preprocess_wikitext.ipynb
geohci/wikipedia-language-agnostic-topic-classification
eed1d0021e15739f8a7580afa0f641517e287812
[ "MIT" ]
1
2022-03-22T13:15:02.000Z
2022-03-22T13:15:02.000Z
56.091549
149
0.600427
[ [ [ "## Prep notebook", "_____no_output_____" ] ], [ [ "import bz2\nimport json\nimport os\nimport random\nimport re\nimport string\n\nimport mwparserfromhell\nimport numpy as np\nimport pandas as pd\nimport requests\n\nimport findspark\nfindspark.init('/usr/lib/spark2')\n\nfrom pyspark.sql import SparkSession", "_____no_output_____" ], [ "!which python", "/usr/lib/anaconda-wmf/bin/python\n" ], [ "spark = (\n SparkSession.builder\n .appName('Pyspark notebook (isaacj -- wikitext)')\n .master('yarn')\n .config(\n 'spark.driver.extraJavaOptions',\n ' '.join('-D{}={}'.format(k, v) for k, v in {\n 'http.proxyHost': 'webproxy.eqiad.wmnet',\n 'http.proxyPort': '8080',\n 'https.proxyHost': 'webproxy.eqiad.wmnet',\n 'https.proxyPort': '8080',\n }.items()))\n# .config('spark.jars.packages', 'graphframes:graphframes:0.6.0-spark2.3-s_2.11')\n .config(\"spark.driver.memory\", \"2g\")\n .config('spark.dynamicAllocation.maxExecutors', 64)\n .config(\"spark.executor.memory\", \"8g\")\n .config(\"spark.executor.cores\", 4)\n .config(\"spark.sql.shuffle.partitions\", 256)\n .getOrCreate()\n)\nspark", "_____no_output_____" ] ], [ [ "## Parameters / Utilities", "_____no_output_____" ] ], [ [ "snapshot = '2020-12' # data will be current to this date -- e.g., 2020-05 means data is up to 30 April 2020 (at least)\nwd_snapshot = '2020-12-07' # closest Wikidata item-page-link to data snapshot", "_____no_output_____" ], [ "def getCleanedText(wikitext):\n \"\"\"Clean/preprocess wikitext for fastText modeling.\n Should work ok for any space-delimited language. Might need to update punctuation / category names.\n \n What it does:\n * Lowercase\n * Removes wiki markup -- e.g., brackets\n * Removes categories (this is mainly to prevent WikiProject categories from bleeding labels into data)\n * Removes extraneous white-space + punctuation\n What it returns:\n * Cleaned, space-delimited tokens as a string\n \"\"\"\n try:\n wt = mwparserfromhell.parse(wikitext).strip_code().lower()\n return ' '.join([w for w in re.sub('[\"\\'.,?(){}]','', wt).split() if not w.startswith('category:')])\n except Exception:\n return None\n \nspark.udf.register('getCleanedText', getCleanedText, 'String')", "_____no_output_____" ] ], [ [ "## Gather wikitext data and write to TSV", "_____no_output_____" ] ], [ [ "print_for_hive = False\ndo_execute = True\n\nquery = f\"\"\"\nWITH wikidata_ids AS (\n SELECT page_id,\n item_id\n FROM wmf.wikidata_item_page_link wd\n WHERE wd.snapshot = '{wd_snapshot}'\n AND wd.page_namespace = 0\n AND wiki_db = 'enwiki'\n)\nSELECT item_id,\n getCleanedText(revision_text) as cleaned_wikitext\n FROM wmf.mediawiki_wikitext_current wt\n INNER JOIN wikidata_ids wd\n ON (wt.page_id = wd.page_id)\n WHERE snapshot = '{snapshot}'\n AND wiki_db = 'enwiki'\n AND page_namespace = 0\n\"\"\"\n\nif print_for_hive:\n print(re.sub(' +', ' ', re.sub('\\n', ' ', query)).strip())\nelse:\n print(query)\n\nif do_execute:\n result = spark.sql(query)\n result.write.csv(path=\"/user/isaacj/enwiki-cleaned-wikitext\", compression=\"bzip2\", header=True, sep=\"\\t\")", "\nWITH wikidata_ids AS (\n SELECT page_id,\n item_id\n FROM wmf.wikidata_item_page_link wd\n WHERE wd.snapshot = '2020-12-07'\n AND wd.page_namespace = 0\n AND wiki_db = 'enwiki'\n)\nSELECT item_id,\n getCleanedText(revision_text) as cleaned_wikitext\n FROM wmf.mediawiki_wikitext_current wt\n INNER JOIN wikidata_ids wd\n ON (wt.page_id = wd.page_id)\n WHERE snapshot = '2020-12'\n AND wiki_db = 'enwiki'\n AND page_namespace = 0\n\n" ] ], [ [ "## Pull from HDFS to local", "_____no_output_____" ] ], [ [ "file_parts_dir = './text_file_parts/'\n!rm -R {file_parts_dir}\n!mkdir {file_parts_dir}\n!hdfs dfs -copyToLocal enwiki-cleaned-wikitext/part* {file_parts_dir}", "rm: cannot remove './text_file_parts/': No such file or directory\n" ] ], [ [ "## Add labels and train/test split", "_____no_output_____" ] ], [ [ "base_fasttext_fn = './fasttext/wt_2020_12.txt'\ngroundtruth_data = 'labeled_enwiki_with_topics_metadata.json.bz2'\n\ntrain_prop = 0.9\nval_prop = 0.02\ntest_prop = 0.08\nassert train_prop + val_prop + test_prop == 1\ntrain_fn = base_fasttext_fn.replace('.txt', '_train.txt')\ntrain_metadata_fn = base_fasttext_fn.replace('.txt', '_train_metadata.txt')\nval_fn = base_fasttext_fn.replace('.txt', '_val.txt')\nval_metadata_fn = base_fasttext_fn.replace('.txt', '_val_metadata.txt')\ntest_fn = base_fasttext_fn.replace('.txt', '_test.txt')\ntest_metadata_fn = base_fasttext_fn.replace('.txt', '_test_metadata.txt')\nnogroundtruth_fn = base_fasttext_fn.replace('.txt', '_nogt.txt')\nnogroundtruth_metadata_fn = base_fasttext_fn.replace('.txt', '_nogt_metadata.txt')", "_____no_output_____" ], [ "def fasttextify(topic):\n \"\"\"Translate articletopic labels into fastText format (prefixed with __label__ and no spaces).\"\"\"\n return '__label__{0}'.format(topic.replace(' ', '_'))", "_____no_output_____" ], [ "# load in groundtruth\nqid_topics = {}\nwith bz2.open(groundtruth_data, 'rt') as fin:\n for line in fin:\n line = json.loads(line)\n qid = line.get('qid')\n topics = line.get('topics')\n if qid and topics:\n qid_topics[qid] = topics\nprint(\"{0} QIDs with topics.\".format(len(qid_topics)))", "5662388 QIDs with topics.\n" ], [ "train_written = 0\nval_written = 0\ntest_written = 0\nnogt_written = 0\ni = 0\nqids_to_split = {}\ninput_header = ['item_id', 'cleaned_wikitext']\nfns = [fn for fn in os.listdir(file_parts_dir) if fn.endswith('.csv.bz2')]\nwith open(train_fn, 'w') as train_fout:\n with open(train_metadata_fn, 'w') as train_metadata_fout:\n with open(val_fn, 'w') as val_fout:\n with open(val_metadata_fn, 'w') as val_metadata_fout:\n with open(test_fn, 'w') as test_fout:\n with open(test_metadata_fn, 'w') as test_metadata_fout:\n with open(nogroundtruth_fn, 'w') as nogt_fout:\n with open(nogroundtruth_metadata_fn, 'w') as nogt_metadata_fout:\n for fidx, fn in enumerate(fns, start=1):\n with bz2.open(os.path.join(file_parts_dir, fn), 'rt') as fin:\n header = next(fin).strip().split('\\t')\n assert header == input_header\n for i, line_str in enumerate(fin, start=1):\n line = line_str.strip().split('\\t')\n assert len(line) == len(input_header)\n qid = line[0]\n wikitext = line[1]\n if not wikitext or not qid:\n continue\n topics = qid_topics.get(qid)\n if topics:\n if qid in qids_to_split:\n r = qids_to_split[qid]\n else:\n r = random.random()\n qids_to_split[qid] = r\n if r <= train_prop:\n data_fout = train_fout\n metadata_fout = train_metadata_fout\n train_written += 1\n elif r <= train_prop + val_prop:\n data_fout = val_fout\n metadata_fout = val_metadata_fout\n val_written += 1\n else:\n data_fout = test_fout\n metadata_fout = test_metadata_fout\n test_written += 1\n else:\n topics = []\n data_fout = nogt_fout\n metadata_fout = nogt_metadata_fout\n nogt_written += 1\n data_fout.write('{0} {1}\\n'.format(' '.join([fasttextify(t) for t in topics]), wikitext))\n metadata_fout.write('{0}\\n'.format(qid))\n print(\"{0} of {1} processed: {2} train. {3} val. {4} test. {5} no groundtruth.\".format(fidx, len(fns),\n train_written,\n val_written,\n test_written,\n nogt_written))", "1 of 256 processed: 19895 train. 454 val. 1752 test. 2671 no groundtruth.\n2 of 256 processed: 39897 train. 888 val. 3540 test. 5335 no groundtruth.\n3 of 256 processed: 59612 train. 1312 val. 5315 test. 7899 no groundtruth.\n4 of 256 processed: 79527 train. 1742 val. 7028 test. 10576 no groundtruth.\n5 of 256 processed: 99350 train. 2175 val. 8774 test. 13305 no groundtruth.\n6 of 256 processed: 119147 train. 2597 val. 10529 test. 15945 no groundtruth.\n7 of 256 processed: 139220 train. 3022 val. 12307 test. 18566 no groundtruth.\n8 of 256 processed: 159137 train. 3468 val. 14084 test. 21133 no groundtruth.\n9 of 256 processed: 179111 train. 3926 val. 15818 test. 23712 no groundtruth.\n10 of 256 processed: 198857 train. 4347 val. 17615 test. 26346 no groundtruth.\n11 of 256 processed: 218957 train. 4815 val. 19382 test. 28944 no groundtruth.\n12 of 256 processed: 238746 train. 5243 val. 21114 test. 31648 no groundtruth.\n13 of 256 processed: 258463 train. 5703 val. 22903 test. 34254 no groundtruth.\n14 of 256 processed: 278252 train. 6135 val. 24651 test. 36943 no groundtruth.\n15 of 256 processed: 297836 train. 6552 val. 26457 test. 39587 no groundtruth.\n16 of 256 processed: 317805 train. 7010 val. 28209 test. 42229 no groundtruth.\n17 of 256 processed: 337687 train. 7502 val. 29891 test. 44897 no groundtruth.\n18 of 256 processed: 357829 train. 7929 val. 31675 test. 47574 no groundtruth.\n19 of 256 processed: 377709 train. 8341 val. 33444 test. 50174 no groundtruth.\n20 of 256 processed: 397619 train. 8760 val. 35222 test. 52840 no groundtruth.\n21 of 256 processed: 417332 train. 9171 val. 37019 test. 55458 no groundtruth.\n22 of 256 processed: 437192 train. 9619 val. 38823 test. 57994 no groundtruth.\n23 of 256 processed: 456910 train. 10034 val. 40620 test. 60498 no groundtruth.\n24 of 256 processed: 476815 train. 10495 val. 42380 test. 63116 no groundtruth.\n25 of 256 processed: 496821 train. 10953 val. 44178 test. 65686 no groundtruth.\n26 of 256 processed: 516625 train. 11410 val. 45952 test. 68303 no groundtruth.\n27 of 256 processed: 536678 train. 11858 val. 47724 test. 70872 no groundtruth.\n28 of 256 processed: 556530 train. 12290 val. 49411 test. 73562 no groundtruth.\n29 of 256 processed: 576360 train. 12699 val. 51223 test. 76188 no groundtruth.\n30 of 256 processed: 596185 train. 13136 val. 52997 test. 78833 no groundtruth.\n31 of 256 processed: 616121 train. 13570 val. 54674 test. 81512 no groundtruth.\n32 of 256 processed: 635879 train. 14024 val. 56479 test. 84047 no groundtruth.\n33 of 256 processed: 655645 train. 14455 val. 58220 test. 86656 no groundtruth.\n34 of 256 processed: 675214 train. 14867 val. 59965 test. 89226 no groundtruth.\n35 of 256 processed: 694905 train. 15299 val. 61771 test. 91819 no groundtruth.\n36 of 256 processed: 714740 train. 15747 val. 63556 test. 94418 no groundtruth.\n37 of 256 processed: 734617 train. 16174 val. 65295 test. 97038 no groundtruth.\n38 of 256 processed: 754698 train. 16595 val. 67024 test. 99777 no groundtruth.\n39 of 256 processed: 774652 train. 17017 val. 68899 test. 102327 no groundtruth.\n40 of 256 processed: 794653 train. 17480 val. 70676 test. 104995 no groundtruth.\n41 of 256 processed: 814535 train. 17955 val. 72450 test. 107582 no groundtruth.\n42 of 256 processed: 834712 train. 18419 val. 74182 test. 110245 no groundtruth.\n43 of 256 processed: 854484 train. 18869 val. 75998 test. 112852 no groundtruth.\n44 of 256 processed: 874368 train. 19292 val. 77777 test. 115406 no groundtruth.\n45 of 256 processed: 894304 train. 19728 val. 79482 test. 118065 no groundtruth.\n46 of 256 processed: 913946 train. 20143 val. 81284 test. 120688 no groundtruth.\n47 of 256 processed: 934059 train. 20581 val. 83119 test. 123375 no groundtruth.\n48 of 256 processed: 953871 train. 21061 val. 84823 test. 126006 no groundtruth.\n49 of 256 processed: 973946 train. 21490 val. 86601 test. 128665 no groundtruth.\n50 of 256 processed: 993848 train. 21913 val. 88391 test. 131363 no groundtruth.\n51 of 256 processed: 1013954 train. 22362 val. 90120 test. 133954 no groundtruth.\n52 of 256 processed: 1033515 train. 22798 val. 91919 test. 136507 no groundtruth.\n53 of 256 processed: 1053330 train. 23217 val. 93668 test. 139105 no groundtruth.\n54 of 256 processed: 1073192 train. 23643 val. 95496 test. 141685 no groundtruth.\n55 of 256 processed: 1093012 train. 24118 val. 97223 test. 144394 no groundtruth.\n56 of 256 processed: 1112801 train. 24562 val. 99077 test. 146969 no groundtruth.\n57 of 256 processed: 1132713 train. 24992 val. 100846 test. 149595 no groundtruth.\n58 of 256 processed: 1152757 train. 25425 val. 102551 test. 152225 no groundtruth.\n59 of 256 processed: 1172465 train. 25855 val. 104384 test. 154785 no groundtruth.\n60 of 256 processed: 1192453 train. 26296 val. 106187 test. 157397 no groundtruth.\n61 of 256 processed: 1212419 train. 26738 val. 107878 test. 159940 no groundtruth.\n62 of 256 processed: 1232151 train. 27131 val. 109618 test. 162499 no groundtruth.\n63 of 256 processed: 1251967 train. 27574 val. 111386 test. 165163 no groundtruth.\n64 of 256 processed: 1271788 train. 28000 val. 113133 test. 167758 no groundtruth.\n65 of 256 processed: 1291641 train. 28429 val. 114877 test. 170395 no groundtruth.\n66 of 256 processed: 1311318 train. 28854 val. 116542 test. 173013 no groundtruth.\n67 of 256 processed: 1331270 train. 29328 val. 118260 test. 175609 no groundtruth.\n68 of 256 processed: 1350975 train. 29767 val. 120086 test. 178273 no groundtruth.\n69 of 256 processed: 1370886 train. 30240 val. 121885 test. 180911 no groundtruth.\n70 of 256 processed: 1390543 train. 30681 val. 123606 test. 183567 no groundtruth.\n71 of 256 processed: 1410584 train. 31118 val. 125396 test. 186161 no groundtruth.\n72 of 256 processed: 1430369 train. 31574 val. 127090 test. 188828 no groundtruth.\n73 of 256 processed: 1450358 train. 32015 val. 128863 test. 191464 no groundtruth.\n74 of 256 processed: 1470393 train. 32452 val. 130604 test. 194153 no groundtruth.\n75 of 256 processed: 1490245 train. 32935 val. 132329 test. 196743 no groundtruth.\n76 of 256 processed: 1510404 train. 33421 val. 134032 test. 199441 no groundtruth.\n77 of 256 processed: 1530341 train. 33880 val. 135820 test. 202044 no groundtruth.\n78 of 256 processed: 1550157 train. 34279 val. 137620 test. 204680 no groundtruth.\n79 of 256 processed: 1570157 train. 34712 val. 139402 test. 207261 no groundtruth.\n80 of 256 processed: 1590210 train. 35154 val. 141174 test. 209885 no groundtruth.\n81 of 256 processed: 1610049 train. 35611 val. 142851 test. 212519 no groundtruth.\n82 of 256 processed: 1629880 train. 36046 val. 144625 test. 215150 no groundtruth.\n83 of 256 processed: 1649777 train. 36441 val. 146378 test. 217701 no groundtruth.\n84 of 256 processed: 1669689 train. 36863 val. 148112 test. 220371 no groundtruth.\n85 of 256 processed: 1689668 train. 37292 val. 149940 test. 223138 no groundtruth.\n86 of 256 processed: 1709541 train. 37705 val. 151719 test. 225753 no groundtruth.\n87 of 256 processed: 1729586 train. 38118 val. 153444 test. 228422 no groundtruth.\n88 of 256 processed: 1749390 train. 38563 val. 155265 test. 231040 no groundtruth.\n89 of 256 processed: 1769405 train. 38962 val. 157012 test. 233746 no groundtruth.\n90 of 256 processed: 1789227 train. 39409 val. 158797 test. 236497 no groundtruth.\n91 of 256 processed: 1809093 train. 39826 val. 160686 test. 239131 no groundtruth.\n92 of 256 processed: 1828957 train. 40257 val. 162474 test. 241699 no groundtruth.\n93 of 256 processed: 1848844 train. 40709 val. 164259 test. 244394 no groundtruth.\n94 of 256 processed: 1868593 train. 41155 val. 165959 test. 247026 no groundtruth.\n95 of 256 processed: 1888364 train. 41589 val. 167715 test. 249630 no groundtruth.\n96 of 256 processed: 1908210 train. 42071 val. 169516 test. 252348 no groundtruth.\n97 of 256 processed: 1928158 train. 42496 val. 171305 test. 254967 no groundtruth.\n98 of 256 processed: 1947973 train. 42898 val. 173103 test. 257482 no groundtruth.\n99 of 256 processed: 1967544 train. 43360 val. 174811 test. 260103 no groundtruth.\n100 of 256 processed: 1987286 train. 43796 val. 176555 test. 262641 no groundtruth.\n101 of 256 processed: 2007018 train. 44234 val. 178345 test. 265316 no groundtruth.\n102 of 256 processed: 2027141 train. 44670 val. 180073 test. 267945 no groundtruth.\n103 of 256 processed: 2046884 train. 45099 val. 181795 test. 270568 no groundtruth.\n104 of 256 processed: 2066671 train. 45574 val. 183598 test. 273091 no groundtruth.\n105 of 256 processed: 2086468 train. 46011 val. 185332 test. 275800 no groundtruth.\n106 of 256 processed: 2106313 train. 46429 val. 187142 test. 278412 no groundtruth.\n107 of 256 processed: 2126147 train. 46848 val. 188971 test. 281050 no groundtruth.\n108 of 256 processed: 2145970 train. 47284 val. 190777 test. 283690 no groundtruth.\n109 of 256 processed: 2165636 train. 47741 val. 192521 test. 286282 no groundtruth.\n110 of 256 processed: 2185420 train. 48168 val. 194359 test. 288940 no groundtruth.\n111 of 256 processed: 2205154 train. 48597 val. 196117 test. 291548 no groundtruth.\n112 of 256 processed: 2225099 train. 49030 val. 197780 test. 294213 no groundtruth.\n113 of 256 processed: 2245035 train. 49445 val. 199505 test. 296870 no groundtruth.\n114 of 256 processed: 2264939 train. 49864 val. 201228 test. 299450 no groundtruth.\n115 of 256 processed: 2284662 train. 50271 val. 202960 test. 302127 no groundtruth.\n116 of 256 processed: 2304552 train. 50726 val. 204646 test. 304776 no groundtruth.\n117 of 256 processed: 2324341 train. 51144 val. 206333 test. 307402 no groundtruth.\n118 of 256 processed: 2344055 train. 51561 val. 208156 test. 309990 no groundtruth.\n119 of 256 processed: 2363825 train. 52033 val. 209896 test. 312607 no groundtruth.\n120 of 256 processed: 2383840 train. 52454 val. 211605 test. 315299 no groundtruth.\n121 of 256 processed: 2403749 train. 52894 val. 213413 test. 317908 no groundtruth.\n122 of 256 processed: 2423844 train. 53344 val. 215203 test. 320497 no groundtruth.\n123 of 256 processed: 2443553 train. 53780 val. 217006 test. 323055 no groundtruth.\n124 of 256 processed: 2463362 train. 54200 val. 218704 test. 325606 no groundtruth.\n125 of 256 processed: 2483164 train. 54661 val. 220479 test. 328174 no groundtruth.\n126 of 256 processed: 2503029 train. 55104 val. 222183 test. 330723 no groundtruth.\n127 of 256 processed: 2522997 train. 55516 val. 223897 test. 333365 no groundtruth.\n128 of 256 processed: 2542762 train. 55950 val. 225702 test. 336006 no groundtruth.\n129 of 256 processed: 2562628 train. 56390 val. 227389 test. 338618 no groundtruth.\n130 of 256 processed: 2582695 train. 56785 val. 229186 test. 341179 no groundtruth.\n131 of 256 processed: 2602405 train. 57227 val. 230917 test. 343742 no groundtruth.\n132 of 256 processed: 2622217 train. 57682 val. 232663 test. 346371 no groundtruth.\n133 of 256 processed: 2641972 train. 58130 val. 234450 test. 349017 no groundtruth.\n134 of 256 processed: 2661663 train. 58555 val. 236111 test. 351657 no groundtruth.\n135 of 256 processed: 2681474 train. 58952 val. 237880 test. 354221 no groundtruth.\n136 of 256 processed: 2701422 train. 59398 val. 239725 test. 356798 no groundtruth.\n137 of 256 processed: 2721540 train. 59838 val. 241451 test. 359449 no groundtruth.\n138 of 256 processed: 2741493 train. 60278 val. 243228 test. 362135 no groundtruth.\n139 of 256 processed: 2761424 train. 60731 val. 244954 test. 364823 no groundtruth.\n140 of 256 processed: 2781161 train. 61170 val. 246658 test. 367434 no groundtruth.\n141 of 256 processed: 2801186 train. 61606 val. 248371 test. 369999 no groundtruth.\n142 of 256 processed: 2820716 train. 62056 val. 250071 test. 372549 no groundtruth.\n143 of 256 processed: 2840574 train. 62483 val. 251811 test. 375281 no groundtruth.\n144 of 256 processed: 2860288 train. 62917 val. 253582 test. 377931 no groundtruth.\n145 of 256 processed: 2880220 train. 63334 val. 255385 test. 380571 no groundtruth.\n146 of 256 processed: 2900297 train. 63772 val. 257115 test. 383156 no groundtruth.\n147 of 256 processed: 2919908 train. 64203 val. 258845 test. 385847 no groundtruth.\n148 of 256 processed: 2939639 train. 64658 val. 260667 test. 388440 no groundtruth.\n149 of 256 processed: 2959470 train. 65064 val. 262422 test. 391049 no groundtruth.\n150 of 256 processed: 2979357 train. 65513 val. 264195 test. 393710 no groundtruth.\n151 of 256 processed: 2999223 train. 65926 val. 266004 test. 396307 no groundtruth.\n152 of 256 processed: 3019070 train. 66364 val. 267837 test. 398944 no groundtruth.\n153 of 256 processed: 3038695 train. 66790 val. 269574 test. 401541 no groundtruth.\n154 of 256 processed: 3058538 train. 67276 val. 271371 test. 404161 no groundtruth.\n155 of 256 processed: 3078483 train. 67754 val. 273178 test. 406810 no groundtruth.\n156 of 256 processed: 3098245 train. 68212 val. 275030 test. 409507 no groundtruth.\n157 of 256 processed: 3117979 train. 68717 val. 276765 test. 412049 no groundtruth.\n158 of 256 processed: 3137560 train. 69158 val. 278577 test. 414740 no groundtruth.\n159 of 256 processed: 3157334 train. 69645 val. 280395 test. 417346 no groundtruth.\n160 of 256 processed: 3177304 train. 70082 val. 282206 test. 420010 no groundtruth.\n161 of 256 processed: 3197000 train. 70538 val. 283995 test. 422532 no groundtruth.\n162 of 256 processed: 3216783 train. 70961 val. 285780 test. 425104 no groundtruth.\n163 of 256 processed: 3236579 train. 71409 val. 287502 test. 427708 no groundtruth.\n164 of 256 processed: 3256402 train. 71851 val. 289253 test. 430412 no groundtruth.\n165 of 256 processed: 3276230 train. 72294 val. 290946 test. 432981 no groundtruth.\n166 of 256 processed: 3295923 train. 72726 val. 292714 test. 435671 no groundtruth.\n167 of 256 processed: 3315581 train. 73155 val. 294489 test. 438241 no groundtruth.\n168 of 256 processed: 3335355 train. 73649 val. 296267 test. 440868 no groundtruth.\n169 of 256 processed: 3354974 train. 74114 val. 298031 test. 443468 no groundtruth.\n170 of 256 processed: 3374879 train. 74563 val. 299794 test. 446184 no groundtruth.\n171 of 256 processed: 3394797 train. 74979 val. 301631 test. 448769 no groundtruth.\n172 of 256 processed: 3414835 train. 75384 val. 303470 test. 451353 no groundtruth.\n173 of 256 processed: 3434561 train. 75804 val. 305257 test. 453983 no groundtruth.\n174 of 256 processed: 3454163 train. 76239 val. 307020 test. 456637 no groundtruth.\n175 of 256 processed: 3474047 train. 76706 val. 308766 test. 459245 no groundtruth.\n176 of 256 processed: 3494064 train. 77161 val. 310503 test. 461850 no groundtruth.\n177 of 256 processed: 3514283 train. 77623 val. 312251 test. 464543 no groundtruth.\n178 of 256 processed: 3534177 train. 78059 val. 313968 test. 467225 no groundtruth.\n179 of 256 processed: 3554116 train. 78481 val. 315764 test. 469815 no groundtruth.\n180 of 256 processed: 3574076 train. 78873 val. 317493 test. 472382 no groundtruth.\n181 of 256 processed: 3593911 train. 79309 val. 319283 test. 475000 no groundtruth.\n182 of 256 processed: 3613567 train. 79775 val. 321057 test. 477591 no groundtruth.\n183 of 256 processed: 3633628 train. 80225 val. 322752 test. 480165 no groundtruth.\n184 of 256 processed: 3653530 train. 80662 val. 324583 test. 482801 no groundtruth.\n185 of 256 processed: 3673404 train. 81073 val. 326319 test. 485420 no groundtruth.\n186 of 256 processed: 3693278 train. 81496 val. 328100 test. 488013 no groundtruth.\n187 of 256 processed: 3713000 train. 81932 val. 329770 test. 490637 no groundtruth.\n188 of 256 processed: 3732885 train. 82374 val. 331597 test. 493214 no groundtruth.\n189 of 256 processed: 3752671 train. 82840 val. 333371 test. 495785 no groundtruth.\n190 of 256 processed: 3772431 train. 83275 val. 335174 test. 498387 no groundtruth.\n191 of 256 processed: 3792287 train. 83738 val. 336863 test. 501077 no groundtruth.\n192 of 256 processed: 3812047 train. 84175 val. 338632 test. 503646 no groundtruth.\n193 of 256 processed: 3831681 train. 84617 val. 340441 test. 506358 no groundtruth.\n194 of 256 processed: 3851509 train. 85041 val. 342192 test. 508974 no groundtruth.\n195 of 256 processed: 3871474 train. 85487 val. 343862 test. 511516 no groundtruth.\n196 of 256 processed: 3891257 train. 85926 val. 345583 test. 514148 no groundtruth.\n197 of 256 processed: 3911137 train. 86397 val. 347317 test. 516752 no groundtruth.\n198 of 256 processed: 3930784 train. 86875 val. 349085 test. 519348 no groundtruth.\n199 of 256 processed: 3950687 train. 87321 val. 350908 test. 522022 no groundtruth.\n200 of 256 processed: 3970558 train. 87764 val. 352671 test. 524593 no groundtruth.\n201 of 256 processed: 3990430 train. 88240 val. 354421 test. 527218 no groundtruth.\n202 of 256 processed: 4010320 train. 88663 val. 356238 test. 529793 no groundtruth.\n203 of 256 processed: 4030175 train. 89076 val. 357901 test. 532459 no groundtruth.\n204 of 256 processed: 4050215 train. 89561 val. 359628 test. 535081 no groundtruth.\n205 of 256 processed: 4070237 train. 89972 val. 361394 test. 537661 no groundtruth.\n206 of 256 processed: 4089991 train. 90432 val. 363159 test. 540284 no groundtruth.\n207 of 256 processed: 4109907 train. 90853 val. 364867 test. 542848 no groundtruth.\n208 of 256 processed: 4129655 train. 91302 val. 366655 test. 545483 no groundtruth.\n209 of 256 processed: 4149509 train. 91752 val. 368381 test. 548104 no groundtruth.\n210 of 256 processed: 4169417 train. 92215 val. 370062 test. 550795 no groundtruth.\n211 of 256 processed: 4189309 train. 92688 val. 371778 test. 553430 no groundtruth.\n212 of 256 processed: 4209335 train. 93141 val. 373513 test. 556011 no groundtruth.\n213 of 256 processed: 4229365 train. 93585 val. 375215 test. 558699 no groundtruth.\n214 of 256 processed: 4248877 train. 93989 val. 376994 test. 561398 no groundtruth.\n215 of 256 processed: 4268826 train. 94415 val. 378703 test. 564052 no groundtruth.\n216 of 256 processed: 4288545 train. 94886 val. 380450 test. 566705 no groundtruth.\n217 of 256 processed: 4308309 train. 95336 val. 382233 test. 569363 no groundtruth.\n218 of 256 processed: 4328338 train. 95790 val. 383975 test. 571947 no groundtruth.\n219 of 256 processed: 4348127 train. 96199 val. 385773 test. 574635 no groundtruth.\n220 of 256 processed: 4367834 train. 96634 val. 387524 test. 577276 no groundtruth.\n221 of 256 processed: 4387530 train. 97060 val. 389276 test. 579862 no groundtruth.\n222 of 256 processed: 4407392 train. 97525 val. 391016 test. 582420 no groundtruth.\n223 of 256 processed: 4427262 train. 97964 val. 392724 test. 585066 no groundtruth.\n224 of 256 processed: 4447148 train. 98398 val. 394462 test. 587685 no groundtruth.\n225 of 256 processed: 4467134 train. 98881 val. 396267 test. 590300 no groundtruth.\n226 of 256 processed: 4487234 train. 99319 val. 398024 test. 592872 no groundtruth.\n227 of 256 processed: 4507076 train. 99778 val. 399839 test. 595443 no groundtruth.\n228 of 256 processed: 4526937 train. 100244 val. 401621 test. 598065 no groundtruth.\n229 of 256 processed: 4546702 train. 100721 val. 403394 test. 600792 no groundtruth.\n230 of 256 processed: 4566505 train. 101171 val. 405109 test. 603411 no groundtruth.\n231 of 256 processed: 4586522 train. 101620 val. 406844 test. 606036 no groundtruth.\n232 of 256 processed: 4606396 train. 102051 val. 408630 test. 608703 no groundtruth.\n233 of 256 processed: 4626354 train. 102454 val. 410372 test. 611225 no groundtruth.\n234 of 256 processed: 4646186 train. 102885 val. 412137 test. 613924 no groundtruth.\n235 of 256 processed: 4666107 train. 103334 val. 413800 test. 616511 no groundtruth.\n236 of 256 processed: 4686053 train. 103806 val. 415606 test. 619131 no groundtruth.\n237 of 256 processed: 4706268 train. 104221 val. 417318 test. 621797 no groundtruth.\n238 of 256 processed: 4726002 train. 104696 val. 418998 test. 624459 no groundtruth.\n239 of 256 processed: 4745886 train. 105121 val. 420728 test. 627000 no groundtruth.\n240 of 256 processed: 4765825 train. 105548 val. 422477 test. 629629 no groundtruth.\n241 of 256 processed: 4785628 train. 105990 val. 424228 test. 632328 no groundtruth.\n242 of 256 processed: 4805273 train. 106452 val. 425970 test. 634943 no groundtruth.\n243 of 256 processed: 4825015 train. 106879 val. 427750 test. 637609 no groundtruth.\n244 of 256 processed: 4844802 train. 107296 val. 429546 test. 640187 no groundtruth.\n245 of 256 processed: 4864827 train. 107746 val. 431292 test. 642864 no groundtruth.\n246 of 256 processed: 4884609 train. 108190 val. 433044 test. 645515 no groundtruth.\n247 of 256 processed: 4904414 train. 108622 val. 434865 test. 648116 no groundtruth.\n248 of 256 processed: 4924195 train. 109073 val. 436600 test. 650738 no groundtruth.\n249 of 256 processed: 4944046 train. 109543 val. 438417 test. 653417 no groundtruth.\n250 of 256 processed: 4963862 train. 109982 val. 440182 test. 656033 no groundtruth.\n251 of 256 processed: 4984057 train. 110432 val. 441929 test. 658630 no groundtruth.\n252 of 256 processed: 5003835 train. 110854 val. 443661 test. 661266 no groundtruth.\n253 of 256 processed: 5023549 train. 111304 val. 445476 test. 663916 no groundtruth.\n254 of 256 processed: 5043384 train. 111741 val. 447268 test. 666523 no groundtruth.\n255 of 256 processed: 5063268 train. 112167 val. 449048 test. 669131 no groundtruth.\n256 of 256 processed: 5083147 train. 112623 val. 450757 test. 671762 no groundtruth.\n" ], [ "!ls -lht /home/isaacj/fasttext/", "total 20G\n-rw-r--r-- 1 isaacj wikidev 45M Jan 28 03:08 wt_2020_12_train_metadata.txt\n-rw-r--r-- 1 isaacj wikidev 17G Jan 28 03:08 wt_2020_12_train.txt\n-rw-r--r-- 1 isaacj wikidev 385M Jan 28 03:08 wt_2020_12_val.txt\n-rw-r--r-- 1 isaacj wikidev 1012K Jan 28 03:08 wt_2020_12_val_metadata.txt\n-rw-r--r-- 1 isaacj wikidev 6.0M Jan 28 03:08 wt_2020_12_nogt_metadata.txt\n-rw-r--r-- 1 isaacj wikidev 978M Jan 28 03:08 wt_2020_12_nogt.txt\n-rw-r--r-- 1 isaacj wikidev 4.0M Jan 28 03:08 wt_2020_12_test_metadata.txt\n-rw-r--r-- 1 isaacj wikidev 1.5G Jan 28 03:08 wt_2020_12_test.txt\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4a522b17f454c7d77a5adf7c20d8f1cd0669660b
12,389
ipynb
Jupyter Notebook
QKD - Ekert 91(Official).ipynb
Chasmiccoder/2022_qutech_challenge
bef4169a3e51772417265d2d7624a1c34dd82b35
[ "MIT" ]
4
2022-01-30T16:32:15.000Z
2022-01-31T08:10:44.000Z
QKD - Ekert 91(Official).ipynb
DRA-chaos/2022_qutech_challenge
bef4169a3e51772417265d2d7624a1c34dd82b35
[ "MIT" ]
null
null
null
QKD - Ekert 91(Official).ipynb
DRA-chaos/2022_qutech_challenge
bef4169a3e51772417265d2d7624a1c34dd82b35
[ "MIT" ]
1
2022-01-30T16:35:06.000Z
2022-01-30T16:35:06.000Z
29.78125
230
0.548309
[ [ [ "### Demonstration of Quantum Key Distribution with the Ekert 91 Protocol\n\nAlgorithm -\n1. First generate the a maximally entangled qubit pair |psi+> = 1/root(2) * (|01> + |10>)\n2. Send one qubit to Alice and one qubit to Bob\n3. Both Alice and Bob perform their measurement and make the measurement bases public.\n4. According to the new information obtained, a sifted key is created, which can be used for secure communication\n\nModification to this Algorithm (because we get only 1 quantum computer) -\n1. First generate the a maximally entangled qubit pair |psi+> = 1/root(2) * (|01> + |10>)\n2. Take the measurement bases from Alice and Bob\n3. Perform measurement, and send the measurement results to Alice and Bob respectively\n4. Note that Alice and Bob do not have each other's measurement outcomes, they have only theirs\n5. The measurement bases are made public, and the sifted key is obtained", "_____no_output_____" ] ], [ [ "import os\nfrom qiskit import execute\nfrom qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit\n\nfrom quantuminspire.credentials import get_authentication, save_account\nfrom quantuminspire.qiskit import QI\nfrom apikey import token\n\nQI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/')\n\nimport re\nimport numpy as np\nimport random\nprint(\"Process Complete!\")", "Process Complete!\n" ] ], [ [ "<a id=\"layout\"></a>\n# 1. Quantum Key Distribution Activity layout\n\nIn project, we are going to implement the E91 protocol. Steps of the protocol:\n\n1. The serves creates a singlet state where one pair corresponds to Alice and other to Bob.\n2. Alice randomly selects a sequence of measurement basis from Z,X,V and sends it to server\n3. Bob randomly selects a sequence of measurement basis from W,V,X and sends it to server\n4. `Intermediate interface function 1`: a MUX that creates a circuit based on Alice and Bob's selection of bases\n5. `Intermediate interface function 2`: execute the measurement on Quantum Inspire \n6. `Intermediate interface function 3`: check the basis and create the key and send it to Alice and Bob \n\nThese 6 steps allow a key to be distributed between Alice and Bob securely, now the two can send secure and encrypted messages through an insecure channel. \n\nIn this lab, we will not worry about an eavesdropper, but focus on the code for the basic protocol. Therefore, Alice and Bob don't need to run an analysis step. We can further extend it this to try implementing code for Eve.", "_____no_output_____" ] ], [ [ "# Parameters\nN_en_pairs = 10\nalice_seq = [random.randint(1, 3) for i in range(N_en_pairs)]\nbob_seq = [random.randint(1, 3) for i in range(N_en_pairs)]\nprint(\"Process Complete!\")", "Process Complete!\n" ] ], [ [ "<a id=\"layout\"></a>\n## 1. Create entangled states and encode measurement sequence", "_____no_output_____" ] ], [ [ "Quantum_Circuit = [] # list for storing the quantum circuit for each bit\n\nfor i in range(N_en_pairs):\n Alice_Reg = QuantumRegister(1, name=\"alice\")\n Bob_Reg = QuantumRegister(1, name=\"bob\")\n cr = ClassicalRegister(2, name=\"cr\")\n qc = QuantumCircuit(Alice_Reg, Bob_Reg, cr)\n \n # Create an entangled pair for Alice and Bob in each loop\n qc.x(Alice_Reg)\n qc.x(Bob_Reg)\n qc.h(Alice_Reg)\n qc.cx(Alice_Reg, Bob_Reg)\n \n # Cicuit Measurement for different bases\n \n if alice_seq[i]== 1: #If Alice's random sequence is 1, Alice measures in the Z basis\n qc.measure(Alice_Reg,cr[0]) \n elif alice_seq[i] == 2: #If Alice's random sequence is 2, Alice measures in the X basis\n qc.h(Alice_Reg)\n qc.measure(Alice_Reg,cr[0])\n elif alice_seq==3: #If Alice's random sequence is 3, Alice measures in the V basis (-1/sqrt(2), 0, 1/sqrt(2))\n qc.s(Alice_Reg)\n qc.h(Alice_Reg)\n qc.tdg(Alice_Reg)\n qc.h(Alice_Reg)\n qc.measure(Alice_Reg, cr[0])\n \n if bob_seq[i]==1: #If Bob's random sequence is 1, Bob measures in the -W basis\n qc.s(Bob_Reg)\n qc.h(Bob_Reg)\n qc.t(Bob_Reg)\n qc.h(Bob_Reg)\n qc.measure(Bob_Reg, cr[1])\n elif bob_seq[i] == 2: #If Bob's random sequence is 2, Bob measures in the V basis\n qc.s(Bob_Reg)\n qc.h(Bob_Reg)\n qc.tdg(Bob_Reg)\n qc.h(Bob_Reg)\n qc.measure(Bob_Reg, cr[1])\n elif bob_seq[i] == 3: #If Bob's random sequence is 3, Bob measures in the X basis\n qc.h(Bob_Reg)\n qc.measure(Bob_Reg, cr[1])\n\n Quantum_Circuit.append(qc)\n\nprint(\"Process Complete!\")", "Process Complete!\n" ], [ "Quantum_Circuit[0].draw(output='mpl')\nprint(\"Process Complete!\")", "Process Complete!\n" ] ], [ [ "## To QI", "_____no_output_____" ] ], [ [ "save_account(token)\nproject_name = 'E91_test_hardware'\nauthentication = get_authentication()\nQI.set_authentication()\n\n# Create an interface between Qiskit and Quantum Inpsire to execute the circuit\n# qi_backend = QI.get_backend('Starmon-5')\nqi_backend = QI.get_backend('QX single-node simulator')\n\njob = execute(Quantum_Circuit, qi_backend, shots = 1)\nprint(\"Process Complete!\")", "Process Complete!\n" ], [ "results = job.result()\ncounts = results.get_counts()\nprint(\"Process Complete!\")", "Process Complete!\n" ], [ "abPatterns = [\n re.compile('00'), # search for the '..00' output (Alice obtained -1 and Bob obtained -1)\n re.compile('01'), # search for the '..01' output\n re.compile('10'), # search for the '..10' output (Alice obtained -1 and Bob obtained 1)\n re.compile('11') # search for the '..11' output\n]\nprint(\"Process Complete!\")", "Process Complete!\n" ] ], [ [ "### Alices and Bobs measurement result", "_____no_output_____" ] ], [ [ "aliceResults = [] # Alice's results (string a)\nbobResults = [] # Bob's results (string a')\n\nfor i in range(N_en_pairs):\n\n res = list(counts[i].keys())[0] # extract the key from the dict and transform it to str; execution result of the i-th circuit\n \n if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1)\n aliceResults.append(-1) # Alice got the result -1 \n bobResults.append(-1) # Bob got the result -1\n if abPatterns[1].search(res):\n aliceResults.append(1)\n bobResults.append(-1)\n if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1)\n aliceResults.append(-1) # Alice got the result -1 \n bobResults.append(1) # Bob got the result 1\n if abPatterns[3].search(res): \n aliceResults.append(1)\n bobResults.append(1)\n\nprint(\"Process Complete!\")", "Process Complete!\n" ] ], [ [ "### Key Generation", "_____no_output_____" ] ], [ [ "aliceKey = [] # Alice's key string k\nbobKey = [] # Bob's key string k'\n\n# comparing the strings with measurement choices\nfor i in range(N_en_pairs):\n # if Alice and Bob have measured the spin projections onto the a_2/b_3 or a_3/b_2 directions\n if (alice_seq[i] == 2 and bob_seq[i] == 3) or (alice_seq[i] == 3 and bob_seq[i] == 2):\n aliceKey.append(aliceResults[i-1]) # record the i-th result obtained by Alice as the bit of the secret key k\n bobKey.append(- bobResults[i-1]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k'\n \nkeyLength = len(aliceKey) # length of the secret key\n\nprint(aliceKey)\nprint(\"Process Complete!\")", "[-1, -1]\nProcess Complete!\n" ], [ "abKeyMismatches = 0 # number of mismatching bits in Alice's and Bob's keys\n\nfor j in range(keyLength):\n if aliceKey[j] != bobKey[j]:\n abKeyMismatches += 1\n\nprint(abKeyMismatches)\nprint(\"Process Complete!\")", "0\nProcess Complete!\n" ] ], [ [ "Thus, Quantum Key Distribution has been demonstrated!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4a522ca16ef6883ea47a74e5f37e6249a1feaef8
125,515
ipynb
Jupyter Notebook
A_Python/FilesAndVisualization.ipynb
uqzzhao/Programming-Geophysics-in-Python
e6e8299116b4698892921b78927b71fc47ee018a
[ "Apache-2.0" ]
20
2019-11-06T09:08:54.000Z
2021-12-03T08:37:47.000Z
A_Python/FilesAndVisualization.ipynb
uqzzhao/Programming-Geophysics-in-Python
e6e8299116b4698892921b78927b71fc47ee018a
[ "Apache-2.0" ]
null
null
null
A_Python/FilesAndVisualization.ipynb
uqzzhao/Programming-Geophysics-in-Python
e6e8299116b4698892921b78927b71fc47ee018a
[ "Apache-2.0" ]
3
2020-11-23T14:16:06.000Z
2022-03-31T14:45:46.000Z
82.521368
22,736
0.846624
[ [ [ "# Modules\n\nPython has a way to put definitions in a file so they can easily be reused. \nSuch files are called a modules. You can define your own module (for instance see [here](https://docs.python.org/3/tutorial/modules.html)) how to do this but in this course we will only discuss how to use\nexisting modules as they come with python as the [python standard library](https://docs.python.org/3.9/tutorial/stdlib.html?highlight=library) or as third party libraries as they for instance are distributed \nthrough [anaconda](https://www.anaconda.com/) or your Linux distribution or you can install trough `pip` or from source. \n\nDefinitions from a module can be imported into your jupyter notebook, your python script, and into other modules.\nThe module is imported using the import statement. Here we import the mathematics library from the python standard library:", "_____no_output_____" ] ], [ [ "import math", "_____no_output_____" ] ], [ [ "You can find a list of the available functions, variables and classes using the `dir` method:", "_____no_output_____" ] ], [ [ "dir(math)", "_____no_output_____" ] ], [ [ "A particular function (or class or constant) can be called in the form `<module name>.<function name>`:", "_____no_output_____" ] ], [ [ "math.exp(1)", "_____no_output_____" ] ], [ [ "Documentation of a function (or class or constant) can be obtained using the `help` function (if the developer has written it): ", "_____no_output_____" ] ], [ [ "help(math.exp)", "Help on built-in function exp in module math:\n\nexp(...)\n exp(x)\n \n Return e raised to the power of x.\n\n" ] ], [ [ "You can also import a specific function (or a set of functions) so you can directly use them without a prefix: ", "_____no_output_____" ] ], [ [ "from cmath import exp\nexp(1j)", "_____no_output_____" ] ], [ [ "In python terminology that means that - in this case - the `exp` function is imported into the main *name space*.\nThis needs to be applied with care as existing functions (or class definition) with identical names are overwritten.\nFor instance the `math` and the `cmath` module have a function `exp`. Importing both will create a problem \nin the main name space. ", "_____no_output_____" ], [ "If you are conficdent in what you are doing you can import all functions and class definitions into the main name space:", "_____no_output_____" ] ], [ [ "from cmath import *\ncos(1.)", "_____no_output_____" ] ], [ [ "Modules can contain submodules. The functions are then \naccessed `<module name>.<sub-module name>.<function name>`:", "_____no_output_____" ] ], [ [ "import os\nos.path.exists('FileHandling.ipynb')", "_____no_output_____" ] ], [ [ "In these cases it can be useful to use an alias to make the code easier to read:", "_____no_output_____" ] ], [ [ "import os.path as pth\npth.exists('FileHandling.ipynb')", "_____no_output_____" ] ], [ [ "# More on printing\n\nPython provides a powerful way of formatting output using formatted string.\nBasicly the ideas is that in a formatted string marked by a leading 'f' variable\nnames are replaced by the corresponding variable values. Here comes an example:", "_____no_output_____" ] ], [ [ "x, y = 2.124, 3", "_____no_output_____" ], [ "f\"the value of x is {x} and of y is {y}.\"", "_____no_output_____" ] ], [ [ "python makes guesses on how to format the value of the variable but you can also be specific if values should be shown in a specific way. here we want to show `x` as a floating point numbers with a scientific number representation indicated by `e` and `y` to be shown as an integer indicated by `d`: ", "_____no_output_____" ] ], [ [ "f\"x={x} x={x:10f} x={x:e} y={y:d}\"", "_____no_output_____" ] ], [ [ "More details on [Formatted string literals](https://docs.python.org/3.7/reference/lexical_analysis.html#index-24)", "_____no_output_____" ], [ "Formatted strings are used to prettify output when printing:", "_____no_output_____" ] ], [ [ "print(f\"x={x:10f}\")\nprint(f\"y={y:10d}\")\n", "x= 2.124000\ny= 3\n" ] ], [ [ "An alternative way of formatting is the `format` method of a string. You can use the \npositional arguments:", "_____no_output_____" ] ], [ [ "guest='John'\n'Hi {0}, welcome to {1}!\"'.format(guest, 'Brisbane')", "_____no_output_____" ] ], [ [ "Or keyword arguments:", "_____no_output_____" ] ], [ [ "'Hi {guest}, welcome to {place}!'.format(guest='Mike', place='Brisbane')", "_____no_output_____" ] ], [ [ "and a combination of positional arguments and keyword arguments:", "_____no_output_____" ] ], [ [ "'Hi {guest}, welcome to {1}! Enjoy your stay for {0} days.'.format(10, 'Brisbane', guest=\"Bob\")\n ", "_____no_output_____" ] ], [ [ "You can also introduce some formatting on how values are represented:", "_____no_output_____" ] ], [ [ "'Hi {guest}, welcome to {0}! Enjoy your stay for {1:+10d} days.'.format('Brisbane', 10, guest=\"Bob\")", "_____no_output_____" ] ], [ [ "More details in particular for formating numbers are found [here](https://docs.python.org/3.9/library/string.html).", "_____no_output_____" ], [ "# Writing and Reading files\n\nTo open a file for reading or writing use the `open` function. `open()`\nreturns a file object, and is most commonly used with two arguments: open(filename, mode).", "_____no_output_____" ] ], [ [ "outfile=open(\"myRicker.csv\", 'wt')", "_____no_output_____" ] ], [ [ "It is commonly used with two arguments: `open(filename, mode)` where the `mode` takes the values:\n- `w` open for writing. An existing file with the same name will be erased.\n- `a` opens the file for appending; any data written to the file is automatically added to the end. \n- `r` opens the file for both reading only.\nBy default text mode `t` is used that means, you read and write strings from and to the file, which are encoded in a specific encoding. `b` appended to the mode opens the file in binary mode: now the data is read and written in the form of bytes objects. ", "_____no_output_____" ], [ "We want to write some code that writes the `Ricker` wavelet of a period of\n`length` and given frequency `f` to the files `myRicker.csv` in the comma-separated-value (CSV) format. The time is incremented by `dt`. ", "_____no_output_____" ] ], [ [ "length=0.128\nf=25\ndt=0.001", "_____no_output_____" ], [ "def ricker(t, f):\n \"\"\"\n return the value of the Ricker wavelet at time t for peak frequency f\n \"\"\"\n r = (1.0 - 2.0*(math.pi**2)*(f**2)*(t**2)) * math.exp(-(math.pi**2)*(f**2)*(t**2))\n return r", "_____no_output_____" ], [ "t=-length/2\nn=0\nwhile t < length/2:\n outfile.write(\"{0}, {1}\\n\".format(t, ricker(t, f)))\n t+=dt\n n+=1\n\nprint(\"{} records writen to {}.\".format(n, outfile.name))", "128 records writen to myRicker.csv.\n" ] ], [ [ "You can download/open the file ['myRicker.csv'](myRicker.csv).\n** Notice ** There is an extra new line character `\\n` at the of string in the `write` statement. This makes sure that separate rows can be identified in the file.", "_____no_output_____" ], [ "Don't forget to close the file at the end:", "_____no_output_____" ] ], [ [ "outfile.close()", "_____no_output_____" ] ], [ [ "Now we want to read this back. First we need to open the file for reading:", "_____no_output_____" ] ], [ [ "infile=open(\"myRicker.csv\", 'r')", "_____no_output_____" ] ], [ [ "We then can read the entire file as a string:", "_____no_output_____" ] ], [ [ "content=infile.read()\ncontent[0:100]", "_____no_output_____" ] ], [ [ "In some cases it is more easier to read the file row-by-row. First we need to move back to the beginning of the file:", "_____no_output_____" ] ], [ [ "infile.seek(0)", "_____no_output_____" ] ], [ [ "Now we read the file line by line. Each line is split into the time and wavelet value which are \ncollected as floats in two lists `times` and `ricker`:", "_____no_output_____" ] ], [ [ "infile.seek(0)\nline=infile.readline()\ntimes=[]\nricker=[]\nn=0\nwhile len(line)>0:\n a, b=line.split(',')\n times.append(float(a))\n ricker.append(float(b))\n line=infile.readline()\n n+=1\nprint(\"{} records read from {}.\".format(n, infile.name))", "128 records read from myRicker.csv.\n" ] ], [ [ "Notice that the end of file is reached when the read line is empty (len(line)=0). Then the loop is exited.", "_____no_output_____" ] ], [ [ "time[:10]", "_____no_output_____" ] ], [ [ "# JSON Files\n\n\nJSON files (JavaScript Object Notation) is an open-standard file format that uses human-readable text to transmit data objects consisting of dictionaries and lists. It is a very common data format, with a diverse range of applications in particular when exchanging data between web browsers and web services.\n\nA typical structure that is saved in JSON files are combinations of lists and dictionaries \nwith string, integer and float entries. For instance", "_____no_output_____" ] ], [ [ "course = [ { \"name\": \"John\", \"age\": 30, \"id\" : 232483948} ,\n { \"name\": \"Tim\", \"age\": 45, \"id\" : 3246284632} ] ", "_____no_output_____" ], [ "course", "_____no_output_____" ] ], [ [ "The `json` module provides the necessary functionality to write `course` into file, here `course.json`:", "_____no_output_____" ] ], [ [ "import json\njson.dump(course, open(\"course.json\", 'w'), indent=4)", "_____no_output_____" ] ], [ [ "You can access the [course.json](course.json). Depending on your web browser the file is identified as JSON file\nand presented accordingly. \n\nWe can easily read the file back using the `load` method:", "_____no_output_____" ] ], [ [ "newcourse=json.load(open(\"course.json\", 'r'))", "_____no_output_____" ] ], [ [ "This recovers the original list+dictionary structure:", "_____no_output_____" ] ], [ [ "newcourse", "_____no_output_____" ] ], [ [ "We can recover the names of the persons in the course:", "_____no_output_____" ] ], [ [ "[ p['name'] for p in newcourse ]", "_____no_output_____" ] ], [ [ "We can add new person to `newcourse`:", "_____no_output_____" ] ], [ [ "newcourse.append({'age': 29, 'name': 'Jane', 'studentid': 2643746328})\nnewcourse", "_____no_output_____" ] ], [ [ "# Visualization\n\nWe would like to plot the Ricker wavelet. \nThe `matplotlib` library provides a convenient, flexible and powerful tool for visualization at least for 2D data sets. Here we can give only a very brief introduction with more functionality being presented as the course evolves. \nFor a comprehensive documentation and list of examples we refer to the [matplotlib web page](https://matplotlib.org).\n\nHere we use the `matplotlib.pyplot` library which is a collection of command style functions but there \nis also a more general API which gives a reacher functionality:", "_____no_output_____" ] ], [ [ "#%matplotlib notebook\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "It is very easy to plot data point we have read:", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(8,5))\nplt.scatter(times, ricker)", "_____no_output_____" ] ], [ [ "We can also plot this as a function rather than just data point:", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(8,5))\nplt.plot(times, ricker)", "_____no_output_____" ] ], [ [ "Let's use proper labeling of the horizontal axis:", "_____no_output_____" ] ], [ [ "plt.xlabel('time [sec]')", "_____no_output_____" ] ], [ [ "and for the vertical axis:", "_____no_output_____" ] ], [ [ "plt.ylabel('aplitude')", "_____no_output_____" ] ], [ [ "And maybe a title:", "_____no_output_____" ] ], [ [ "plt.title('Ricker wavelet for frequency f = 25 hz')", "_____no_output_____" ] ], [ [ "We can also change the line style, eg. red doted line:", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(8,5))\nplt.plot(times, ricker, 'r:')\nplt.xlabel('time [sec]')\nplt.ylabel('aplitude')", "_____no_output_____" ] ], [ [ "We can put different data sets or representations into the plot: ", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(8,5))\nplt.plot(times, ricker, 'r:', label=\"function\")\nplt.scatter(times, ricker, c='b', s=10, label=\"data\")\nplt.xlabel('time [sec]')\nplt.ylabel('aplitude')\nplt.legend()", "_____no_output_____" ] ], [ [ "You can also add grid line to make the plot easier to read: ", "_____no_output_____" ] ], [ [ "plt.grid(True)", "_____no_output_____" ] ], [ [ "Save the plot to a file:", "_____no_output_____" ] ], [ [ "plt.savefig(\"ricker.png\")", "_____no_output_____" ] ], [ [ "see [ricker.png](ricker.png) for the file.", "_____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" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a522e6dcb521bbb3bab8e5a250ef08ce450ee42
80,589
ipynb
Jupyter Notebook
2. Natural Language Processing with Probabilistic Models/Week1/C2_W1_Assignment.ipynb
nirav8403/coursera-natural-language-processing-specialization-II
cceee0d4447d1b391942663c09af718a58cad12f
[ "Apache-2.0" ]
2
2021-08-10T05:52:41.000Z
2022-01-22T14:14:34.000Z
2. Natural Language Processing with Probabilistic Models/Week1/C2_W1_Assignment.ipynb
nirav8403/coursera-natural-language-processing-specialization-II
cceee0d4447d1b391942663c09af718a58cad12f
[ "Apache-2.0" ]
null
null
null
2. Natural Language Processing with Probabilistic Models/Week1/C2_W1_Assignment.ipynb
nirav8403/coursera-natural-language-processing-specialization-II
cceee0d4447d1b391942663c09af718a58cad12f
[ "Apache-2.0" ]
11
2020-10-29T15:25:37.000Z
2022-01-19T13:36:52.000Z
36.731541
859
0.534552
[ [ [ "# Assignment 1: Auto Correct\n\nWelcome to the first assignment of Course 2. This assignment will give you a chance to brush up on your python and probability skills. In doing so, you will implement an auto-correct system that is very effective and useful.", "_____no_output_____" ], [ "## Outline\n- [0. Overview](#0)\n - [0.1 Edit Distance](#0-1)\n- [1. Data Preprocessing](#1)\n - [1.1 Exercise 1](#ex-1)\n - [1.2 Exercise 2](#ex-2)\n - [1.3 Exercise 3](#ex-3)\n- [2. String Manipulation](#2)\n - [2.1 Exercise 4](#ex-4)\n - [2.2 Exercise 5](#ex-5)\n - [2.3 Exercise 6](#ex-6)\n - [2.4 Exercise 7](#ex-7)\n- [3. Combining the edits](#3)\n - [3.1 Exercise 8](#ex-8)\n - [3.2 Exercise 9](#ex-9)\n - [3.3 Exercise 10](#ex-10)\n- [4. Minimum Edit Distance](#4)\n - [4.1 Exercise 11](#ex-11)\n- [5. Backtrace (Optional)](#5)", "_____no_output_____" ], [ "<a name='0'></a>\n## 0. Overview\n\nYou use autocorrect every day on your cell phone and computer. In this assignment, you will explore what really goes on behind the scenes. Of course, the model you are about to implement is not identical to the one used in your phone, but it is still quite good. \n\nBy completing this assignment you will learn how to: \n\n- Get a word count given a corpus\n- Get a word probability in the corpus \n- Manipulate strings \n- Filter strings \n- Implement Minimum edit distance to compare strings and to help find the optimal path for the edits. \n- Understand how dynamic programming works\n\n\nSimilar systems are used everywhere. \n- For example, if you type in the word **\"I am lerningg\"**, chances are very high that you meant to write **\"learning\"**, as shown in **Figure 1**. ", "_____no_output_____" ], [ "<div style=\"width:image width px; font-size:100%; text-align:center;\"><img src='auto-correct.png' alt=\"alternate text\" width=\"width\" height=\"height\" style=\"width:300px;height:250px;\" /> Figure 1 </div>", "_____no_output_____" ], [ "<a name='0-1'></a>\n#### 0.1 Edit Distance\n\nIn this assignment, you will implement models that correct words that are 1 and 2 edit distances away. \n- We say two words are n edit distance away from each other when we need n edits to change one word into another. \n\nAn edit could consist of one of the following options: \n\n- Delete (remove a letter): ‘hat’ => ‘at, ha, ht’\n- Switch (swap 2 adjacent letters): ‘eta’ => ‘eat, tea,...’\n- Replace (change 1 letter to another): ‘jat’ => ‘hat, rat, cat, mat, ...’\n- Insert (add a letter): ‘te’ => ‘the, ten, ate, ...’\n\nYou will be using the four methods above to implement an Auto-correct. \n- To do so, you will need to compute probabilities that a certain word is correct given an input. \n\nThis auto-correct you are about to implement was first created by [Peter Norvig](https://en.wikipedia.org/wiki/Peter_Norvig) in 2007. \n- His [original article](https://norvig.com/spell-correct.html) may be a useful reference for this assignment.\n\nThe goal of our spell check model is to compute the following probability:\n\n$$P(c|w) = \\frac{P(w|c)\\times P(c)}{P(w)} \\tag{Eqn-1}$$\n\nThe equation above is [Bayes Rule](https://en.wikipedia.org/wiki/Bayes%27_theorem). \n- Equation 1 says that the probability of a word being correct $P(c|w) $is equal to the probability of having a certain word $w$, given that it is correct $P(w|c)$, multiplied by the probability of being correct in general $P(C)$ divided by the probability of that word $w$ appearing $P(w)$ in general.\n- To compute equation 1, you will first import a data set and then create all the probabilities that you need using that data set. ", "_____no_output_____" ], [ "<a name='1'></a>\n# Part 1: Data Preprocessing ", "_____no_output_____" ] ], [ [ "import re\nfrom collections import Counter\nimport numpy as np\nimport pandas as pd", "_____no_output_____" ] ], [ [ "As in any other machine learning task, the first thing you have to do is process your data set. \n- Many courses load in pre-processed data for you. \n- However, in the real world, when you build these NLP systems, you load the datasets and process them.\n- So let's get some real world practice in pre-processing the data!\n\nYour first task is to read in a file called **'shakespeare.txt'** which is found in your file directory. To look at this file you can go to `File ==> Open `. ", "_____no_output_____" ], [ "<a name='ex-1'></a>\n### Exercise 1\nImplement the function `process_data` which \n\n1) Reads in a corpus (text file)\n\n2) Changes everything to lowercase\n\n3) Returns a list of words. ", "_____no_output_____" ], [ "#### Options and Hints\n- If you would like more of a real-life practice, don't open the 'Hints' below (yet) and try searching the web to derive your answer.\n- If you want a little help, click on the green \"General Hints\" section by clicking on it with your mouse.\n- If you get stuck or are not getting the expected results, click on the green 'Detailed Hints' section to get hints for each step that you'll take to complete this function.", "_____no_output_____" ], [ "<details> \n<summary>\n <font size=\"3\" color=\"darkgreen\"><b>General Hints</b></font>\n</summary>\n<p>\n \nGeneral Hints to get started\n<ul>\n <li>Python <a href=\"https://docs.python.org/3/tutorial/inputoutput.html\">input and output<a></li>\n <li>Python <a href=\"https://docs.python.org/3/library/re.html\" >'re' documentation </a> </li>\n</ul>\n</p>\n", "_____no_output_____" ], [ "<details> \n<summary>\n <font size=\"3\" color=\"darkgreen\"><b>Detailed Hints</b></font>\n</summary>\n<p> \nDetailed hints if you're stuck\n<ul>\n <li>Use 'with' syntax to read a file</li>\n <li>Decide whether to use 'read()' or 'readline(). What's the difference?</li>\n <li>Choose whether to use either str.lower() or str.lowercase(). What is the difference?</li>\n <li>Use re.findall(pattern, string)</li>\n <li>Look for the \"Raw String Notation\" section in the Python 're' documentation to understand the difference between r'\\W', r'\\W' and '\\\\W'. </li>\n <li>For the pattern, decide between using '\\s', '\\w', '\\s+' or '\\w+'. What do you think are the differences?</li>\n</ul>\n</p>\n", "_____no_output_____" ] ], [ [ "# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: process_data\ndef process_data(file_name):\n \"\"\"\n Input: \n A file_name which is found in your current directory. You just have to read it in. \n Output: \n words: a list containing all the words in the corpus (text file you read) in lower case. \n \"\"\"\n words = [] # return this variable correctly\n\n ### START CODE HERE ### \n f = open(file_name, \"r\")\n words = f.read().lower()\n words = re.sub(r\"[^a-zA-Z0-9]\", \" \", words)\n words = words.split()\n ### END CODE HERE ###\n \n return words", "_____no_output_____" ] ], [ [ "Note, in the following cell, 'words' is converted to a python `set`. This eliminates any duplicate entries.", "_____no_output_____" ] ], [ [ "#DO NOT MODIFY THIS CELL\nword_l = process_data('shakespeare.txt')\nvocab = set(word_l) # this will be your new vocabulary\nprint(f\"The first ten words in the text are: \\n{word_l[0:10]}\")\nprint(f\"There are {len(vocab)} unique words in the vocabulary.\")", "The first ten words in the text are: \n['o', 'for', 'a', 'muse', 'of', 'fire', 'that', 'would', 'ascend', 'the']\nThere are 6116 unique words in the vocabulary.\n" ] ], [ [ "#### Expected Output\n```Python\nThe first ten words in the text are: \n['o', 'for', 'a', 'muse', 'of', 'fire', 'that', 'would', 'ascend', 'the']\nThere are 6116 unique words in the vocabulary.\n```", "_____no_output_____" ], [ "<a name='ex-2'></a>\n### Exercise 2\n\nImplement a `get_count` function that returns a dictionary\n- The dictionary's keys are words\n- The value for each word is the number of times that word appears in the corpus. \n\nFor example, given the following sentence: **\"I am happy because I am learning\"**, your dictionary should return the following: \n<table style=\"width:20%\">\n\n <tr>\n <td> <b>Key </b> </td>\n <td> <b>Value </b> </td> \n\n\n </tr>\n <tr>\n <td> I </td>\n <td> 2</td> \n \n </tr>\n \n <tr>\n <td>am</td>\n <td>2</td> \n </tr>\n\n <tr>\n <td>happy</td>\n <td>1</td> \n </tr>\n \n <tr>\n <td>because</td>\n <td>1</td> \n </tr>\n \n <tr>\n <td>learning</td>\n <td>1</td> \n </tr>\n</table>\n\n\n**Instructions**: \nImplement a `get_count` which returns a dictionary where the key is a word and the value is the number of times the word appears in the list. \n", "_____no_output_____" ], [ "<details> \n<summary>\n <font size=\"3\" color=\"darkgreen\"><b>Hints</b></font>\n</summary>\n<p>\n<ul>\n <li>Try implementing this using a for loop and a regular dictionary. This may be good practice for similar coding interview questions</li>\n <li>You can also use defaultdict instead of a regualr dictionary, along with the for loop</li>\n <li>Otherwise, to skip using a for loop, you can use Python's <a href=\"https://docs.python.org/3.7/library/collections.html#collections.Counter\" > Counter class</a> </li>\n</ul>\n</p>", "_____no_output_____" ] ], [ [ "# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# UNIT TEST COMMENT: Candidate for Table Driven Tests\n# GRADED FUNCTION: get_count\ndef get_count(word_l):\n '''\n Input:\n word_l: a set of words representing the corpus. \n Output:\n word_count_dict: The wordcount dictionary where key is the word and value is its frequency.\n '''\n \n word_count_dict = {} # fill this with word counts\n ### START CODE HERE \n word_count_dict = Counter(word_l)\n ### END CODE HERE ### \n return word_count_dict", "_____no_output_____" ], [ "#DO NOT MODIFY THIS CELL\nword_count_dict = get_count(word_l)\nprint(f\"There are {len(word_count_dict)} key values pairs\")\nprint(f\"The count for the word 'thee' is {word_count_dict.get('thee',0)}\")", "There are 6116 key values pairs\nThe count for the word 'thee' is 240\n" ] ], [ [ "\n#### Expected Output\n```Python\nThere are 6116 key values pairs\nThe count for the word 'thee' is 240\n```", "_____no_output_____" ], [ "<a name='ex-3'></a>\n### Exercise 3\nGiven the dictionary of word counts, compute the probability that each word will appear if randomly selected from the corpus of words.\n\n$$P(w_i) = \\frac{C(w_i)}{M} \\tag{Eqn-2}$$\nwhere \n\n$C(w_i)$ is the total number of times $w_i$ appears in the corpus.\n\n$M$ is the total number of words in the corpus.\n\nFor example, the probability of the word 'am' in the sentence **'I am happy because I am learning'** is:\n\n$$P(am) = \\frac{C(w_i)}{M} = \\frac {2}{7} \\tag{Eqn-3}.$$\n\n**Instructions:** Implement `get_probs` function which gives you the probability \nthat a word occurs in a sample. This returns a dictionary where the keys are words, and the value for each word is its probability in the corpus of words.", "_____no_output_____" ], [ "<details> \n<summary>\n <font size=\"3\" color=\"darkgreen\"><b>Hints</b></font>\n</summary>\n<p>\nGeneral advice\n<ul>\n <li> Use dictionary.values() </li>\n <li> Use sum() </li>\n <li> The cardinality (number of words in the corpus should be equal to len(word_l). You will calculate this same number, but using the word count dictionary.</li>\n</ul>\n \nIf you're using a for loop:\n<ul>\n <li> Use dictionary.keys() </li>\n</ul>\n \nIf you're using a dictionary comprehension:\n<ul>\n <li>Use dictionary.items() </li>\n</ul>\n</p>\n", "_____no_output_____" ] ], [ [ "# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: get_probs\ndef get_probs(word_count_dict):\n '''\n Input:\n word_count_dict: The wordcount dictionary where key is the word and value is its frequency.\n Output:\n probs: A dictionary where keys are the words and the values are the probability that a word will occur. \n '''\n probs = {} # return this variable correctly\n \n ### START CODE HERE ###\n M = sum(word_count_dict.values(), 0)\n for key in word_count_dict:\n probs[key] = word_count_dict[key] / M\n ### END CODE HERE ###\n return probs", "_____no_output_____" ], [ "#DO NOT MODIFY THIS CELL\nprobs = get_probs(word_count_dict)\nprint(f\"Length of probs is {len(probs)}\")\nprint(f\"P('thee') is {probs['thee']:.4f}\")", "Length of probs is 6116\nP('thee') is 0.0045\n" ] ], [ [ "#### Expected Output\n\n```Python\nLength of probs is 6116\nP('thee') is 0.0045\n```", "_____no_output_____" ], [ "<a name='2'></a>\n# Part 2: String Manipulations\n\nNow, that you have computed $P(w_i)$ for all the words in the corpus, you will write a few functions to manipulate strings so that you can edit the erroneous strings and return the right spellings of the words. In this section, you will implement four functions: \n\n* `delete_letter`: given a word, it returns all the possible strings that have **one character removed**. \n* `switch_letter`: given a word, it returns all the possible strings that have **two adjacent letters switched**.\n* `replace_letter`: given a word, it returns all the possible strings that have **one character replaced by another different letter**.\n* `insert_letter`: given a word, it returns all the possible strings that have an **additional character inserted**. \n", "_____no_output_____" ], [ "#### List comprehensions\n\nString and list manipulation in python will often make use of a python feature called [list comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions). The routines below will be described as using list comprehensions, but if you would rather implement them in another way, you are free to do so as long as the result is the same. Further, the following section will provide detailed instructions on how to use list comprehensions and how to implement the desired functions. If you are a python expert, feel free to skip the python hints and move to implementing the routines directly.", "_____no_output_____" ], [ "Python List Comprehensions embed a looping structure inside of a list declaration, collapsing many lines of code into a single line. If you are not familiar with them, they seem slightly out of order relative to for loops. ", "_____no_output_____" ], [ "<div style=\"width:image width px; font-size:100%; text-align:center;\"><img src='GenericListComp3.PNG' alt=\"alternate text\" width=\"width\" height=\"height\" style=\"width:800px;height:400px;\"/> Figure 2 </div>", "_____no_output_____" ], [ "The diagram above shows that the components of a list comprehension are the same components you would find in a typical for loop that appends to a list, but in a different order. With that in mind, we'll continue the specifics of this assignment. We will be very descriptive for the first function, `deletes()`, and less so in later functions as you become familiar with list comprehensions.", "_____no_output_____" ], [ "<a name='ex-4'></a>\n### Exercise 4\n\n**Instructions for delete_letter():** Implement a `delete_letter()` function that, given a word, returns a list of strings with one character deleted. \n\nFor example, given the word **nice**, it would return the set: {'ice', 'nce', 'nic', 'nie'}. \n\n**Step 1:** Create a list of 'splits'. This is all the ways you can split a word into Left and Right: For example, \n'nice is split into : `[('', 'nice'), ('n', 'ice'), ('ni', 'ce'), ('nic', 'e'), ('nice', '')]`\nThis is common to all four functions (delete, replace, switch, insert).\n", "_____no_output_____" ], [ "<div style=\"width:image width px; font-size:100%; text-align:center;\"><img src='Splits1.PNG' alt=\"alternate text\" width=\"width\" height=\"height\" style=\"width:650px;height:200px;\" /> Figure 3 </div>", "_____no_output_____" ], [ "**Step 2:** This is specific to `delete_letter`. Here, we are generating all words that result from deleting one character. \nThis can be done in a single line with a list comprehension. You can make use of this type of syntax: \n`[f(a,b) for a, b in splits if condition]` \n\nFor our 'nice' example you get: \n['ice', 'nce', 'nie', 'nic']", "_____no_output_____" ], [ "<div style=\"width:image width px; font-size:100%; text-align:center;\"><img src='ListComp2.PNG' alt=\"alternate text\" width=\"width\" height=\"height\" style=\"width:550px;height:300px;\" /> Figure 4 </div>", "_____no_output_____" ], [ "#### Levels of assistance\n\nTry this exercise with these levels of assistance. \n- We hope that this will make it both a meaningful experience but also not a frustrating experience. \n- Start with level 1, then move onto level 2, and 3 as needed.\n\n - Level 1. Try to think this through and implement this yourself.\n - Level 2. Click on the \"Level 2 Hints\" section for some hints to get started.\n - Level 3. If you would prefer more guidance, please click on the \"Level 3 Hints\" cell for step by step instructions.\n \n- If you are still stuck, look at the images in the \"list comprehensions\" section above.\n", "_____no_output_____" ], [ "<details> \n<summary>\n <font size=\"3\" color=\"darkgreen\"><b>Level 2 Hints</b></font>\n</summary>\n<p>\n<ul>\n <li><a href=\"\" > Use array slicing like my_string[0:2] </a> </li>\n <li><a href=\"\" > Use list comprehensions or for loops </a> </li>\n</ul>\n</p>\n", "_____no_output_____" ], [ "<details> \n<summary>\n <font size=\"3\" color=\"darkgreen\"><b>Level 3 Hints</b></font>\n</summary>\n<p>\n<ul>\n <li>splits: Use array slicing, like my_str[0:2], to separate a string into two pieces.</li>\n <li>Do this in a loop or list comprehension, so that you have a list of tuples.\n <li> For example, \"cake\" can get split into \"ca\" and \"ke\". They're stored in a tuple (\"ca\",\"ke\"), and the tuple is appended to a list. We'll refer to these as L and R, so the tuple is (L,R)</li>\n <li>When choosing the range for your loop, if you input the word \"cans\" and generate the tuple ('cans',''), make sure to include an if statement to check the length of that right-side string (R) in the tuple (L,R) </li>\n <li>deletes: Go through the list of tuples and combine the two strings together. You can use the + operator to combine two strings</li>\n <li>When combining the tuples, make sure that you leave out a middle character.</li>\n <li>Use array slicing to leave out the first character of the right substring.</li>\n</ul>\n</p>", "_____no_output_____" ] ], [ [ "# UNQ_C4 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# UNIT TEST COMMENT: Candidate for Table Driven Tests\n# GRADED FUNCTION: deletes\ndef delete_letter(word, verbose=False):\n '''\n Input:\n word: the string/word for which you will generate all possible words \n in the vocabulary which have 1 missing character\n Output:\n delete_l: a list of all possible strings obtained by deleting 1 character from word\n '''\n \n delete_l = []\n split_l = []\n \n ### START CODE HERE ###\n split_l = [(word[:i], word[i:]) for i in range(len(word) + 1) if word[i:]]\n delete_l = [L + R[1:] for L, R in split_l]\n ### END CODE HERE ###\n\n if verbose: print(f\"input word {word}, \\nsplit_l = {split_l}, \\ndelete_l = {delete_l}\")\n\n return delete_l", "_____no_output_____" ], [ "delete_word_l = delete_letter(word=\"cans\",\n verbose=True)", "input word cans, \nsplit_l = [('', 'cans'), ('c', 'ans'), ('ca', 'ns'), ('can', 's')], \ndelete_l = ['ans', 'cns', 'cas', 'can']\n" ] ], [ [ "#### Expected Output\n```CPP\nNote: You might get a slightly different result with split_l\n\ninput word cans, \nsplit_l = [('', 'cans'), ('c', 'ans'), ('ca', 'ns'), ('can', 's')], \ndelete_l = ['ans', 'cns', 'cas', 'can']\n```", "_____no_output_____" ], [ "#### Note 1\n- Notice how it has the extra tuple `('cans', '')`.\n- This will be fine as long as you have checked the size of the right-side substring in tuple (L,R).\n- Can you explain why this will give you the same result for the list of deletion strings (delete_l)?\n\n```CPP\ninput word cans, \nsplit_l = [('', 'cans'), ('c', 'ans'), ('ca', 'ns'), ('can', 's'), ('cans', '')], \ndelete_l = ['ans', 'cns', 'cas', 'can']\n```", "_____no_output_____" ], [ "#### Note 2\nIf you end up getting the same word as your input word, like this:\n\n```Python\ninput word cans, \nsplit_l = [('', 'cans'), ('c', 'ans'), ('ca', 'ns'), ('can', 's'), ('cans', '')], \ndelete_l = ['ans', 'cns', 'cas', 'can', 'cans']\n```\n\n- Check how you set the `range`.\n- See if you check the length of the string on the right-side of the split.", "_____no_output_____" ] ], [ [ "# test # 2\nprint(f\"Number of outputs of delete_letter('at') is {len(delete_letter('at'))}\")", "Number of outputs of delete_letter('at') is 2\n" ] ], [ [ "#### Expected output\n\n```CPP\nNumber of outputs of delete_letter('at') is 2\n```", "_____no_output_____" ], [ "<a name='ex-5'></a>\n### Exercise 5\n\n**Instructions for switch_letter()**: Now implement a function that switches two letters in a word. It takes in a word and returns a list of all the possible switches of two letters **that are adjacent to each other**. \n- For example, given the word 'eta', it returns {'eat', 'tea'}, but does not return 'ate'.\n\n**Step 1:** is the same as in delete_letter() \n**Step 2:** A list comprehension or for loop which forms strings by swapping adjacent letters. This is of the form: \n`[f(L,R) for L, R in splits if condition]` where 'condition' will test the length of R in a given iteration. See below.", "_____no_output_____" ], [ "<div style=\"width:image width px; font-size:100%; text-align:center;\"><img src='Switches1.PNG' alt=\"alternate text\" width=\"width\" height=\"height\" style=\"width:600px;height:200px;\"/> Figure 5 </div> ", "_____no_output_____" ], [ "#### Levels of difficulty\n\nTry this exercise with these levels of difficulty. \n- Level 1. Try to think this through and implement this yourself.\n- Level 2. Click on the \"Level 2 Hints\" section for some hints to get started.\n- Level 3. If you would prefer more guidance, please click on the \"Level 3 Hints\" cell for step by step instructions.", "_____no_output_____" ], [ "<details> \n<summary>\n <font size=\"3\" color=\"darkgreen\"><b>Level 2 Hints</b></font>\n</summary>\n<p>\n<ul>\n <li><a href=\"\" > Use array slicing like my_string[0:2] </a> </li>\n <li><a href=\"\" > Use list comprehensions or for loops </a> </li>\n <li>To do a switch, think of the whole word as divided into 4 distinct parts. Write out 'cupcakes' on a piece of paper and see how you can split it into ('cupc', 'k', 'a', 'es')</li>\n</ul>\n</p>\n", "_____no_output_____" ], [ "<details> \n<summary>\n <font size=\"3\" color=\"darkgreen\"><b>Level 3 Hints</b></font>\n</summary>\n<p>\n<ul>\n <li>splits: Use array slicing, like my_str[0:2], to separate a string into two pieces.</li>\n <li>Splitting is the same as for delete_letter</li>\n <li>To perform the switch, go through the list of tuples and combine four strings together. You can use the + operator to combine strings</li>\n <li>The four strings will be the left substring from the split tuple, followed by the first (index 1) character of the right substring, then the zero-th character (index 0) of the right substring, and then the remaining part of the right substring.</li>\n <li>Unlike delete_letter, you will want to check that your right substring is at least a minimum length. To see why, review the previous hint bullet point (directly before this one).</li>\n</ul>\n</p>", "_____no_output_____" ] ], [ [ "# UNQ_C5 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# UNIT TEST COMMENT: Candidate for Table Driven Tests\n# GRADED FUNCTION: switches\ndef switch_letter(word, verbose=False):\n '''\n Input:\n word: input string\n Output:\n switches: a list of all possible strings with one adjacent charater switched\n ''' \n \n switch_l = []\n split_l = []\n \n ### START CODE HERE ###\n split_l = [(word[:i], word[i:]) for i in range(len(word) + 1) if word[i:]]\n switch_l = [L + R[1] + R[0] + R[2:] for L, R in split_l if len(R) > 1]\n ### END CODE HERE ###\n \n if verbose: print(f\"Input word = {word} \\nsplit_l = {split_l} \\nswitch_l = {switch_l}\") \n\n return switch_l", "_____no_output_____" ], [ "switch_word_l = switch_letter(word=\"eta\",\n verbose=True)", "Input word = eta \nsplit_l = [('', 'eta'), ('e', 'ta'), ('et', 'a')] \nswitch_l = ['tea', 'eat']\n" ] ], [ [ "#### Expected output\n\n```Python\nInput word = eta \nsplit_l = [('', 'eta'), ('e', 'ta'), ('et', 'a')] \nswitch_l = ['tea', 'eat']\n```", "_____no_output_____" ], [ "#### Note 1\n\nYou may get this:\n```Python\nInput word = eta \nsplit_l = [('', 'eta'), ('e', 'ta'), ('et', 'a'), ('eta', '')] \nswitch_l = ['tea', 'eat']\n```\n- Notice how it has the extra tuple `('eta', '')`.\n- This is also correct.\n- Can you think of why this is the case?", "_____no_output_____" ], [ "#### Note 2\n\nIf you get an error\n```Python\nIndexError: string index out of range\n```\n- Please see if you have checked the length of the strings when switching characters.", "_____no_output_____" ] ], [ [ "# test # 2\nprint(f\"Number of outputs of switch_letter('at') is {len(switch_letter('at'))}\")", "Number of outputs of switch_letter('at') is 1\n" ] ], [ [ "#### Expected output\n\n```CPP\nNumber of outputs of switch_letter('at') is 1\n```", "_____no_output_____" ], [ "<a name='ex-6'></a>\n### Exercise 6\n**Instructions for replace_letter()**: Now implement a function that takes in a word and returns a list of strings with one **replaced letter** from the original word. \n\n**Step 1:** is the same as in `delete_letter()`\n\n**Step 2:** A list comprehension or for loop which form strings by replacing letters. This can be of the form: \n`[f(a,b,c) for a, b in splits if condition for c in string]` Note the use of the second for loop. \nIt is expected in this routine that one or more of the replacements will include the original word. For example, replacing the first letter of 'ear' with 'e' will return 'ear'.\n\n**Step 3:** Remove the original input letter from the output.", "_____no_output_____" ], [ "<details> \n<summary>\n <font size=\"3\" color=\"darkgreen\"><b>Hints</b></font>\n</summary>\n<p>\n<ul>\n <li>To remove a word from a list, first store its contents inside a set()</li>\n <li>Use set.discard('the_word') to remove a word in a set (if the word does not exist in the set, then it will not throw a KeyError. Using set.remove('the_word') throws a KeyError if the word does not exist in the set. </li>\n</ul>\n</p>\n", "_____no_output_____" ] ], [ [ "# UNQ_C6 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# UNIT TEST COMMENT: Candidate for Table Driven Tests\n# GRADED FUNCTION: replaces\ndef replace_letter(word, verbose=False):\n '''\n Input:\n word: the input string/word \n Output:\n replaces: a list of all possible strings where we replaced one letter from the original word. \n ''' \n \n letters = 'abcdefghijklmnopqrstuvwxyz'\n replace_l = []\n split_l = []\n \n ### START CODE HERE ###\n split_l = [(word[:i], word[i:]) for i in range(len(word) + 1) if word[i:]]\n replace_set = set([L + i + R[1:] for L, R in split_l for i in letters])\n replace_set.discard(word)\n ### END CODE HERE ###\n \n # turn the set back into a list and sort it, for easier viewing\n replace_l = sorted(list(replace_set))\n \n if verbose: print(f\"Input word = {word} \\nsplit_l = {split_l} \\nreplace_l {replace_l}\") \n \n return replace_l", "_____no_output_____" ], [ "replace_l = replace_letter(word='can',\n verbose=True)", "Input word = can \nsplit_l = [('', 'can'), ('c', 'an'), ('ca', 'n')] \nreplace_l ['aan', 'ban', 'caa', 'cab', 'cac', 'cad', 'cae', 'caf', 'cag', 'cah', 'cai', 'caj', 'cak', 'cal', 'cam', 'cao', 'cap', 'caq', 'car', 'cas', 'cat', 'cau', 'cav', 'caw', 'cax', 'cay', 'caz', 'cbn', 'ccn', 'cdn', 'cen', 'cfn', 'cgn', 'chn', 'cin', 'cjn', 'ckn', 'cln', 'cmn', 'cnn', 'con', 'cpn', 'cqn', 'crn', 'csn', 'ctn', 'cun', 'cvn', 'cwn', 'cxn', 'cyn', 'czn', 'dan', 'ean', 'fan', 'gan', 'han', 'ian', 'jan', 'kan', 'lan', 'man', 'nan', 'oan', 'pan', 'qan', 'ran', 'san', 'tan', 'uan', 'van', 'wan', 'xan', 'yan', 'zan']\n" ] ], [ [ "#### Expected Output**: \n```Python\nInput word = can \nsplit_l = [('', 'can'), ('c', 'an'), ('ca', 'n')] \nreplace_l ['aan', 'ban', 'caa', 'cab', 'cac', 'cad', 'cae', 'caf', 'cag', 'cah', 'cai', 'caj', 'cak', 'cal', 'cam', 'cao', 'cap', 'caq', 'car', 'cas', 'cat', 'cau', 'cav', 'caw', 'cax', 'cay', 'caz', 'cbn', 'ccn', 'cdn', 'cen', 'cfn', 'cgn', 'chn', 'cin', 'cjn', 'ckn', 'cln', 'cmn', 'cnn', 'con', 'cpn', 'cqn', 'crn', 'csn', 'ctn', 'cun', 'cvn', 'cwn', 'cxn', 'cyn', 'czn', 'dan', 'ean', 'fan', 'gan', 'han', 'ian', 'jan', 'kan', 'lan', 'man', 'nan', 'oan', 'pan', 'qan', 'ran', 'san', 'tan', 'uan', 'van', 'wan', 'xan', 'yan', 'zan']\n```\n- Note how the input word 'can' should not be one of the output words.", "_____no_output_____" ], [ "#### Note 1\nIf you get something like this:\n\n```Python\nInput word = can \nsplit_l = [('', 'can'), ('c', 'an'), ('ca', 'n'), ('can', '')] \nreplace_l ['aan', 'ban', 'caa', 'cab', 'cac', 'cad', 'cae', 'caf', 'cag', 'cah', 'cai', 'caj', 'cak', 'cal', 'cam', 'cao', 'cap', 'caq', 'car', 'cas', 'cat', 'cau', 'cav', 'caw', 'cax', 'cay', 'caz', 'cbn', 'ccn', 'cdn', 'cen', 'cfn', 'cgn', 'chn', 'cin', 'cjn', 'ckn', 'cln', 'cmn', 'cnn', 'con', 'cpn', 'cqn', 'crn', 'csn', 'ctn', 'cun', 'cvn', 'cwn', 'cxn', 'cyn', 'czn', 'dan', 'ean', 'fan', 'gan', 'han', 'ian', 'jan', 'kan', 'lan', 'man', 'nan', 'oan', 'pan', 'qan', 'ran', 'san', 'tan', 'uan', 'van', 'wan', 'xan', 'yan', 'zan']\n```\n- Notice how split_l has an extra tuple `('can', '')`, but the output is still the same, so this is okay.", "_____no_output_____" ], [ "#### Note 2\nIf you get something like this:\n```Python\nInput word = can \nsplit_l = [('', 'can'), ('c', 'an'), ('ca', 'n'), ('can', '')] \nreplace_l ['aan', 'ban', 'caa', 'cab', 'cac', 'cad', 'cae', 'caf', 'cag', 'cah', 'cai', 'caj', 'cak', 'cal', 'cam', 'cana', 'canb', 'canc', 'cand', 'cane', 'canf', 'cang', 'canh', 'cani', 'canj', 'cank', 'canl', 'canm', 'cann', 'cano', 'canp', 'canq', 'canr', 'cans', 'cant', 'canu', 'canv', 'canw', 'canx', 'cany', 'canz', 'cao', 'cap', 'caq', 'car', 'cas', 'cat', 'cau', 'cav', 'caw', 'cax', 'cay', 'caz', 'cbn', 'ccn', 'cdn', 'cen', 'cfn', 'cgn', 'chn', 'cin', 'cjn', 'ckn', 'cln', 'cmn', 'cnn', 'con', 'cpn', 'cqn', 'crn', 'csn', 'ctn', 'cun', 'cvn', 'cwn', 'cxn', 'cyn', 'czn', 'dan', 'ean', 'fan', 'gan', 'han', 'ian', 'jan', 'kan', 'lan', 'man', 'nan', 'oan', 'pan', 'qan', 'ran', 'san', 'tan', 'uan', 'van', 'wan', 'xan', 'yan', 'zan']\n```\n- Notice how there are strings that are 1 letter longer than the original word, such as `cana`.\n- Please check for the case when there is an empty string `''`, and if so, do not use that empty string when setting replace_l.", "_____no_output_____" ] ], [ [ "# test # 2\nprint(f\"Number of outputs of switch_letter('at') is {len(switch_letter('at'))}\")", "Number of outputs of switch_letter('at') is 1\n" ] ], [ [ "#### Expected output\n```CPP\nNumber of outputs of switch_letter('at') is 1\n```", "_____no_output_____" ], [ "<a name='ex-7'></a>\n### Exercise 7\n\n**Instructions for insert_letter()**: Now implement a function that takes in a word and returns a list with a letter inserted at every offset.\n\n**Step 1:** is the same as in `delete_letter()`\n\n**Step 2:** This can be a list comprehension of the form: \n`[f(a,b,c) for a, b in splits if condition for c in string]` ", "_____no_output_____" ] ], [ [ "# UNQ_C7 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# UNIT TEST COMMENT: Candidate for Table Driven Tests\n# GRADED FUNCTION: inserts\ndef insert_letter(word, verbose=False):\n '''\n Input:\n word: the input string/word \n Output:\n inserts: a set of all possible strings with one new letter inserted at every offset\n ''' \n letters = 'abcdefghijklmnopqrstuvwxyz'\n insert_l = []\n split_l = []\n \n ### START CODE HERE ###\n split_l = [(word[:i], word[i:]) for i in range(len(word) + 1)]\n insert_l = [L + i + R for L, R in split_l for i in letters]\n ### END CODE HERE ###\n\n if verbose: print(f\"Input word {word} \\nsplit_l = {split_l} \\ninsert_l = {insert_l}\")\n \n return insert_l", "_____no_output_____" ], [ "insert_l = insert_letter('at', True)\nprint(f\"Number of strings output by insert_letter('at') is {len(insert_l)}\")", "Input word at \nsplit_l = [('', 'at'), ('a', 't'), ('at', '')] \ninsert_l = ['aat', 'bat', 'cat', 'dat', 'eat', 'fat', 'gat', 'hat', 'iat', 'jat', 'kat', 'lat', 'mat', 'nat', 'oat', 'pat', 'qat', 'rat', 'sat', 'tat', 'uat', 'vat', 'wat', 'xat', 'yat', 'zat', 'aat', 'abt', 'act', 'adt', 'aet', 'aft', 'agt', 'aht', 'ait', 'ajt', 'akt', 'alt', 'amt', 'ant', 'aot', 'apt', 'aqt', 'art', 'ast', 'att', 'aut', 'avt', 'awt', 'axt', 'ayt', 'azt', 'ata', 'atb', 'atc', 'atd', 'ate', 'atf', 'atg', 'ath', 'ati', 'atj', 'atk', 'atl', 'atm', 'atn', 'ato', 'atp', 'atq', 'atr', 'ats', 'att', 'atu', 'atv', 'atw', 'atx', 'aty', 'atz']\nNumber of strings output by insert_letter('at') is 78\n" ] ], [ [ "#### Expected output\n\n```Python\nInput word at \nsplit_l = [('', 'at'), ('a', 't'), ('at', '')] \ninsert_l = ['aat', 'bat', 'cat', 'dat', 'eat', 'fat', 'gat', 'hat', 'iat', 'jat', 'kat', 'lat', 'mat', 'nat', 'oat', 'pat', 'qat', 'rat', 'sat', 'tat', 'uat', 'vat', 'wat', 'xat', 'yat', 'zat', 'aat', 'abt', 'act', 'adt', 'aet', 'aft', 'agt', 'aht', 'ait', 'ajt', 'akt', 'alt', 'amt', 'ant', 'aot', 'apt', 'aqt', 'art', 'ast', 'att', 'aut', 'avt', 'awt', 'axt', 'ayt', 'azt', 'ata', 'atb', 'atc', 'atd', 'ate', 'atf', 'atg', 'ath', 'ati', 'atj', 'atk', 'atl', 'atm', 'atn', 'ato', 'atp', 'atq', 'atr', 'ats', 'att', 'atu', 'atv', 'atw', 'atx', 'aty', 'atz']\nNumber of strings output by insert_letter('at') is 78\n```", "_____no_output_____" ], [ "#### Note 1\n\nIf you get a split_l like this:\n```Python\nInput word at \nsplit_l = [('', 'at'), ('a', 't')] \ninsert_l = ['aat', 'bat', 'cat', 'dat', 'eat', 'fat', 'gat', 'hat', 'iat', 'jat', 'kat', 'lat', 'mat', 'nat', 'oat', 'pat', 'qat', 'rat', 'sat', 'tat', 'uat', 'vat', 'wat', 'xat', 'yat', 'zat', 'aat', 'abt', 'act', 'adt', 'aet', 'aft', 'agt', 'aht', 'ait', 'ajt', 'akt', 'alt', 'amt', 'ant', 'aot', 'apt', 'aqt', 'art', 'ast', 'att', 'aut', 'avt', 'awt', 'axt', 'ayt', 'azt']\nNumber of strings output by insert_letter('at') is 52\n```\n- Notice that split_l is missing the extra tuple ('at', ''). For insertion, we actually **WANT** this tuple.\n- The function is not creating all the desired output strings.\n- Check the range that you use for the for loop.", "_____no_output_____" ], [ "#### Note 2\nIf you see this:\n```Python\nInput word at \nsplit_l = [('', 'at'), ('a', 't'), ('at', '')] \ninsert_l = ['aat', 'bat', 'cat', 'dat', 'eat', 'fat', 'gat', 'hat', 'iat', 'jat', 'kat', 'lat', 'mat', 'nat', 'oat', 'pat', 'qat', 'rat', 'sat', 'tat', 'uat', 'vat', 'wat', 'xat', 'yat', 'zat', 'aat', 'abt', 'act', 'adt', 'aet', 'aft', 'agt', 'aht', 'ait', 'ajt', 'akt', 'alt', 'amt', 'ant', 'aot', 'apt', 'aqt', 'art', 'ast', 'att', 'aut', 'avt', 'awt', 'axt', 'ayt', 'azt']\nNumber of strings output by insert_letter('at') is 52\n```\n\n- Even though you may have fixed the split_l so that it contains the tuple `('at', '')`, notice that you're still missing some output strings.\n - Notice that it's missing strings such as 'ata', 'atb', 'atc' all the way to 'atz'.\n- To fix this, make sure that when you set insert_l, you allow the use of the empty string `''`.", "_____no_output_____" ] ], [ [ "# test # 2\nprint(f\"Number of outputs of insert_letter('at') is {len(insert_letter('at'))}\")", "Number of outputs of insert_letter('at') is 78\n" ] ], [ [ "#### Expected output\n\n```CPP\nNumber of outputs of insert_letter('at') is 78\n```", "_____no_output_____" ], [ "<a name='3'></a>\n\n# Part 3: Combining the edits\n\nNow that you have implemented the string manipulations, you will create two functions that, given a string, will return all the possible single and double edits on that string. These will be `edit_one_letter()` and `edit_two_letters()`.", "_____no_output_____" ], [ "<a name='3-1'></a>\n## 3.1 Edit one letter\n\n<a name='ex-8'></a>\n### Exercise 8\n\n**Instructions**: Implement the `edit_one_letter` function to get all the possible edits that are one edit away from a word. The edits consist of the replace, insert, delete, and optionally the switch operation. You should use the previous functions you have already implemented to complete this function. The 'switch' function is a less common edit function, so its use will be selected by an \"allow_switches\" input argument.\n\nNote that those functions return *lists* while this function should return a *python set*. Utilizing a set eliminates any duplicate entries.", "_____no_output_____" ], [ "<details> \n<summary>\n <font size=\"3\" color=\"darkgreen\"><b>Hints</b></font>\n</summary>\n<p>\n<ul>\n <li> Each of the functions returns a list. You can combine lists using the `+` operator. </li>\n <li> To get unique strings (avoid duplicates), you can use the set() function. </li>\n</ul>\n</p>\n", "_____no_output_____" ] ], [ [ "# UNQ_C8 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# UNIT TEST COMMENT: Candidate for Table Driven Tests\n# GRADED FUNCTION: edit_one_letter\ndef edit_one_letter(word, allow_switches = True):\n \"\"\"\n Input:\n word: the string/word for which we will generate all possible wordsthat are one edit away.\n Output:\n edit_one_set: a set of words with one possible edit. Please return a set. and not a list.\n \"\"\"\n \n edit_one_set = set()\n \n ### START CODE HERE ###\n switch_l = switch_letter(word) if allow_switches else []\n edit_one_set = set(insert_letter(word) + delete_letter(word) + replace_letter(word) + switch_l)\n ### END CODE HERE ###\n\n return edit_one_set", "_____no_output_____" ], [ "tmp_word = \"at\"\ntmp_edit_one_set = edit_one_letter(tmp_word)\n# turn this into a list to sort it, in order to view it\ntmp_edit_one_l = sorted(list(tmp_edit_one_set))\n\nprint(f\"input word {tmp_word} \\nedit_one_l \\n{tmp_edit_one_l}\\n\")\nprint(f\"The type of the returned object should be a set {type(tmp_edit_one_set)}\")\nprint(f\"Number of outputs from edit_one_letter('at') is {len(edit_one_letter('at'))}\")", "input word at \nedit_one_l \n['a', 'aa', 'aat', 'ab', 'abt', 'ac', 'act', 'ad', 'adt', 'ae', 'aet', 'af', 'aft', 'ag', 'agt', 'ah', 'aht', 'ai', 'ait', 'aj', 'ajt', 'ak', 'akt', 'al', 'alt', 'am', 'amt', 'an', 'ant', 'ao', 'aot', 'ap', 'apt', 'aq', 'aqt', 'ar', 'art', 'as', 'ast', 'ata', 'atb', 'atc', 'atd', 'ate', 'atf', 'atg', 'ath', 'ati', 'atj', 'atk', 'atl', 'atm', 'atn', 'ato', 'atp', 'atq', 'atr', 'ats', 'att', 'atu', 'atv', 'atw', 'atx', 'aty', 'atz', 'au', 'aut', 'av', 'avt', 'aw', 'awt', 'ax', 'axt', 'ay', 'ayt', 'az', 'azt', 'bat', 'bt', 'cat', 'ct', 'dat', 'dt', 'eat', 'et', 'fat', 'ft', 'gat', 'gt', 'hat', 'ht', 'iat', 'it', 'jat', 'jt', 'kat', 'kt', 'lat', 'lt', 'mat', 'mt', 'nat', 'nt', 'oat', 'ot', 'pat', 'pt', 'qat', 'qt', 'rat', 'rt', 'sat', 'st', 't', 'ta', 'tat', 'tt', 'uat', 'ut', 'vat', 'vt', 'wat', 'wt', 'xat', 'xt', 'yat', 'yt', 'zat', 'zt']\n\nThe type of the returned object should be a set <class 'set'>\nNumber of outputs from edit_one_letter('at') is 129\n" ] ], [ [ "#### Expected Output\n```CPP\ninput word at \nedit_one_l \n['a', 'aa', 'aat', 'ab', 'abt', 'ac', 'act', 'ad', 'adt', 'ae', 'aet', 'af', 'aft', 'ag', 'agt', 'ah', 'aht', 'ai', 'ait', 'aj', 'ajt', 'ak', 'akt', 'al', 'alt', 'am', 'amt', 'an', 'ant', 'ao', 'aot', 'ap', 'apt', 'aq', 'aqt', 'ar', 'art', 'as', 'ast', 'ata', 'atb', 'atc', 'atd', 'ate', 'atf', 'atg', 'ath', 'ati', 'atj', 'atk', 'atl', 'atm', 'atn', 'ato', 'atp', 'atq', 'atr', 'ats', 'att', 'atu', 'atv', 'atw', 'atx', 'aty', 'atz', 'au', 'aut', 'av', 'avt', 'aw', 'awt', 'ax', 'axt', 'ay', 'ayt', 'az', 'azt', 'bat', 'bt', 'cat', 'ct', 'dat', 'dt', 'eat', 'et', 'fat', 'ft', 'gat', 'gt', 'hat', 'ht', 'iat', 'it', 'jat', 'jt', 'kat', 'kt', 'lat', 'lt', 'mat', 'mt', 'nat', 'nt', 'oat', 'ot', 'pat', 'pt', 'qat', 'qt', 'rat', 'rt', 'sat', 'st', 't', 'ta', 'tat', 'tt', 'uat', 'ut', 'vat', 'vt', 'wat', 'wt', 'xat', 'xt', 'yat', 'yt', 'zat', 'zt']\n\nThe type of the returned object should be a set <class 'set'>\nNumber of outputs from edit_one_letter('at') is 129\n```", "_____no_output_____" ], [ "<a name='3-2'></a>\n## Part 3.2 Edit two letters\n\n<a name='ex-9'></a>\n### Exercise 9\n\nNow you can generalize this to implement to get two edits on a word. To do so, you would have to get all the possible edits on a single word and then for each modified word, you would have to modify it again. \n\n**Instructions**: Implement the `edit_two_letters` function that returns a set of words that are two edits away. Note that creating additional edits based on the `edit_one_letter` function may 'restore' some one_edits to zero or one edits. That is allowed here. This accounted for in get_corrections.", "_____no_output_____" ], [ "<details> \n<summary>\n <font size=\"3\" color=\"darkgreen\"><b>Hints</b></font>\n</summary>\n<p>\n<ul>\n <li>You will likely want to take the union of two sets.</li>\n <li>You can either use set.union() or use the '|' (or operator) to union two sets</li>\n <li>See the documentation <a href=\"https://docs.python.org/2/library/sets.html\" > Python sets </a> for examples of using operators or functions of the Python set.</li>\n</ul>\n</p>\n", "_____no_output_____" ] ], [ [ "# UNQ_C9 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# UNIT TEST COMMENT: Candidate for Table Driven Tests\n# GRADED FUNCTION: edit_two_letters\ndef edit_two_letters(word, allow_switches = True):\n '''\n Input:\n word: the input string/word \n Output:\n edit_two_set: a set of strings with all possible two edits\n '''\n \n edit_two_set = set()\n \n ### START CODE HERE ###\n edit_one_set = edit_one_letter(word, allow_switches)\n for edited_word in edit_one_set:\n edit_two_set = edit_two_set.union(edit_one_letter(edited_word, allow_switches))\n ### END CODE HERE ###\n \n return edit_two_set", "_____no_output_____" ], [ "tmp_edit_two_set = edit_two_letters(\"a\")\ntmp_edit_two_l = sorted(list(tmp_edit_two_set))\nprint(f\"Number of strings with edit distance of two: {len(tmp_edit_two_l)}\")\nprint(f\"First 10 strings {tmp_edit_two_l[:10]}\")\nprint(f\"Last 10 strings {tmp_edit_two_l[-10:]}\")\nprint(f\"The data type of the returned object should be a set {type(tmp_edit_two_set)}\")\nprint(f\"Number of strings that are 2 edit distances from 'at' is {len(edit_two_letters('at'))}\")", "Number of strings with edit distance of two: 2654\nFirst 10 strings ['', 'a', 'aa', 'aaa', 'aab', 'aac', 'aad', 'aae', 'aaf', 'aag']\nLast 10 strings ['zv', 'zva', 'zw', 'zwa', 'zx', 'zxa', 'zy', 'zya', 'zz', 'zza']\nThe data type of the returned object should be a set <class 'set'>\nNumber of strings that are 2 edit distances from 'at' is 7154\n" ] ], [ [ "#### Expected Output\n\n```CPP\nNumber of strings with edit distance of two: 2654\nFirst 10 strings ['', 'a', 'aa', 'aaa', 'aab', 'aac', 'aad', 'aae', 'aaf', 'aag']\nLast 10 strings ['zv', 'zva', 'zw', 'zwa', 'zx', 'zxa', 'zy', 'zya', 'zz', 'zza']\nThe data type of the returned object should be a set <class 'set'>\nNumber of strings that are 2 edit distances from 'at' is 7154\n```", "_____no_output_____" ], [ "<a name='3-3'></a>\n## Part 3-3: suggest spelling suggestions\n\nNow you will use your `edit_two_letters` function to get a set of all the possible 2 edits on your word. You will then use those strings to get the most probable word you meant to type aka your typing suggestion.\n\n<a name='ex-10'></a>\n### Exercise 10\n**Instructions**: Implement `get_corrections`, which returns a list of zero to n possible suggestion tuples of the form (word, probability_of_word). \n\n**Step 1:** Generate suggestions for a supplied word: You'll use the edit functions you have developed. The 'suggestion algorithm' should follow this logic: \n* If the word is in the vocabulary, suggest the word. \n* Otherwise, if there are suggestions from `edit_one_letter` that are in the vocabulary, use those. \n* Otherwise, if there are suggestions from `edit_two_letters` that are in the vocabulary, use those. \n* Otherwise, suggest the input word.* \n* The idea is that words generated from fewer edits are more likely than words with more edits.\n\n\nNote: \n- Edits of one or two letters may 'restore' strings to either zero or one edit. This algorithm accounts for this by preferentially selecting lower distance edits first.", "_____no_output_____" ], [ "#### Short circuit\nIn Python, logical operations such as `and` and `or` have two useful properties. They can operate on lists and they have ['short-circuit' behavior](https://docs.python.org/3/library/stdtypes.html). Try these:", "_____no_output_____" ] ], [ [ "# example of logical operation on lists or sets\nprint( [] and [\"a\",\"b\"] )\nprint( [] or [\"a\",\"b\"] )\n#example of Short circuit behavior\nval1 = [\"Most\",\"Likely\"] or [\"Less\",\"so\"] or [\"least\",\"of\",\"all\"] # selects first, does not evalute remainder\nprint(val1)\nval2 = [] or [] or [\"least\",\"of\",\"all\"] # continues evaluation until there is a non-empty list\nprint(val2)", "[]\n['a', 'b']\n['Most', 'Likely']\n['least', 'of', 'all']\n" ] ], [ [ "The logical `or` could be used to implement the suggestion algorithm very compactly. Alternately, if/then constructs could be used.\n \n**Step 2**: Create a 'best_words' dictionary where the 'key' is a suggestion and the 'value' is the probability of that word in your vocabulary. If the word is not in the vocabulary, assign it a probability of 0.\n\n**Step 3**: Select the n best suggestions. There may be fewer than n.", "_____no_output_____" ], [ "<details> \n<summary>\n <font size=\"3\" color=\"darkgreen\"><b>Hints</b></font>\n</summary>\n<p>\n<ul>\n <li>edit_one_letter and edit_two_letters return *python sets*. </li>\n <li> Sets have a handy <a href=\"https://docs.python.org/2/library/sets.html\" > set.intersection </a> feature</li>\n <li>To find the keys that have the highest values in a dictionary, you can use the Counter dictionary to create a Counter object from a regular dictionary. Then you can use Counter.most_common(n) to get the n most common keys.\n </li>\n <li>To find the intersection of two sets, you can use set.intersection or the & operator.</li>\n <li>If you are not as familiar with short circuit syntax (as shown above), feel free to use if else statements instead.</li>\n <li>To use an if statement to check of a set is empty, use 'if not x:' syntax </li>\n</ul>\n</p>\n", "_____no_output_____" ] ], [ [ "# UNQ_C10 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# UNIT TEST COMMENT: Candidate for Table Driven Tests\n# GRADED FUNCTION: get_corrections\ndef get_corrections(word, probs, vocab, n=2, verbose = False):\n '''\n Input: \n word: a user entered string to check for suggestions\n probs: a dictionary that maps each word to its probability in the corpus\n vocab: a set containing all the vocabulary\n n: number of possible word corrections you want returned in the dictionary\n Output: \n n_best: a list of tuples with the most probable n corrected words and their probabilities.\n '''\n \n suggestions = []\n n_best = []\n \n ### START CODE HERE ###\n word_probs = {}\n \n if word in vocab:\n word_probs[word] = probs[word]\n \n if len(word_probs) == 0:\n one_edit_set = edit_one_letter(word, True)\n for edited_word in one_edit_set:\n if edited_word in vocab:\n word_probs[edited_word] = probs[edited_word]\n \n if len(word_probs) == 0:\n two_edits_set = edit_two_letters(word, True)\n for edited_word in two_edits_set:\n if edited_word in vocab:\n word_probs[edited_word] = probs[edited_word]\n \n n_best = Counter(word_probs).most_common(n)\n \n for best_word, prob in n_best:\n suggestions.append(best_word)\n ### END CODE HERE ###\n \n if verbose: print(\"entered word = \", word, \"\\nsuggestions = \", suggestions)\n\n return n_best", "_____no_output_____" ], [ "# Test your implementation - feel free to try other words in my word\nmy_word = 'dys' \ntmp_corrections = get_corrections(my_word, probs, vocab, 2, verbose=True) # keep verbose=True\nfor i, word_prob in enumerate(tmp_corrections):\n print(f\"word {i}: {word_prob[0]}, probability {word_prob[1]:.6f}\")\n\n# CODE REVIEW COMMENT: using \"tmp_corrections\" insteads of \"cors\". \"cors\" is not defined\nprint(f\"data type of corrections {type(tmp_corrections)}\")", "entered word = dys \nsuggestions = ['days', 'dye']\nword 0: days, probability 0.000410\nword 1: dye, probability 0.000019\ndata type of corrections <class 'list'>\n" ] ], [ [ "#### Expected Output\n- Note: This expected output is for `my_word = 'dys'`. Also, keep `verbose=True`\n```CPP\nentered word = dys \nsuggestions = {'days', 'dye'}\nword 0: days, probability 0.000410\nword 1: dye, probability 0.000019\ndata type of corrections <class 'list'>\n```", "_____no_output_____" ], [ "<a name='4'></a>\n# Part 4: Minimum Edit distance\n\nNow that you have implemented your auto-correct, how do you evaluate the similarity between two strings? For example: 'waht' and 'what'\n\nAlso how do you efficiently find the shortest path to go from the word, 'waht' to the word 'what'?\n\nYou will implement a dynamic programming system that will tell you the minimum number of edits required to convert a string into another string.", "_____no_output_____" ], [ "<a name='4-1'></a>\n### Part 4.1 Dynamic Programming\n\nDynamic Programming breaks a problem down into subproblems which can be combined to form the final solution. Here, given a string source[0..i] and a string target[0..j], we will compute all the combinations of substrings[i, j] and calculate their edit distance. To do this efficiently, we will use a table to maintain the previously computed substrings and use those to calculate larger substrings.\n\nYou have to create a matrix and update each element in the matrix as follows: ", "_____no_output_____" ], [ "$$\\text{Initialization}$$\n\n\\begin{align}\nD[0,0] &= 0 \\\\\nD[i,0] &= D[i-1,0] + del\\_cost(source[i]) \\tag{4}\\\\\nD[0,j] &= D[0,j-1] + ins\\_cost(target[j]) \\\\\n\\end{align}", "_____no_output_____" ], [ "\n$$\\text{Per Cell Operations}$$\n\\begin{align}\n \\\\\nD[i,j] =min\n\\begin{cases}\nD[i-1,j] + del\\_cost\\\\\nD[i,j-1] + ins\\_cost\\\\\nD[i-1,j-1] + \\left\\{\\begin{matrix}\nrep\\_cost; & if src[i]\\neq tar[j]\\\\\n0 ; & if src[i]=tar[j]\n\\end{matrix}\\right.\n\\end{cases}\n\\tag{5}\n\\end{align}", "_____no_output_____" ], [ "So converting the source word **play** to the target word **stay**, using an input cost of one, a delete cost of 1, and replace cost of 2 would give you the following table:\n<table style=\"width:20%\">\n\n <tr>\n <td> <b> </b> </td>\n <td> <b># </b> </td>\n <td> <b>s </b> </td>\n <td> <b>t </b> </td> \n <td> <b>a </b> </td> \n <td> <b>y </b> </td> \n </tr>\n <tr>\n <td> <b> # </b></td>\n <td> 0</td> \n <td> 1</td> \n <td> 2</td> \n <td> 3</td> \n <td> 4</td> \n \n </tr>\n <tr>\n <td> <b> p </b></td>\n <td> 1</td> \n <td> 2</td> \n <td> 3</td> \n <td> 4</td> \n <td> 5</td>\n </tr>\n \n <tr>\n <td> <b> l </b></td>\n <td>2</td> \n <td>3</td> \n <td>4</td> \n <td>5</td> \n <td>6</td>\n </tr>\n\n <tr>\n <td> <b> a </b></td>\n <td>3</td> \n <td>4</td> \n <td>5</td> \n <td>4</td>\n <td>5</td> \n </tr>\n \n <tr>\n <td> <b> y </b></td>\n <td>4</td> \n <td>5</td> \n <td>6</td> \n <td>5</td>\n <td>4</td> \n </tr>\n \n\n</table>\n\n", "_____no_output_____" ], [ "The operations used in this algorithm are 'insert', 'delete', and 'replace'. These correspond to the functions that you defined earlier: insert_letter(), delete_letter() and replace_letter(). switch_letter() is not used here.", "_____no_output_____" ], [ "The diagram below describes how to initialize the table. Each entry in D[i,j] represents the minimum cost of converting string source[0:i] to string target[0:j]. The first column is initialized to represent the cumulative cost of deleting the source characters to convert string \"EER\" to \"\". The first row is initialized to represent the cumulative cost of inserting the target characters to convert from \"\" to \"NEAR\".", "_____no_output_____" ], [ "<div style=\"width:image width px; font-size:100%; text-align:center;\"><img src='EditDistInit4.PNG' alt=\"alternate text\" width=\"width\" height=\"height\" style=\"width:1000px;height:400px;\"/> Figure 6 Initializing Distance Matrix</div> ", "_____no_output_____" ], [ "Filling in the remainder of the table utilizes the 'Per Cell Operations' in the equation (5) above. Note, the diagram below includes in the table some of the 3 sub-calculations shown in light grey. Only 'min' of those operations is stored in the table in the `min_edit_distance()` function.", "_____no_output_____" ], [ "<div style=\"width:image width px; font-size:100%; text-align:center;\"><img src='EditDistFill2.PNG' alt=\"alternate text\" width=\"width\" height=\"height\" style=\"width:800px;height:400px;\"/> Figure 7 Filling Distance Matrix</div> ", "_____no_output_____" ], [ "Note that the formula for $D[i,j]$ shown in the image is equivalent to:\n\n\\begin{align}\n \\\\\nD[i,j] =min\n\\begin{cases}\nD[i-1,j] + del\\_cost\\\\\nD[i,j-1] + ins\\_cost\\\\\nD[i-1,j-1] + \\left\\{\\begin{matrix}\nrep\\_cost; & if src[i]\\neq tar[j]\\\\\n0 ; & if src[i]=tar[j]\n\\end{matrix}\\right.\n\\end{cases}\n\\tag{5}\n\\end{align}\n\nThe variable `sub_cost` (for substitution cost) is the same as `rep_cost`; replacement cost. We will stick with the term \"replace\" whenever possible.", "_____no_output_____" ], [ "Below are some examples of cells where replacement is used. This also shows the minimum path from the lower right final position where \"EER\" has been replaced by \"NEAR\" back to the start. This provides a starting point for the optional 'backtrace' algorithm below.", "_____no_output_____" ], [ "<div style=\"width:image width px; font-size:100%; text-align:center;\"><img src='EditDistExample1.PNG' alt=\"alternate text\" width=\"width\" height=\"height\" style=\"width:1200px;height:400px;\"/> Figure 8 Examples Distance Matrix</div> ", "_____no_output_____" ], [ "<a name='ex-11'></a>\n### Exercise 11\n\nAgain, the word \"substitution\" appears in the figure, but think of this as \"replacement\".", "_____no_output_____" ], [ "**Instructions**: Implement the function below to get the minimum amount of edits required given a source string and a target string. ", "_____no_output_____" ], [ "<details> \n<summary>\n <font size=\"3\" color=\"darkgreen\"><b>Hints</b></font>\n</summary>\n<p>\n<ul>\n <li>The range(start, stop, step) function excludes 'stop' from its output</li>\n <li><a href=\"\" > words </a> </li>\n</ul>\n</p>\n", "_____no_output_____" ] ], [ [ "# UNQ_C11 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: min_edit_distance\ndef min_edit_distance(source, target, ins_cost = 1, del_cost = 1, rep_cost = 2):\n '''\n Input: \n source: a string corresponding to the string you are starting with\n target: a string corresponding to the string you want to end with\n ins_cost: an integer setting the insert cost\n del_cost: an integer setting the delete cost\n rep_cost: an integer setting the replace cost\n Output:\n D: a matrix of len(source)+1 by len(target)+1 containing minimum edit distances\n med: the minimum edit distance (med) required to convert the source string to the target\n '''\n # use deletion and insert cost as 1\n m = len(source) \n n = len(target) \n #initialize cost matrix with zeros and dimensions (m+1,n+1) \n D = np.zeros((m+1, n+1), dtype=int) \n \n ### START CODE HERE (Replace instances of 'None' with your code) ###\n \n # Fill in column 0, from row 1 to row m, both inclusive\n for row in range(1,m+1): # Replace None with the proper range\n D[row,0] = row\n \n # Fill in row 0, for all columns from 1 to n, both inclusive\n for col in range(1,n+1): # Replace None with the proper range\n D[0,col] = col\n \n # Loop through row 1 to row m, both inclusive\n for row in range(1,m+1): \n \n # Loop through column 1 to column n, both inclusive\n for col in range(1,n+1):\n \n # Intialize r_cost to the 'replace' cost that is passed into this function\n r_cost = rep_cost\n \n # Check to see if source character at the previous row\n # matches the target character at the previous column, \n if source[row-1] == target[col-1]:\n # Update the replacement cost to 0 if source and target are the same\n r_cost = 0\n \n # Update the cost at row, col based on previous entries in the cost matrix\n # Refer to the equation calculate for D[i,j] (the minimum of three calculated costs)\n D[row,col] = min((D[row-1, col] + del_cost), (D[row, col-1] + ins_cost), (D[row-1,col-1] + r_cost))\n \n # Set the minimum edit distance with the cost found at row m, column n\n med = D[m,n]\n \n ### END CODE HERE ###\n return D, med", "_____no_output_____" ], [ "#DO NOT MODIFY THIS CELL\n# testing your implementation \nsource = 'play'\ntarget = 'stay'\nmatrix, min_edits = min_edit_distance(source, target)\nprint(\"minimum edits: \",min_edits, \"\\n\")\nidx = list('#' + source)\ncols = list('#' + target)\ndf = pd.DataFrame(matrix, index=idx, columns= cols)\nprint(df)", "minimum edits: 4 \n\n # s t a y\n# 0 1 2 3 4\np 1 2 3 4 5\nl 2 3 4 5 6\na 3 4 5 4 5\ny 4 5 6 5 4\n" ] ], [ [ "**Expected Results:** \n\n```CPP\nminimum edits: 4\n \n # s t a y\n# 0 1 2 3 4\np 1 2 3 4 5\nl 2 3 4 5 6\na 3 4 5 4 5\ny 4 5 6 5 4\n```", "_____no_output_____" ] ], [ [ "#DO NOT MODIFY THIS CELL\n# testing your implementation \nsource = 'eer'\ntarget = 'near'\nmatrix, min_edits = min_edit_distance(source, target)\nprint(\"minimum edits: \",min_edits, \"\\n\")\nidx = list(source)\nidx.insert(0, '#')\ncols = list(target)\ncols.insert(0, '#')\ndf = pd.DataFrame(matrix, index=idx, columns= cols)\nprint(df)", "minimum edits: 3 \n\n # n e a r\n# 0 1 2 3 4\ne 1 2 1 2 3\ne 2 3 2 3 4\nr 3 4 3 4 3\n" ] ], [ [ "**Expected Results** \n```CPP\nminimum edits: 3 \n\n # n e a r\n# 0 1 2 3 4\ne 1 2 1 2 3\ne 2 3 2 3 4\nr 3 4 3 4 3\n```", "_____no_output_____" ], [ "We can now test several of our routines at once:", "_____no_output_____" ] ], [ [ "source = \"eer\"\ntargets = edit_one_letter(source,allow_switches = False) #disable switches since min_edit_distance does not include them\nfor t in targets:\n _, min_edits = min_edit_distance(source, t,1,1,1) # set ins, del, sub costs all to one\n if min_edits != 1: print(source, t, min_edits)", "_____no_output_____" ] ], [ [ "**Expected Results** \n```CPP\n(empty)\n```\n\nThe 'replace()' routine utilizes all letters a-z one of which returns the original word.", "_____no_output_____" ] ], [ [ "source = \"eer\"\ntargets = edit_two_letters(source,allow_switches = False) #disable switches since min_edit_distance does not include them\nfor t in targets:\n _, min_edits = min_edit_distance(source, t,1,1,1) # set ins, del, sub costs all to one\n if min_edits != 2 and min_edits != 1: print(source, t, min_edits)", "eer eer 0\n" ] ], [ [ "**Expected Results** \n```CPP\neer eer 0\n```\n\nWe have to allow single edits here because some two_edits will restore a single edit.", "_____no_output_____" ], [ "# Submission\nMake sure you submit your assignment before you modify anything below\n", "_____no_output_____" ], [ "<a name='5'></a>\n\n# Part 5: Optional - Backtrace\n\n\nOnce you have computed your matrix using minimum edit distance, how would find the shortest path from the top left corner to the bottom right corner? \n\nNote that you could use backtrace algorithm. Try to find the shortest path given the matrix that your `min_edit_distance` function returned.\n\nYou can use these [lecture slides on minimum edit distance](https://web.stanford.edu/class/cs124/lec/med.pdf) by Dan Jurafsky to learn about the algorithm for backtrace.", "_____no_output_____" ] ], [ [ "# Experiment with back trace - insert your code here\n\n", "_____no_output_____" ] ], [ [ "#### References\n- Dan Jurafsky - Speech and Language Processing - Textbook\n- This auto-correct explanation was first done by Peter Norvig in 2007 ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
4a52408a1ea835f0d7efc9e2616397bcac737509
46,832
ipynb
Jupyter Notebook
sprint2_classification/sprint2_hands_on.ipynb
maliaca/ML_sprint
c1018dee7a27a879eb5c04990a078bd7db3eb808
[ "MIT" ]
1
2020-04-24T18:57:06.000Z
2020-04-24T18:57:06.000Z
sprint2_classification/sprint2_hands_on.ipynb
maliaca/ML_sprint
c1018dee7a27a879eb5c04990a078bd7db3eb808
[ "MIT" ]
null
null
null
sprint2_classification/sprint2_hands_on.ipynb
maliaca/ML_sprint
c1018dee7a27a879eb5c04990a078bd7db3eb808
[ "MIT" ]
1
2020-04-24T18:57:18.000Z
2020-04-24T18:57:18.000Z
40.407248
14,876
0.574244
[ [ [ "import pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.model_selection import train_test_split \nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\n#from sklearn.metrics import precision_recall_curve\n#from sklearn.metrics import plot_precision_recall_curve\nfrom sklearn.metrics import average_precision_score\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ] ], [ [ "# demonstration of vectorizer in Scikit learn", "_____no_output_____" ] ], [ [ "# word counts\n\n# list of text documents\ntext_test = [\"This is a test document\",\"this is a second text\",\"and here is a third text\", \"this is a dum text!\"]\n# create the transform\nvectorizer_test = CountVectorizer()\n# tokenize and build vocab\nvectorizer_test.fit(text_test)\n# summarize\nprint(vectorizer_test.vocabulary_)\n# encode document\nvector_test = vectorizer_test.transform(text_test)\n# show encoded vector\nprint(vector_test.toarray())", "{'this': 9, 'is': 4, 'test': 6, 'document': 1, 'second': 5, 'text': 7, 'and': 0, 'here': 3, 'third': 8, 'dum': 2}\n[[0 1 0 0 1 0 1 0 0 1]\n [0 0 0 0 1 1 0 1 0 1]\n [1 0 0 1 1 0 0 1 1 0]\n [0 0 1 0 1 0 0 1 0 1]]\n" ] ], [ [ "# Spam/Ham dataset", "_____no_output_____" ] ], [ [ "# import data from TSV\nsms_data=pd.read_csv('SMSSpamCollection.txt', sep='\\t')\nsms_data.head()", "_____no_output_____" ], [ "# create a new column with inferred class\ndef f(row):\n if row['Label'] == \"ham\":\n val = 1\n else:\n val = 0\n return val\n\n\nsms_data['Class'] = sms_data.apply(f, axis=1)\nsms_data.head()", "_____no_output_____" ], [ "vectorizer = CountVectorizer(\n analyzer = 'word',\n lowercase = True,\n)\nfeatures = vectorizer.fit_transform(\n sms_data['Text']\n)", "_____no_output_____" ], [ "# split X and Y\nX = features.toarray()\nY= sms_data['Class']", "_____no_output_____" ], [ "# split training and testing\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y,test_size=0.20, random_state=1)", "_____no_output_____" ], [ "log_model = LogisticRegression(penalty='l2', solver='lbfgs', class_weight='balanced')\nlog_model = log_model.fit(X_train, Y_train)", "_____no_output_____" ], [ "# make predictions\nY_pred = log_model.predict(X_test)\n\n# make predictions\npred_df = pd.DataFrame({'Actual': Y_test, 'Predicted': Y_pred.flatten()})\npred_df.head()", "_____no_output_____" ], [ "# compute accuracy of the spam filter\nprint(accuracy_score(Y_test, Y_pred))", "0.9901345291479821\n" ], [ "# compute precision and recall\naverage_precision = average_precision_score(Y_test, Y_pred)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n average_precision))", "Average precision-recall score: 0.99\n" ], [ "# precision-recall curve\ndisp = plot_precision_recall_curve(log_model, X_test, Y_test)\ndisp.ax_.set_title('2-class Precision-Recall curve: '\n 'AP={0:0.2f}'.format(average_precision))", "_____no_output_____" ], [ "# look at the words learnt and their coefficients\ncoeff_df = pd.DataFrame({'coeffs': log_model.coef_.flatten(), 'Words': vectorizer.get_feature_names()}, ) \n# Words with highest coefficients -> predictive of 'Ham'\ncoeff_df.nlargest(10, 'coeffs') ", "_____no_output_____" ], [ "# Words with highest coefficients -> predictive of 'Spam'\ncoeff_df.nsmallest(10, 'coeffs') ", "_____no_output_____" ] ], [ [ "# Upload review dataset", "_____no_output_____" ] ], [ [ "# import data from TSV\nrev_data=pd.read_csv('book_reviews.csv')\nrev_data.head()", "_____no_output_____" ], [ "# fix issues with format text\nreviews = rev_data['reviewText'].apply(lambda x: np.str_(x))", "_____no_output_____" ], [ "# create a new column with inferred class\n", "_____no_output_____" ], [ "# count words in texts", "_____no_output_____" ], [ "# split X and Y\n", "_____no_output_____" ], [ "# split training and testing\n", "_____no_output_____" ], [ "# fit model (this takes a while)\n", "_____no_output_____" ], [ "# make predictions\n", "_____no_output_____" ], [ "# compute accuracy of the sentiment analysis\n", "_____no_output_____" ], [ "# compute precision and recall", "_____no_output_____" ], [ "# precision-recall curve\n", "_____no_output_____" ], [ "# look at the words learnt and their coefficients\ncoeff_df = pd.DataFrame({'coeffs': log_model.coef_.flatten(), 'Words': vectorizer.get_feature_names()}, ) \n# Words with highest coefficients -> predictive of 'good reviews'\ncoeff_df.nlargest(10, 'coeffs') ", "_____no_output_____" ], [ "# Words with highest coefficients -> predictive of 'bad reviews'\ncoeff_df.nsmallest(10, 'coeffs') ", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a52420e2ae6aa8e049fecf146f2ad132e6f6a09
69,349
ipynb
Jupyter Notebook
Simple Generative Adversarial Network Demo.ipynb
udibr/GAN
6e8f74d081b2cb54197df02a28ad70611e126d42
[ "MIT" ]
null
null
null
Simple Generative Adversarial Network Demo.ipynb
udibr/GAN
6e8f74d081b2cb54197df02a28ad70611e126d42
[ "MIT" ]
null
null
null
Simple Generative Adversarial Network Demo.ipynb
udibr/GAN
6e8f74d081b2cb54197df02a28ad70611e126d42
[ "MIT" ]
null
null
null
200.430636
30,308
0.89847
[ [ [ "http://arxiv.org/pdf/1406.2661v1.pdf ...we simultaneously train two models: a generative model $G$\nthat captures the data distribution, and a discriminative model $D$ that estimates\nthe probability that a sample came from the training data rather than $G$. The training\nprocedure for $G$ is to maximize the probability of $D$ making a mistake...\nwe define a prior on input noise variables $p_z(z)$...\nwe simultaneously train G to minimize\n$\\log(1 − D(G(z)))$...", "_____no_output_____" ], [ "original code from https://gist.github.com/Newmu/4ee0a712454480df5ee3", "_____no_output_____" ], [ "You will need to install Foxhound:\n```bash\ngit clone https://github.com/IndicoDataSolutions/Foxhound.git\ncd Foxhound/\npython setup.py install\n```", "_____no_output_____" ] ], [ [ "%matplotlib inline", "_____no_output_____" ], [ "import os\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom time import time\nimport theano\nimport theano.tensor as T\n \nfrom scipy.stats import gaussian_kde\nfrom scipy.misc import imsave, imread", "Couldn't import dot_parser, loading of dot files will not be possible.\n" ], [ "from foxhound import activations\nfrom foxhound import updates\nfrom foxhound import inits\nfrom foxhound.theano_utils import floatX, sharedX", "_____no_output_____" ], [ "leakyrectify = activations.LeakyRectify()\nrectify = activations.Rectify()\ntanh = activations.Tanh()\nsigmoid = activations.Sigmoid()\nbce = T.nnet.binary_crossentropy\nbatch_size = 128\nnh = 2048\ninit_fn = inits.Normal(scale=0.02)", "_____no_output_____" ], [ "def gaussian_likelihood(X, u=0., s=1.):\n return (1./(s*np.sqrt(2*np.pi)))*np.exp(-(((X - u)**2)/(2*s**2)))\n \ndef scale_and_shift(X, g, b, e=1e-8):\n X = X*g + b\n return X", "_____no_output_____" ] ], [ [ "build two networks", "_____no_output_____" ] ], [ [ "def g(X, w, g, b, w2, g2, b2, wo):\n h = leakyrectify(scale_and_shift(T.dot(X, w), g, b))\n h2 = leakyrectify(scale_and_shift(T.dot(h, w2), g2, b2))\n y = T.dot(h2, wo)\n return y\n \ndef d(X, w, g, b, w2, g2, b2, wo):\n h = rectify(scale_and_shift(T.dot(X, w), g, b))\n h2 = tanh(scale_and_shift(T.dot(h, w2), g2, b2))\n y = sigmoid(T.dot(h2, wo))\n return y", "_____no_output_____" ], [ "gw = init_fn((1, nh))\ngg = inits.Constant(1.)(nh)\ngg = inits.Normal(1., 0.02)(nh)\ngb = inits.Normal(0., 0.02)(nh)\n \ngw2 = init_fn((nh, nh))\ngg2 = inits.Normal(1., 0.02)(nh)\ngb2 = inits.Normal(0., 0.02)(nh)\n \ngy = init_fn((nh, 1))\nggy = inits.Constant(1.)(1)\ngby = inits.Normal(0., 0.02)(1)\n \ndw = init_fn((1, nh))\ndg = inits.Normal(1., 0.02)(nh)\ndb = inits.Normal(0., 0.02)(nh)\n \ndw2 = init_fn((nh, nh))\ndg2 = inits.Normal(1., 0.02)(nh)\ndb2 = inits.Normal(0., 0.02)(nh)\n \ndy = init_fn((nh, 1))\ndgy = inits.Normal(1., 0.02)(1)\ndby = inits.Normal(0., 0.02)(1)\n \ng_params = [gw, gg, gb, gw2, gg2, gb2, gy]\nd_params = [dw, dg, db, dw2, dg2, db2, dy]", "_____no_output_____" ], [ "Z = T.matrix()\nX = T.matrix()\n \ngen = g(Z, *g_params)\n \np_real = d(X, *d_params)\np_gen = d(gen, *d_params)\n \nd_cost_real = bce(p_real, T.ones(p_real.shape)).mean()\nd_cost_gen = bce(p_gen, T.zeros(p_gen.shape)).mean()\ng_cost_d = bce(p_gen, T.ones(p_gen.shape)).mean()\n \nd_cost = d_cost_real + d_cost_gen\ng_cost = g_cost_d\n \ncost = [g_cost, d_cost, d_cost_real, d_cost_gen]", "_____no_output_____" ], [ "lr = 0.001\nlrt = sharedX(lr)\nd_updater = updates.Adam(lr=lrt)\ng_updater = updates.Adam(lr=lrt)\n \nd_updates = d_updater(d_params, d_cost)\ng_updates = g_updater(g_params, g_cost)\nupdates = d_updates + g_updates\n \n_train_g = theano.function([X, Z], cost, updates=g_updates)\n_train_d = theano.function([X, Z], cost, updates=d_updates)\n_train_both = theano.function([X, Z], cost, updates=updates)\n_gen = theano.function([Z], gen)\n_score = theano.function([X], p_real)\n_cost = theano.function([X, Z], cost)", "_____no_output_____" ], [ "from IPython import display\n\ndef vis(i):\n s = 1.\n u = 0.\n zs = np.linspace(-1, 1, 500).astype('float32')\n xs = np.linspace(-5, 5, 500).astype('float32')\n ps = gaussian_likelihood(xs, 1.)\n \n gs = _gen(zs.reshape(-1, 1)).flatten()\n preal = _score(xs.reshape(-1, 1)).flatten()\n kde = gaussian_kde(gs)\n \n plt.clf()\n plt.plot(xs, ps, '--', lw=2)\n plt.plot(xs, kde(xs), lw=2)\n plt.plot(xs, preal, lw=2)\n plt.xlim([-5., 5.])\n plt.ylim([0., 1.])\n plt.ylabel('Prob')\n plt.xlabel('x')\n plt.legend(['P(data)', 'G(z)', 'D(x)'])\n plt.title('GAN learning guassian %d'%i)\n \n display.clear_output(wait=True)\n display.display(plt.gcf())", "_____no_output_____" ], [ "for i in range(1000):\n # the prior over the input noise\n zmb = np.random.uniform(-1, 1, size=(batch_size, 1)).astype('float32')\n xmb = np.random.normal(1., 1, size=(batch_size, 1)).astype('float32')\n if i % 10 == 0:\n # you dont really use xmb in training G\n _train_g(xmb, zmb)\n else:\n _train_d(xmb, zmb)\n if i % 10 == 0:\n vis(i)\n lrt.set_value(floatX(lrt.get_value()*0.9999))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
4a52548ceaa944f9271afba94bc3262495cb63ba
1,635
ipynb
Jupyter Notebook
Generators.ipynb
SriVinayA/FCS-Python
d6121153b4650e046f54bd3790056f0cc8fed99e
[ "MIT" ]
null
null
null
Generators.ipynb
SriVinayA/FCS-Python
d6121153b4650e046f54bd3790056f0cc8fed99e
[ "MIT" ]
null
null
null
Generators.ipynb
SriVinayA/FCS-Python
d6121153b4650e046f54bd3790056f0cc8fed99e
[ "MIT" ]
null
null
null
16.35
51
0.442202
[ [ [ "# Generators", "_____no_output_____" ] ], [ [ "#Generator function\n\ndef gencubes(n):\n for num in range(n):\n yield num**3", "_____no_output_____" ], [ "list(gencubes(10))", "_____no_output_____" ], [ "for x in gencubes(10):\n print(x)", "0\n1\n8\n27\n64\n125\n216\n343\n512\n729\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ] ]
4a527d06342debfc89ad2351fdce6f538b9ac702
1,167
ipynb
Jupyter Notebook
notebooks/kotlin.ipynb
tabito-htnet-org/jupyter-langs
049cf8aa196c7011172b18cb642472c4e2d36d0e
[ "MIT" ]
null
null
null
notebooks/kotlin.ipynb
tabito-htnet-org/jupyter-langs
049cf8aa196c7011172b18cb642472c4e2d36d0e
[ "MIT" ]
null
null
null
notebooks/kotlin.ipynb
tabito-htnet-org/jupyter-langs
049cf8aa196c7011172b18cb642472c4e2d36d0e
[ "MIT" ]
null
null
null
16.43662
39
0.46958
[ [ [ "KotlinVersion.CURRENT", "_____no_output_____" ], [ "fun helloWorld() {\n println(\"Hello, World!\")\n}\nhelloWorld()", "Hello, World!\n" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
4a5286843a5f761bd44cb2e703e5f3a95e719968
114,426
ipynb
Jupyter Notebook
conditional/.ipynb_checkpoints/main_conditional_disentangle_cifar_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_rlw_1_0_run1-checkpoint.ipynb
minhtannguyen/ffjord
f3418249eaa4647f4339aea8d814cf2ce33be141
[ "MIT" ]
null
null
null
conditional/.ipynb_checkpoints/main_conditional_disentangle_cifar_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_rlw_1_0_run1-checkpoint.ipynb
minhtannguyen/ffjord
f3418249eaa4647f4339aea8d814cf2ce33be141
[ "MIT" ]
null
null
null
conditional/.ipynb_checkpoints/main_conditional_disentangle_cifar_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_rlw_1_0_run1-checkpoint.ipynb
minhtannguyen/ffjord
f3418249eaa4647f4339aea8d814cf2ce33be141
[ "MIT" ]
null
null
null
69.559878
1,269
0.503033
[ [ [ "import os\nos.environ['CUDA_VISIBLE_DEVICES']='4,5,6,7'", "_____no_output_____" ], [ "%run -p ../train_cnf_disentangle_rl.py --data cifar10 --dims 64,64,64 --strides 1,1,1,1 --num_blocks 2 --layer_type concat --multiscale True --rademacher True --batch_size 900 --test_batch_size 500 --save ../experiments_published/cnf_conditional_disentangle_cifar10_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_rlw_0_1_run1 --seed 1 --lr 0.001 --conditional True --controlled_tol False --train_mode semisup --log_freq 10 --weight_y 0.5 --condition_ratio 0.5 --dropout_rate 0.5 --scale_fac 1.0 --scale_std 6.0 --rl-weight 0.1\n#", "/tancode/repos/tan-ffjord/train_cnf_disentangle_rl.py\nimport argparse\nimport os\nimport time\nimport numpy as np\n\nimport torch\nimport torch.optim as optim\nimport torchvision.datasets as dset\nimport torchvision.transforms as tforms\nfrom torchvision.utils import save_image\n\nimport lib.layers as layers\nimport lib.utils as utils\nimport lib.multiscale_parallel as multiscale_parallel\nimport lib.modules as modules\nimport lib.thops as thops\n\nfrom train_misc import standard_normal_logprob\nfrom train_misc import set_cnf_options, count_nfe, count_parameters, count_total_time\nfrom train_misc import add_spectral_norm, spectral_norm_power_iteration\nfrom train_misc import create_regularization_fns, get_regularization, append_regularization_to_log\n\nfrom tensorboardX import SummaryWriter\n\n# go fast boi!!\ntorch.backends.cudnn.benchmark = True\nSOLVERS = [\"dopri5\", \"bdf\", \"rk4\", \"midpoint\", 'adams', 'explicit_adams']\nGATES = [\"cnn1\", \"cnn2\", \"rnn\"]\n\nparser = argparse.ArgumentParser(\"Continuous Normalizing Flow\")\nparser.add_argument(\"--data\", choices=[\"mnist\", \"svhn\", \"cifar10\", 'lsun_church'], type=str, default=\"mnist\")\nparser.add_argument(\"--dims\", type=str, default=\"8,32,32,8\")\nparser.add_argument(\"--strides\", type=str, default=\"2,2,1,-2,-2\")\nparser.add_argument(\"--num_blocks\", type=int, default=1, help='Number of stacked CNFs.')\n\nparser.add_argument(\"--conv\", type=eval, default=True, choices=[True, False])\nparser.add_argument(\n \"--layer_type\", type=str, default=\"ignore\",\n choices=[\"ignore\", \"concat\", \"concat_v2\", \"squash\", \"concatsquash\", \"concatcoord\", \"hyper\", \"blend\"]\n)\nparser.add_argument(\"--divergence_fn\", type=str, default=\"approximate\", choices=[\"brute_force\", \"approximate\"])\nparser.add_argument(\n \"--nonlinearity\", type=str, default=\"softplus\", choices=[\"tanh\", \"relu\", \"softplus\", \"elu\", \"swish\"]\n)\n\nparser.add_argument(\"--seed\", type=int, default=0)\n\nparser.add_argument('--solver', type=str, default='dopri5', choices=SOLVERS)\nparser.add_argument('--atol', type=float, default=1e-5)\nparser.add_argument('--rtol', type=float, default=1e-5)\nparser.add_argument(\"--step_size\", type=float, default=None, help=\"Optional fixed step size.\")\n\nparser.add_argument('--gate', type=str, default='cnn1', choices=GATES)\nparser.add_argument('--scale', type=float, default=1.0)\nparser.add_argument('--scale_fac', type=float, default=1.0)\nparser.add_argument('--scale_std', type=float, default=1.0)\nparser.add_argument('--eta', default=0.1, type=float,\n help='tuning parameter that allows us to trade-off the competing goals of' \n 'minimizing the prediction loss and maximizing the gate rewards ')\nparser.add_argument('--rl-weight', default=0.01, type=float,\n help='rl weight')\n\nparser.add_argument('--gamma', default=0.99, type=float,\n help='discount factor, default: (0.99)')\n\nparser.add_argument('--test_solver', type=str, default=None, choices=SOLVERS + [None])\nparser.add_argument('--test_atol', type=float, default=None)\nparser.add_argument('--test_rtol', type=float, default=None)\n\nparser.add_argument(\"--imagesize\", type=int, default=None)\nparser.add_argument(\"--alpha\", type=float, default=1e-6)\nparser.add_argument('--time_length', type=float, default=1.0)\nparser.add_argument('--train_T', type=eval, default=True)\n\nparser.add_argument(\"--num_epochs\", type=int, default=1000)\nparser.add_argument(\"--batch_size\", type=int, default=200)\nparser.add_argument(\n \"--batch_size_schedule\", type=str, default=\"\", help=\"Increases the batchsize at every given epoch, dash separated.\"\n)\nparser.add_argument(\"--test_batch_size\", type=int, default=200)\nparser.add_argument(\"--lr\", type=float, default=1e-3)\nparser.add_argument(\"--warmup_iters\", type=float, default=1000)\nparser.add_argument(\"--weight_decay\", type=float, default=0.0)\nparser.add_argument(\"--spectral_norm_niter\", type=int, default=10)\nparser.add_argument(\"--weight_y\", type=float, default=0.5)\n\nparser.add_argument(\"--add_noise\", type=eval, default=True, choices=[True, False])\nparser.add_argument(\"--batch_norm\", type=eval, default=False, choices=[True, False])\nparser.add_argument('--residual', type=eval, default=False, choices=[True, False])\nparser.add_argument('--autoencode', type=eval, default=False, choices=[True, False])\nparser.add_argument('--rademacher', type=eval, default=True, choices=[True, False])\nparser.add_argument('--spectral_norm', type=eval, default=False, choices=[True, False])\nparser.add_argument('--multiscale', type=eval, default=False, choices=[True, False])\nparser.add_argument('--parallel', type=eval, default=False, choices=[True, False])\nparser.add_argument('--conditional', type=eval, default=False, choices=[True, False])\nparser.add_argument('--controlled_tol', type=eval, default=False, choices=[True, False])\nparser.add_argument(\"--train_mode\", choices=[\"semisup\", \"sup\", \"unsup\"], type=str, default=\"semisup\")\nparser.add_argument(\"--condition_ratio\", type=float, default=0.5)\nparser.add_argument(\"--dropout_rate\", type=float, default=0.0)\n\n\n# Regularizations\nparser.add_argument('--l1int', type=float, default=None, help=\"int_t ||f||_1\")\nparser.add_argument('--l2int', type=float, default=None, help=\"int_t ||f||_2\")\nparser.add_argument('--dl2int', type=float, default=None, help=\"int_t ||f^T df/dt||_2\")\nparser.add_argument('--JFrobint', type=float, default=None, help=\"int_t ||df/dx||_F\")\nparser.add_argument('--JdiagFrobint', type=float, default=None, help=\"int_t ||df_i/dx_i||_F\")\nparser.add_argument('--JoffdiagFrobint', type=float, default=None, help=\"int_t ||df/dx - df_i/dx_i||_F\")\n\nparser.add_argument(\"--time_penalty\", type=float, default=0, help=\"Regularization on the end_time.\")\nparser.add_argument(\n \"--max_grad_norm\", type=float, default=1e10,\n help=\"Max norm of graidents (default is just stupidly high to avoid any clipping)\"\n)\n\nparser.add_argument(\"--begin_epoch\", type=int, default=1)\nparser.add_argument(\"--resume\", type=str, default=None)\nparser.add_argument(\"--save\", type=str, default=\"experiments/cnf\")\nparser.add_argument(\"--val_freq\", type=int, default=1)\nparser.add_argument(\"--log_freq\", type=int, default=1)\n\nargs = parser.parse_args()\n\nimport lib.odenvp_conditional_rl as odenvp\n \n# set seed\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\n\n# logger\nutils.makedirs(args.save)\nlogger = utils.get_logger(logpath=os.path.join(args.save, 'logs'), filepath=os.path.abspath(__file__)) # write to log file\nwriter = SummaryWriter(os.path.join(args.save, 'tensorboard')) # write to tensorboard\n\nif args.layer_type == \"blend\":\n logger.info(\"!! Setting time_length from None to 1.0 due to use of Blend layers.\")\n args.time_length = 1.0\n\nlogger.info(args)\n\n\ndef add_noise(x):\n \"\"\"\n [0, 1] -> [0, 255] -> add noise -> [0, 1]\n \"\"\"\n if args.add_noise:\n noise = x.new().resize_as_(x).uniform_()\n x = x * 255 + noise\n x = x / 256\n return x\n\n\ndef update_lr(optimizer, itr):\n iter_frac = min(float(itr + 1) / max(args.warmup_iters, 1), 1.0)\n lr = args.lr * iter_frac\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = lr\n\n\ndef get_train_loader(train_set, epoch):\n if args.batch_size_schedule != \"\":\n epochs = [0] + list(map(int, args.batch_size_schedule.split(\"-\")))\n n_passed = sum(np.array(epochs) <= epoch)\n current_batch_size = int(args.batch_size * n_passed)\n else:\n current_batch_size = args.batch_size\n train_loader = torch.utils.data.DataLoader(\n dataset=train_set, batch_size=current_batch_size, shuffle=True, drop_last=True, pin_memory=True\n )\n logger.info(\"===> Using batch size {}. Total {} iterations/epoch.\".format(current_batch_size, len(train_loader)))\n return train_loader\n\n\ndef get_dataset(args):\n trans = lambda im_size: tforms.Compose([tforms.Resize(im_size), tforms.ToTensor(), add_noise])\n\n if args.data == \"mnist\":\n im_dim = 1\n im_size = 28 if args.imagesize is None else args.imagesize\n train_set = dset.MNIST(root=\"../data\", train=True, transform=trans(im_size), download=True)\n test_set = dset.MNIST(root=\"../data\", train=False, transform=trans(im_size), download=True)\n elif args.data == \"svhn\":\n im_dim = 3\n im_size = 32 if args.imagesize is None else args.imagesize\n train_set = dset.SVHN(root=\"../data\", split=\"train\", transform=trans(im_size), download=True)\n test_set = dset.SVHN(root=\"../data\", split=\"test\", transform=trans(im_size), download=True)\n elif args.data == \"cifar10\":\n im_dim = 3\n im_size = 32 if args.imagesize is None else args.imagesize\n train_set = dset.CIFAR10(\n root=\"../data\", train=True, transform=tforms.Compose([\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ]), download=True\n )\n test_set = dset.CIFAR10(root=\"../data\", train=False, transform=trans(im_size), download=True)\n elif args.data == 'celeba':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.CelebA(\n train=True, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.CelebA(\n train=False, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n elif args.data == 'lsun_church':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.LSUN(\n '../data', ['church_outdoor_train'], transform=tforms.Compose([\n tforms.Resize(96),\n tforms.RandomCrop(64),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.LSUN(\n '../data', ['church_outdoor_val'], transform=tforms.Compose([\n tforms.Resize(96),\n tforms.RandomCrop(64),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n ) \n elif args.data == 'imagenet_64':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.ImageFolder(\n train=True, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.ImageFolder(\n train=False, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n \n data_shape = (im_dim, im_size, im_size)\n if not args.conv:\n data_shape = (im_dim * im_size * im_size,)\n\n test_loader = torch.utils.data.DataLoader(\n dataset=test_set, batch_size=args.test_batch_size, shuffle=False, drop_last=True\n )\n return train_set, test_loader, data_shape\n\n\ndef compute_bits_per_dim(x, model):\n zero = torch.zeros(x.shape[0], 1).to(x)\n\n # Don't use data parallelize if batch size is small.\n # if x.shape[0] < 200:\n # model = model.module\n \n z, delta_logp, atol, rtol, logp_actions, nfe = model(x, zero) # run model forward\n\n logpz = standard_normal_logprob(z).view(z.shape[0], -1).sum(1, keepdim=True) # logp(z)\n logpx = logpz - delta_logp\n\n logpx_per_dim = torch.sum(logpx) / x.nelement() # averaged over batches\n bits_per_dim = -(logpx_per_dim - np.log(256)) / np.log(2)\n\n return bits_per_dim, atol, rtol, logp_actions, nfe\n\ndef compute_bits_per_dim_conditional(x, y, model):\n zero = torch.zeros(x.shape[0], 1).to(x)\n y_onehot = thops.onehot(y, num_classes=model.module.y_class).to(x)\n\n # Don't use data parallelize if batch size is small.\n # if x.shape[0] < 200:\n # model = model.module\n \n z, delta_logp, atol, rtol, logp_actions, nfe = model(x, zero) # run model forward\n \n dim_sup = int(args.condition_ratio * np.prod(z.size()[1:]))\n \n # prior\n mean, logs = model.module._prior(y_onehot)\n\n logpz_sup = modules.GaussianDiag.logp(mean, logs, z[:, 0:dim_sup]).view(-1,1) # logp(z)_sup\n logpz_unsup = standard_normal_logprob(z[:, dim_sup:]).view(z.shape[0], -1).sum(1, keepdim=True)\n logpz = logpz_sup + logpz_unsup\n logpx = logpz - delta_logp\n\n logpx_per_dim = torch.sum(logpx) / x.nelement() # averaged over batches\n bits_per_dim = -(logpx_per_dim - np.log(256)) / np.log(2)\n \n # dropout\n if args.dropout_rate > 0:\n zsup = model.module.dropout(z[:, 0:dim_sup])\n else:\n zsup = z[:, 0:dim_sup]\n \n # compute xentropy loss\n y_logits = model.module.project_class(zsup)\n loss_xent = model.module.loss_class(y_logits, y.to(x.get_device()))\n y_predicted = np.argmax(y_logits.cpu().detach().numpy(), axis=1)\n\n return bits_per_dim, loss_xent, y_predicted, atol, rtol, logp_actions, nfe\n\ndef create_model(args, data_shape, regularization_fns):\n hidden_dims = tuple(map(int, args.dims.split(\",\")))\n strides = tuple(map(int, args.strides.split(\",\")))\n\n if args.multiscale:\n model = odenvp.ODENVP(\n (args.batch_size, *data_shape),\n n_blocks=args.num_blocks,\n intermediate_dims=hidden_dims,\n nonlinearity=args.nonlinearity,\n alpha=args.alpha,\n cnf_kwargs={\"T\": args.time_length, \"train_T\": args.train_T, \"regularization_fns\": regularization_fns, \"solver\": args.solver, \"atol\": args.atol, \"rtol\": args.rtol, \"scale\": args.scale, \"scale_fac\": args.scale_fac, \"scale_std\": args.scale_std, \"gate\": args.gate},\n condition_ratio=args.condition_ratio,\n dropout_rate=args.dropout_rate,)\n elif args.parallel:\n model = multiscale_parallel.MultiscaleParallelCNF(\n (args.batch_size, *data_shape),\n n_blocks=args.num_blocks,\n intermediate_dims=hidden_dims,\n alpha=args.alpha,\n time_length=args.time_length,\n )\n else:\n if args.autoencode:\n\n def build_cnf():\n autoencoder_diffeq = layers.AutoencoderDiffEqNet(\n hidden_dims=hidden_dims,\n input_shape=data_shape,\n strides=strides,\n conv=args.conv,\n layer_type=args.layer_type,\n nonlinearity=args.nonlinearity,\n )\n odefunc = layers.AutoencoderODEfunc(\n autoencoder_diffeq=autoencoder_diffeq,\n divergence_fn=args.divergence_fn,\n residual=args.residual,\n rademacher=args.rademacher,\n )\n cnf = layers.CNF(\n odefunc=odefunc,\n T=args.time_length,\n regularization_fns=regularization_fns,\n solver=args.solver,\n )\n return cnf\n else:\n\n def build_cnf():\n diffeq = layers.ODEnet(\n hidden_dims=hidden_dims,\n input_shape=data_shape,\n strides=strides,\n conv=args.conv,\n layer_type=args.layer_type,\n nonlinearity=args.nonlinearity,\n )\n odefunc = layers.ODEfunc(\n diffeq=diffeq,\n divergence_fn=args.divergence_fn,\n residual=args.residual,\n rademacher=args.rademacher,\n )\n cnf = layers.CNF(\n odefunc=odefunc,\n T=args.time_length,\n train_T=args.train_T,\n regularization_fns=regularization_fns,\n solver=args.solver,\n )\n return cnf\n\n chain = [layers.LogitTransform(alpha=args.alpha)] if args.alpha > 0 else [layers.ZeroMeanTransform()]\n chain = chain + [build_cnf() for _ in range(args.num_blocks)]\n if args.batch_norm:\n chain.append(layers.MovingBatchNorm2d(data_shape[0]))\n model = layers.SequentialFlow(chain)\n return model\n\n\nif __name__ == \"__main__\":\n\n # get deivce\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n cvt = lambda x: x.type(torch.float32).to(device, non_blocking=True)\n\n # load dataset\n train_set, test_loader, data_shape = get_dataset(args)\n\n # build model\n regularization_fns, regularization_coeffs = create_regularization_fns(args)\n model = create_model(args, data_shape, regularization_fns)\n\n if args.spectral_norm: add_spectral_norm(model, logger)\n set_cnf_options(args, model)\n\n logger.info(model)\n logger.info(\"Number of trainable parameters: {}\".format(count_parameters(model)))\n \n writer.add_text('info', \"Number of trainable parameters: {}\".format(count_parameters(model)))\n\n # optimizer\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n \n # set initial iter\n itr = 1\n \n # set the meters\n time_epoch_meter = utils.RunningAverageMeter(0.97)\n time_meter = utils.RunningAverageMeter(0.97)\n loss_meter = utils.RunningAverageMeter(0.97) # track total loss\n nll_meter = utils.RunningAverageMeter(0.97) # track negative log-likelihood\n xent_meter = utils.RunningAverageMeter(0.97) # track xentropy score\n error_meter = utils.RunningAverageMeter(0.97) # track error score\n steps_meter = utils.RunningAverageMeter(0.97)\n grad_meter = utils.RunningAverageMeter(0.97)\n tt_meter = utils.RunningAverageMeter(0.97)\n\n # restore parameters\n if args.resume is not None:\n checkpt = torch.load(args.resume, map_location=lambda storage, loc: storage)\n model.load_state_dict(checkpt[\"state_dict\"])\n if \"optim_state_dict\" in checkpt.keys():\n optimizer.load_state_dict(checkpt[\"optim_state_dict\"])\n # Manually move optimizer state to device.\n for state in optimizer.state.values():\n for k, v in state.items():\n if torch.is_tensor(v):\n state[k] = cvt(v)\n args.begin_epoch = checkpt['epoch'] + 1\n itr = checkpt['iter'] + 1\n time_epoch_meter.set(checkpt['epoch_time_avg'])\n time_meter.set(checkpt['time_train'])\n loss_meter.set(checkpt['loss_train'])\n nll_meter.set(checkpt['bits_per_dim_train'])\n xent_meter.set(checkpt['xent_train'])\n error_meter.set(checkpt['error_train'])\n steps_meter.set(checkpt['nfe_train'])\n grad_meter.set(checkpt['grad_train'])\n tt_meter.set(checkpt['total_time_train'])\n\n if torch.cuda.is_available():\n model = torch.nn.DataParallel(model).cuda()\n\n # For visualization.\n if args.conditional:\n dim_unsup = int((1.0 - args.condition_ratio) * np.prod(data_shape))\n fixed_y = torch.from_numpy(np.arange(model.module.y_class)).repeat(model.module.y_class).type(torch.long).to(device, non_blocking=True)\n fixed_y_onehot = thops.onehot(fixed_y, num_classes=model.module.y_class)\n with torch.no_grad():\n mean, logs = model.module._prior(fixed_y_onehot)\n fixed_z_sup = modules.GaussianDiag.sample(mean, logs)\n fixed_z_unsup = cvt(torch.randn(model.module.y_class**2, dim_unsup))\n fixed_z = torch.cat((fixed_z_sup, fixed_z_unsup),1)\n else:\n fixed_z = cvt(torch.randn(100, *data_shape))\n \n\n if args.spectral_norm and not args.resume: spectral_norm_power_iteration(model, 500)\n\n best_loss_nll = float(\"inf\")\n best_error_score = float(\"inf\")\n \n for epoch in range(args.begin_epoch, args.num_epochs + 1):\n start_epoch = time.time()\n model.train()\n train_loader = get_train_loader(train_set, epoch)\n for _, (x, y) in enumerate(train_loader):\n start = time.time()\n update_lr(optimizer, itr)\n optimizer.zero_grad()\n\n if not args.conv:\n x = x.view(x.shape[0], -1)\n\n # cast data and move to device\n x = cvt(x)\n \n # compute loss\n if args.conditional:\n loss_nll, loss_xent, y_predicted, atol, rtol, logp_actions, nfe = compute_bits_per_dim_conditional(x, y, model)\n if args.train_mode == \"semisup\":\n loss = loss_nll + args.weight_y * loss_xent\n elif args.train_mode == \"sup\":\n loss = loss_xent\n elif args.train_mode == \"unsup\":\n loss = loss_nll\n else:\n raise ValueError('Choose supported train_mode: semisup, sup, unsup')\n error_score = 1. - np.mean(y_predicted.astype(int) == y.numpy()) \n \n else:\n loss, atol, rtol, logp_actions, nfe = compute_bits_per_dim(x, model)\n loss_nll, loss_xent, error_score = loss, 0., 0.\n \n if regularization_coeffs:\n reg_states = get_regularization(model, regularization_coeffs)\n reg_loss = sum(\n reg_state * coeff for reg_state, coeff in zip(reg_states, regularization_coeffs) if coeff != 0\n )\n loss = loss + reg_loss\n total_time = count_total_time(model)\n loss = loss + total_time * args.time_penalty\n\n # re-weight the gate rewards\n normalized_eta = args.eta / len(logp_actions)\n \n # collect cumulative future rewards\n R = - loss\n cum_rewards = []\n for r in nfe[::-1]:\n R = -normalized_eta * r.view(-1,1) + args.gamma * R\n cum_rewards.insert(0,R)\n \n # apply REINFORCE\n rl_loss = 0\n for lpa, r in zip(logp_actions, cum_rewards):\n rl_loss = rl_loss - lpa.view(-1,1) * args.rl_weight * r\n \n loss = loss + rl_loss.mean()\n \n loss.backward()\n \n grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)\n\n optimizer.step()\n \n for idx in range(len(model.module.transforms)):\n for layer in model.module.transforms[idx].chain:\n if hasattr(layer, 'atol'):\n layer.odefunc.after_odeint()\n\n if args.spectral_norm: spectral_norm_power_iteration(model, args.spectral_norm_niter)\n \n time_meter.update(time.time() - start)\n loss_meter.update(loss.item())\n nll_meter.update(loss_nll.item())\n if args.conditional:\n xent_meter.update(loss_xent.item())\n else:\n xent_meter.update(loss_xent)\n error_meter.update(error_score)\n steps_meter.update(count_nfe(model))\n grad_meter.update(grad_norm)\n tt_meter.update(total_time)\n \n # write to tensorboard\n writer.add_scalars('time', {'train_iter': time_meter.val}, itr)\n writer.add_scalars('loss', {'train_iter': loss_meter.val}, itr)\n writer.add_scalars('bits_per_dim', {'train_iter': nll_meter.val}, itr)\n writer.add_scalars('xent', {'train_iter': xent_meter.val}, itr)\n writer.add_scalars('error', {'train_iter': error_meter.val}, itr)\n writer.add_scalars('nfe', {'train_iter': steps_meter.val}, itr)\n writer.add_scalars('grad', {'train_iter': grad_meter.val}, itr)\n writer.add_scalars('total_time', {'train_iter': tt_meter.val}, itr)\n\n if itr % args.log_freq == 0:\n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_%i'%tol_indx, {'train': atol[tol_indx].mean()}, itr)\n writer.add_scalars('rtol_%i'%tol_indx, {'train': rtol[tol_indx].mean()}, itr)\n \n log_message = (\n \"Iter {:04d} | Time {:.4f}({:.4f}) | Bit/dim {:.4f}({:.4f}) | Xent {:.4f}({:.4f}) | Loss {:.4f}({:.4f}) | Error {:.4f}({:.4f}) \"\n \"Steps {:.0f}({:.2f}) | Grad Norm {:.4f}({:.4f}) | Total Time {:.2f}({:.2f})\".format(\n itr, time_meter.val, time_meter.avg, nll_meter.val, nll_meter.avg, xent_meter.val, xent_meter.avg, loss_meter.val, loss_meter.avg, error_meter.val, error_meter.avg, steps_meter.val, steps_meter.avg, grad_meter.val, grad_meter.avg, tt_meter.val, tt_meter.avg\n )\n )\n if regularization_coeffs:\n log_message = append_regularization_to_log(log_message, regularization_fns, reg_states)\n logger.info(log_message)\n writer.add_text('info', log_message, itr)\n\n itr += 1\n \n # compute test loss\n model.eval()\n if epoch % args.val_freq == 0:\n with torch.no_grad():\n # write to tensorboard\n writer.add_scalars('time', {'train_epoch': time_meter.avg}, epoch)\n writer.add_scalars('loss', {'train_epoch': loss_meter.avg}, epoch)\n writer.add_scalars('bits_per_dim', {'train_epoch': nll_meter.avg}, epoch)\n writer.add_scalars('xent', {'train_epoch': xent_meter.avg}, epoch)\n writer.add_scalars('error', {'train_epoch': error_meter.avg}, epoch)\n writer.add_scalars('nfe', {'train_epoch': steps_meter.avg}, epoch)\n writer.add_scalars('grad', {'train_epoch': grad_meter.avg}, epoch)\n writer.add_scalars('total_time', {'train_epoch': tt_meter.avg}, epoch)\n \n start = time.time()\n logger.info(\"validating...\")\n writer.add_text('info', \"validating...\", epoch)\n losses_nll = []; losses_xent = []; losses = []\n total_correct = 0\n \n for (x, y) in test_loader:\n if not args.conv:\n x = x.view(x.shape[0], -1)\n x = cvt(x)\n if args.conditional:\n loss_nll, loss_xent, y_predicted, atol, rtol, logp_actions, nfe = compute_bits_per_dim_conditional(x, y, model)\n if args.train_mode == \"semisup\":\n loss = loss_nll + args.weight_y * loss_xent\n elif args.train_mode == \"sup\":\n loss = loss_xent\n elif args.train_mode == \"unsup\":\n loss = loss_nll\n else:\n raise ValueError('Choose supported train_mode: semisup, sup, unsup')\n total_correct += np.sum(y_predicted.astype(int) == y.numpy())\n else:\n loss, atol, rtol, logp_actions, nfe = compute_bits_per_dim(x, model)\n loss_nll, loss_xent = loss, 0.\n losses_nll.append(loss_nll.cpu().numpy()); losses.append(loss.cpu().numpy())\n if args.conditional: \n losses_xent.append(loss_xent.cpu().numpy())\n else:\n losses_xent.append(loss_xent)\n \n loss_nll = np.mean(losses_nll); loss_xent = np.mean(losses_xent); loss = np.mean(losses)\n error_score = 1. - total_correct / len(test_loader.dataset)\n time_epoch_meter.update(time.time() - start_epoch)\n \n # write to tensorboard\n test_time_spent = time.time() - start\n writer.add_scalars('time', {'validation': test_time_spent}, epoch)\n writer.add_scalars('epoch_time', {'validation': time_epoch_meter.val}, epoch)\n writer.add_scalars('bits_per_dim', {'validation': loss_nll}, epoch)\n writer.add_scalars('xent', {'validation': loss_xent}, epoch)\n writer.add_scalars('loss', {'validation': loss}, epoch)\n writer.add_scalars('error', {'validation': error_score}, epoch)\n \n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_%i'%tol_indx, {'validation': atol[tol_indx].mean()}, epoch)\n writer.add_scalars('rtol_%i'%tol_indx, {'validation': rtol[tol_indx].mean()}, epoch)\n \n log_message = \"Epoch {:04d} | Time {:.4f}, Epoch Time {:.4f}({:.4f}), Bit/dim {:.4f}(best: {:.4f}), Xent {:.4f}, Loss {:.4f}, Error {:.4f}(best: {:.4f})\".format(epoch, time.time() - start, time_epoch_meter.val, time_epoch_meter.avg, loss_nll, best_loss_nll, loss_xent, loss, error_score, best_error_score)\n logger.info(log_message)\n writer.add_text('info', log_message, epoch)\n \n for name, param in model.named_parameters():\n writer.add_histogram(name, param.clone().cpu().data.numpy(), epoch)\n \n \n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"epoch_%i_checkpt.pth\"%epoch))\n \n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"current_checkpt.pth\"))\n \n if loss_nll < best_loss_nll:\n best_loss_nll = loss_nll\n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"best_nll_checkpt.pth\"))\n \n if args.conditional:\n if error_score < best_error_score:\n best_error_score = error_score\n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"best_error_checkpt.pth\"))\n \n\n # visualize samples and density\n with torch.no_grad():\n fig_filename = os.path.join(args.save, \"figs\", \"{:04d}.jpg\".format(epoch))\n utils.makedirs(os.path.dirname(fig_filename))\n generated_samples, atol, rtol, logp_actions, nfe = model(fixed_z, reverse=True)\n generated_samples = generated_samples.view(-1, *data_shape)\n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_gen_%i'%tol_indx, {'validation': atol[tol_indx].mean()}, epoch)\n writer.add_scalars('rtol_gen_%i'%tol_indx, {'validation': rtol[tol_indx].mean()}, epoch)\n save_image(generated_samples, fig_filename, nrow=10)\n if args.data == \"mnist\":\n writer.add_images('generated_images', generated_samples.repeat(1,3,1,1), epoch)\n else:\n writer.add_images('generated_images', generated_samples.repeat(1,1,1,1), epoch)\n\nNamespace(JFrobint=None, JdiagFrobint=None, JoffdiagFrobint=None, add_noise=True, alpha=1e-06, atol=1e-05, autoencode=False, batch_norm=False, batch_size=900, batch_size_schedule='', begin_epoch=1, condition_ratio=0.5, conditional=True, controlled_tol=False, conv=True, data='cifar10', dims='64,64,64', divergence_fn='approximate', dl2int=None, dropout_rate=0.5, eta=0.1, gamma=0.99, gate='cnn1', imagesize=None, l1int=None, l2int=None, layer_type='concat', log_freq=10, lr=0.001, max_grad_norm=10000000000.0, multiscale=True, nonlinearity='softplus', num_blocks=2, num_epochs=1000, parallel=False, rademacher=True, residual=False, resume='../experiments_published/cnf_conditional_disentangle_cifar10_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_run1/epoch_40_checkpt.pth', rl_weight=0.01, rtol=1e-05, save='../experiments_published/cnf_conditional_disentangle_cifar10_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_run1', scale=1.0, scale_fac=1.0, scale_std=6.0, seed=1, solver='dopri5', spectral_norm=False, spectral_norm_niter=10, step_size=None, strides='1,1,1,1', test_atol=None, test_batch_size=500, test_rtol=None, test_solver=None, time_length=1.0, time_penalty=0, train_T=True, train_mode='semisup', val_freq=1, warmup_iters=1000, weight_decay=0.0, weight_y=0.5)\n" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
4a528cf7b981e7080bb5a13dcfa84c76a2a2697f
6,408
ipynb
Jupyter Notebook
viz_scripts/mode_purpose_share.ipynb
shankari/em-public-dashboard
63477b889ab3349e2bc36310674d7d8091eef8d9
[ "BSD-3-Clause" ]
null
null
null
viz_scripts/mode_purpose_share.ipynb
shankari/em-public-dashboard
63477b889ab3349e2bc36310674d7d8091eef8d9
[ "BSD-3-Clause" ]
15
2021-02-09T21:47:42.000Z
2022-01-28T04:35:31.000Z
viz_scripts/mode_purpose_share.ipynb
shankari/em-public-dashboard
63477b889ab3349e2bc36310674d7d8091eef8d9
[ "BSD-3-Clause" ]
3
2021-01-23T23:55:01.000Z
2022-01-05T17:38:28.000Z
21.795918
222
0.566479
[ [ [ "## Sample code to generate static graphs", "_____no_output_____" ], [ "These are the input parameters for the notebook. They will be automatically changed when the scripts to generate monthly statistics are run. You can modify them manually to generate multiple plots locally as well.\n\nPass in `None` to remove the filters and plot all data. This is not recommended for production settings, but might be useful for reports based on data snapshots.", "_____no_output_____" ] ], [ [ "year = 2020\nmonth = 11\nprogram = \"prepilot\"", "_____no_output_____" ], [ "import scaffolding", "_____no_output_____" ], [ "import pandas as pd", "_____no_output_____" ], [ "tq = scaffolding.get_time_query(year, month)", "_____no_output_____" ], [ "participant_ct_df = scaffolding.load_all_participant_trips(program, tq)", "_____no_output_____" ], [ "labeled_ct = scaffolding.filter_labeled_trips(participant_ct_df)", "_____no_output_____" ], [ "expanded_ct = scaffolding.expand_userinputs(labeled_ct)", "_____no_output_____" ], [ "mode_confirm_vals = expanded_ct.mode_confirm.value_counts()\nmode_confirm_vals", "_____no_output_____" ], [ "mode_confirm_vals_df = pd.DataFrame(mode_confirm_vals)\nmode_confirm_vals_df", "_____no_output_____" ], [ "total_mode_confirms = mode_confirm_vals.sum()\ntop_ten_mode_confirm = mode_confirm_vals_df.iloc[0:9]\ntop_ten_mode_confirm", "_____no_output_____" ], [ "misc_count = (total_mode_confirms - top_ten_mode_confirm.mode_confirm.sum())\nmisc_count", "_____no_output_____" ], [ "top_ten_mode_confirm.loc[\"misc\"] = misc_count", "_____no_output_____" ], [ "top_ten_mode_confirm", "_____no_output_____" ], [ "expanded_ct.user_id.unique()", "_____no_output_____" ], [ "quality_text = scaffolding.get_quality_text(participant_ct_df, expanded_ct)", "_____no_output_____" ], [ "quality_text", "_____no_output_____" ], [ "pctFmt = lambda p: '%.1f%%'%p if p > 5 else None", "_____no_output_____" ], [ "ax = top_ten_mode_confirm.mode_confirm.plot.pie(autopct=pctFmt)\nax.set_ylabel(\"\")\nax.set_title(\"Travel modes selected by users\\n%s\" % quality_text)", "_____no_output_____" ], [ "file_suffix = scaffolding.get_file_suffix(year, month, program)", "_____no_output_____" ], [ "ax.figure.savefig(\"/plots/mode_confirm_%s.png\" % file_suffix)", "_____no_output_____" ], [ "below_top_ten_mode_confirm = mode_confirm_vals_df.iloc[9:]\nbelow_top_ten_mode_confirm", "_____no_output_____" ], [ "ax = below_top_ten_mode_confirm.mode_confirm.plot.pie(autopct=pctFmt)\nax.set_ylabel(\"\")\nax.set_title(\"Expansion of the 'misc' travel modes\\n%s\" % quality_text)", "_____no_output_____" ], [ "ax.figure.savefig(\"/plots/mode_confirm_misc_expand_%s.png\" % file_suffix)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a52938e135e1dafd5426e1a3516bfe804381e6d
69,233
ipynb
Jupyter Notebook
notebooks/4.0-ab-metadata-model.ipynb
adithyabsk/bird_audio
0962d966a6c4c866b9947ab87cfc63c110bfa497
[ "MIT" ]
6
2021-05-19T18:06:22.000Z
2022-02-04T23:29:44.000Z
notebooks/4.0-ab-metadata-model.ipynb
adithyabsk/bird_audio
0962d966a6c4c866b9947ab87cfc63c110bfa497
[ "MIT" ]
5
2021-05-19T01:48:50.000Z
2021-05-19T01:49:02.000Z
notebooks/4.0-ab-metadata-model.ipynb
adithyabsk/bird_audio
0962d966a6c4c866b9947ab87cfc63c110bfa497
[ "MIT" ]
null
null
null
132.884837
28,739
0.867058
[ [ [ "import json\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport xgboost as xgb\nfrom category_encoders import OneHotEncoder\nfrom pandas_profiling import ProfileReport\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.preprocessing import FunctionTransformer, MinMaxScaler, StandardScaler\nfrom sklearn_pandas import DataFrameMapper, gen_features\n\nsns.set_style(\"white\")\n\nROOT_PATH = Path(\"..\")", "_____no_output_____" ], [ "df = pd.read_csv(ROOT_PATH / \"data/raw/metadata.csv\")\nsvc_ids = pd.read_json(ROOT_PATH / \"data/raw/song_vs_call.json\").squeeze()\nsvc_df = df.loc[df.id.isin(svc_ids)].copy()\n\nwith open(ROOT_PATH / \"data/processed/svc_split.json\") as svc_split_file:\n svc_split = json.load(svc_split_file)\n train_ids = svc_split[\"train_ids\"]\n test_ids = svc_split[\"test_ids\"]", "_____no_output_____" ], [ "# Add response variable\ntype_col = svc_df.type.str.lower().str.replace(\" \", \"\").str.split(\",\")\nfiltered_type_col = type_col.apply(lambda l: set(l) - {\"call\", \"song\"})\nsvc_df[\"pred\"] = type_col.apply(lambda l: \"call\" in l).astype(int)", "_____no_output_____" ], [ "# Add gender feature\ndef filter_gender(labels):\n if \"male\" in labels:\n return \"male\"\n elif \"female\" in labels:\n return \"female\"\n else:\n return np.nan\n\n\nsvc_df[\"gender\"] = type_col.apply(filter_gender)", "_____no_output_____" ], [ "# Add age feature\ndef filter_age(labels):\n if \"adult\" in labels:\n return \"adult\"\n elif \"juvenile\" in labels:\n return \"juvenile\"\n else:\n return np.nan\n\n\nsvc_df[\"age\"] = type_col.apply(filter_age)", "_____no_output_____" ], [ "# Set up date and time columns\nsvc_df.date = pd.to_datetime(svc_df.date, format=\"%Y-%m-%d\", errors=\"coerce\")\nsvc_df.time = pd.to_datetime(svc_df.time, format=\"%H:%M\", errors=\"coerce\")\nsvc_df[\"month\"] = svc_df.date.dt.month\nsvc_df[\"day\"] = svc_df.date.dt.day\nsvc_df[\"hour\"] = svc_df.time.dt.hour\nsvc_df[\"minute\"] = svc_df.time.dt.minute", "_____no_output_____" ], [ "profile = ProfileReport(svc_df, title=\"Metadata Report\")\nfname = \"metadata_report.html\"\nprofile.to_file(f\"assets/{fname}\")", "_____no_output_____" ], [ "keep_cols = [\n \"id\",\n \"gen\",\n \"sp\",\n \"ssp\",\n \"en\",\n \"lat\",\n \"lng\",\n \"time\",\n \"date\",\n \"gender\",\n \"age\",\n \"month\",\n \"day\",\n \"hour\",\n \"minute\",\n]\nX_df, y_df = (\n svc_df.reindex(columns=keep_cols).copy(),\n svc_df.reindex(columns=[\"id\", \"pred\"]).copy(),\n)\ndt_feats = gen_features(\n columns=[[\"month\"], [\"day\"], [\"hour\"], [\"minute\"]],\n classes=[\n SimpleImputer,\n {\"class\": FunctionTransformer, \"func\": np.sin},\n MinMaxScaler,\n ],\n)\nn_components = 50\nfeature_mapper = DataFrameMapper(\n [\n (\"id\", None),\n ([\"gen\"], OneHotEncoder(drop_invariant=True, use_cat_names=True)),\n ([\"sp\"], OneHotEncoder(drop_invariant=True, use_cat_names=True)),\n ([\"en\"], OneHotEncoder(drop_invariant=True, use_cat_names=True)),\n ([\"lat\"], [SimpleImputer(), StandardScaler()]), # gaussian\n ([\"lng\"], [SimpleImputer(), MinMaxScaler()]), # bi-modal --> MinMaxScaler\n # TODO: maybe later look into converting month / day into days since start of year\n (\n [\"month\"],\n [\n SimpleImputer(),\n FunctionTransformer(lambda X: np.sin((X - 1) * 2 * np.pi / 12)),\n StandardScaler(), # gaussian\n ],\n ),\n (\n [\"day\"],\n [\n SimpleImputer(),\n FunctionTransformer(lambda X: np.sin(X * 2 * np.pi / 31)),\n MinMaxScaler(), # uniform\n ],\n ),\n # TODO: maybe later look into converting hour / minute into seconds since start of day\n (\n [\"hour\"],\n [\n SimpleImputer(),\n FunctionTransformer(lambda X: np.sin(X * 2 * np.pi / 24)),\n StandardScaler(), # gaussian\n ],\n ),\n (\n [\"minute\"],\n [\n SimpleImputer(),\n FunctionTransformer(lambda X: np.sin(X * 2 * np.pi / 60)),\n MinMaxScaler(), # uniform\n ],\n ),\n ],\n df_out=True,\n)", "_____no_output_____" ], [ "X_feat_df = feature_mapper.fit_transform(X_df, y_df[\"pred\"])\nX_train, X_test = (\n X_feat_df[X_feat_df.id.isin(train_ids)].drop(columns=[\"id\"]),\n X_feat_df[X_feat_df.id.isin(test_ids)].drop(columns=[\"id\"]),\n)\ny_train, y_test = (\n y_df[y_df.id.isin(train_ids)].drop(columns=[\"id\"]).squeeze(),\n y_df[y_df.id.isin(test_ids)].drop(columns=[\"id\"]).squeeze(),\n)", "/Users/adithyabalaji/.pyenv/versions/3.8.0/envs/pracds_final/lib/python3.8/site-packages/category_encoders/utils.py:21: FutureWarning: is_categorical is deprecated and will be removed in a future version. Use is_categorical_dtype instead\n elif pd.api.types.is_categorical(cols):\n/Users/adithyabalaji/.pyenv/versions/3.8.0/envs/pracds_final/lib/python3.8/site-packages/category_encoders/utils.py:21: FutureWarning: is_categorical is deprecated and will be removed in a future version. Use is_categorical_dtype instead\n elif pd.api.types.is_categorical(cols):\n/Users/adithyabalaji/.pyenv/versions/3.8.0/envs/pracds_final/lib/python3.8/site-packages/category_encoders/utils.py:21: FutureWarning: is_categorical is deprecated and will be removed in a future version. Use is_categorical_dtype instead\n elif pd.api.types.is_categorical(cols):\n" ], [ "lr = LogisticRegression()\nlr.fit(X_train, y_train)\n\nprint(lr.score(X_test, y_test))", "0.7496551724137931\n" ], [ "xgb_clf = xgb.XGBClassifier()\neval_set = [(X_train, y_train), (X_test, y_test)]\nxgb_clf.fit(\n X_train, y_train, eval_metric=[\"error\", \"logloss\"], eval_set=eval_set, verbose=False\n)\n\nprint(xgb_clf.score(X_test, y_test))", "/Users/adithyabalaji/.pyenv/versions/3.8.0/envs/pracds_final/lib/python3.8/site-packages/xgboost/sklearn.py:1146: UserWarning: The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1].\n warnings.warn(label_encoder_deprecation_msg, UserWarning)\n" ], [ "# Loss\n# retrieve performance metrics\nresults = xgb_clf.evals_result()\nepochs = len(results[\"validation_0\"][\"error\"])\nx_axis = range(0, epochs)\n\n# plot log loss\nf, ax = plt.subplots()\nax.plot(x_axis, results[\"validation_0\"][\"logloss\"], label=\"Train\")\nax.plot(x_axis, results[\"validation_1\"][\"logloss\"], label=\"Test\")\nax.legend()\nsns.despine(f, ax)\nplt.ylabel(\"Log Loss\")\nplt.xlabel(\"Epochs\")\nplt.title(\"Log Loss vs Epochs (XGBoost Meta Model)\")\n\nf.tight_layout()\nfig_name = \"svc_meta_xgb_loss.png\"\nf.savefig(f\"assets/{fig_name}\", dpi=150);", "_____no_output_____" ], [ "xgb_train_acc = xgb_clf.score(X_train, y_train)\nxgb_test_acc = xgb_clf.score(X_test, y_test)\n\nprint(f\"Train Loss: {results['validation_0']['logloss'][-1]:.3f}\")\nprint(f\"Test Loss: {results['validation_1']['logloss'][-1]:.3f}\")\n\nprint(f\"Train Accuracy: {xgb_train_acc:.3f}\")\nprint(f\"Test Accuracy: {xgb_test_acc:.3f}\")", "Train Loss: 0.331\nTest Loss: 0.507\nTrain Accuracy: 0.879\nTest Accuracy: 0.773\n" ], [ "# Feature importance\n# how it is calculated: https://stats.stackexchange.com/a/422480/311774\nN_feats = 10\nfeat_imp = pd.Series(\n xgb_clf.feature_importances_, index=X_train.columns, name=\"imp\"\n).nlargest(N_feats)\n\nf, ax = plt.subplots()\nax.bar(feat_imp.index, feat_imp)\nsns.despine(f, ax, bottom=True)\nplt.setp(ax.get_xticklabels(), rotation=75)\n\nax.set_xlabel(\"Feature Name\")\nax.set_ylabel(\"Importance\")\nax.set_title(f\"Importance vs Feature for the {N_feats} Largest Importances\")\nf.tight_layout()\nfig_name = \"svc_meta_xgb_imp.png\"\nf.savefig(f\"assets/{fig_name}\", dpi=150);", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a52969c54755f86d22a8f41355228adc6cc1fe9
1,553
ipynb
Jupyter Notebook
ds/cancer.ipynb
ganesh-95/machine-learning
03f15e2bfdf53b0cd651e0b3e997513b4f66c68c
[ "MIT" ]
null
null
null
ds/cancer.ipynb
ganesh-95/machine-learning
03f15e2bfdf53b0cd651e0b3e997513b4f66c68c
[ "MIT" ]
5
2020-03-24T15:48:59.000Z
2021-06-01T22:20:40.000Z
ds/cancer.ipynb
ganesh-95/machine-learning
03f15e2bfdf53b0cd651e0b3e997513b4f66c68c
[ "MIT" ]
null
null
null
23.892308
98
0.547972
[ [ [ "import numpy as np\nfrom sklearn import preprocessing, cross_validation, neighbors\nimport pandas as pd\n\ndf = pd.read_csv('breast-cancer-wisconsin.data.txt')\ndf.replace('?', -99999, inplace=True)\ndf.drop(['id'], 1, inplace=True)\n\nX = np.array(df.drop(['class'],1))\ny = np.array(df['class'])\n\nX_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.2)\n\nclf = neighbors.KNeighborsClassifier()\nclf.fit(X_train, y_train)\naccuracy = clf.score(X_test, y_test)\nprint (accuracy)\n\nexample_measures = np.array([4, 2, 1, 1, 1, 2, 3, 2, 1])\nexample_measures = example_measures.reshape(1, -1)\nprediction = clf.predict(example_measures)\nprint (prediction)", "0.971428571429\n[2]\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
4a52a7af6226ca63f63a78b76a0bc1d1782a5234
171,576
ipynb
Jupyter Notebook
data_analysis/Figure_6_splicing_and_cleavage.ipynb
NeugebauerLab/MEL_LRS
6b88e3c93b0369d064c1c2969384f7f09e5de69e
[ "MIT" ]
1
2021-05-02T16:23:10.000Z
2021-05-02T16:23:10.000Z
data_analysis/Figure_6_splicing_and_cleavage.ipynb
NeugebauerLab/MEL_LRS
6b88e3c93b0369d064c1c2969384f7f09e5de69e
[ "MIT" ]
null
null
null
data_analysis/Figure_6_splicing_and_cleavage.ipynb
NeugebauerLab/MEL_LRS
6b88e3c93b0369d064c1c2969384f7f09e5de69e
[ "MIT" ]
1
2020-12-14T05:30:25.000Z
2020-12-14T05:30:25.000Z
271.481013
67,288
0.907458
[ [ [ "'''\nThis notebook analyzes splicing and cleavage using LRS data.\nFigures 6 and S7\n'''", "_____no_output_____" ], [ "import os\nimport re\n\nimport numpy as np\nimport pandas as pd\nfrom pandas.api.types import CategoricalDtype\nimport mygene\nimport scipy\n\nfrom plotnine import *\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport matplotlib\nmatplotlib.rcParams['pdf.fonttype'] = 42 # export pdfs with editable font types in Illustrator", "_____no_output_____" ], [ "# Link to annotation of all TES from UCSC Genome Browser\nTES_all = pd.read_csv('mm10_TES.bed', # downloaded from UCSC table browser, all genes last coordinate only\n delimiter = '\\t', \n names = ['chr', 'start', 'end', 'name', 'score', 'strand'])\n\n# Link to active TSSs from PRO-seq\nactive_TSS = pd.read_csv('../annotation_files/active_TSS_PROseq_150_counts_mm10_VM20.txt', delimiter = '\\t', header = 0)\n\n# Links to input data: BED12 files that have been separated by splicing status\ndataFiles = [\n '../Figure_2_S3/all_spliced_reads.bed',\n '../Figure_2_S3/partially_spliced_reads.bed',\n '../Figure_2_S3/all_unspliced_reads.bed',\n ]\n\n# Read in file with PROseq read counts downstream of the PAS associated with each intron transcript ID\nproseq_cts_all = pd.read_csv('../annotation_files/200916_Untreated_10readcutoff_PROseq_Intronic_vs_Flanking_Exon_Signal.txt', sep = '\\t')", "_____no_output_____" ], [ "# # First, filter TES coordinates for only those that come from actively transcribed TSS's in MEL cells (as defined by PRO-seq)\nTES_all['ENSMUST.ID'] = TES_all.name.str.split('_').str[0] # create column with txid from name column\nTES = pd.merge(TES_all, active_TSS[['txname']], left_on = 'ENSMUST.ID', right_on = 'txname', how = 'inner', copy = False)", "_____no_output_____" ], [ "# Generate a file for doing bedtools coverage with a window around the TES\n# set window length for generating window around splice sites\nupstream = 100\ndownstream = 1000\n\n# make a window around TES using defined window length\nTES.loc[TES['strand'] == '+', 'window_start'] = (TES['start'] - upstream)\nTES.loc[TES['strand'] == '-', 'window_start'] = (TES['start'] - downstream)\nTES.loc[TES['strand'] == '+', 'window_end'] = (TES['end'] + downstream)\nTES.loc[TES['strand'] == '-', 'window_end'] = (TES['end'] + upstream)\n\n# return window start and end coordinates to intergers rather than floats\nTES['window_start'] = TES['window_start'].astype(np.int64)\nTES['window_end'] = TES['window_end'].astype(np.int64)\nTES['window_start'] = TES['window_start'].astype(np.int64)\nTES['window_end'] = TES['window_end'].astype(np.int64)\n\nout_cols = ['chr', 'window_start', 'window_end', 'name', 'score', 'strand']\n\nTES.to_csv('TES_window.bed', columns = out_cols, sep = '\\t', index = False, header = False)", "_____no_output_____" ], [ "# Calculate coverage over the TES window region using bedtools coverage (IN A TERMINAL WINDOW)\n################################################################################################################\n# bedtools coverage -s -d -a TES_window.bed -b ../Figure_2/all_spliced_reads.bed > all_spliced_cov.txt\n# bedtools coverage -s -d -a TES_window.bed -b ../Figure_2/partially_spliced_reads.bed > partially_spliced_cov.txt\n# bedtools coverage -s -d -a TES_window.bed -b ../Figure_2/all_unspliced_reads.bed > all_unspliced_cov.txt\n################################################################################################################", "_____no_output_____" ], [ "# Define a function to read in output of bedtools coverage, rearrange columns and compute coverage in bins over a TES window\ndef get_coverage(file):\n filestring = file.split('/')[-1].split('_')[0:2]\n sample = '_'.join(filestring) # get sample ID from file name\n \n f = pd.read_csv(file, compression = 'gzip', sep = '\\t', names = ['chr', 'start', 'end', 'name', 'score', 'strand', 'position', 'count'])\n \n f_grouped = f.groupby(['strand', 'position']).agg({'count':'sum'}) # group by position and strand, sum all counts\n \n tmp = f_grouped.unstack(level='strand') # separate plus and minus strand counts\n tmp_plus = tmp['count', '+'].to_frame() # convert both + and - strand series to dataframes\n tmp_minus = tmp['count', '-'].to_frame()\n tmp_minus = tmp_minus[::-1] # reverse order of the entries in the minus strand df\n tmp_minus['new_position'] = list(range(1,1102,1)) # reset the position to be 1-50 for the minus strand so it matches plus strand (flipped)\n df = pd.merge(tmp_plus, tmp_minus, left_index = True, right_on = 'new_position')\n\n df['total_count'] = df['count', '+'] + df['count', '-']\n df = df[['new_position', 'total_count']] # drop separate count columns for each strand\n df['rel_position'] = range(-100,1001,1) # add relative position around TES\n \n\n TES_val = df['total_count'].values[1] # get the coverage at the TES nucleotide position\n df['TES_pos_count'] = TES_val\n df['normalized_count'] = df['total_count'] / df['TES_pos_count'] # normalize coverage to TES coverage\n df['sample'] = sample # add sample identifier\n \n return df # return dataframe with position around TES ('normalized_count') and relative position around TES ('rel_position')", "_____no_output_____" ], [ "# get coverage for all_spliced, partially_spliced, and all_unspliced reads (each of these is slow)\ndf_cov_all_spliced = get_coverage('all_spliced_cov.txt.gz')\ndf_cov_partially_spliced = get_coverage('partially_spliced_cov.txt.gz')\ndf_cov_all_unspliced = get_coverage('all_unspliced_cov.txt.gz')\n\n# concat all coverage dataframes together\ndf = pd.concat([df_cov_all_spliced, df_cov_partially_spliced, df_cov_all_unspliced])", "_____no_output_____" ], [ "# save coverage df\ndf.to_csv('coverage_matrix.txt', sep = '\\t', index = False, header = True)", "_____no_output_____" ] ], [ [ "### Figure 6C", "_____no_output_____" ] ], [ [ "# plot read coverage past PAS\nmy_colours = ['#43006A', '#FBC17D', '#81176D']\n\nplt_PAS_coverage = (ggplot\n (data = df, mapping=aes( x = 'rel_position', y = 'normalized_count', colour = 'sample')) + \n geom_line(size = 2, stat = 'identity') +\n scale_colour_manual(values = my_colours) + \n theme_linedraw(base_size = 12) +\n xlab('Position relative to PAS [nt]') +\n ylim(0.6,1.05) +\n xlim(-100, 250) +\n ylab('Read Coverage normalized to 100 nt before PAS'))\nplt_PAS_coverage", "_____no_output_____" ], [ "# plot PROseq coverage downstream of TES\n# NOTE: THIS INPUT FILE IS FROM CLAUDIA WITHOUT INTRON IDS\nproseq_tes = pd.read_csv('Figure 6C_Log2 transformed PRO-seq Signal aroundTES Violin Plot Test.txt', sep = '\\t')\nproseq_tes.columns = ['<0.6', '0.6-0.79', '0.8-0.99', '1']\nproseq_tes_long = proseq_tes.melt(value_vars = ['<0.6', '0.6-0.79', '0.8-0.99', '1'], value_name = 'PROseq_counts', var_name = 'CoSE')\ncat_type = CategoricalDtype(categories=['<0.6', '0.6-0.79', '0.8-0.99', '1'], ordered=True) # turn category column into a category variable in order to control order of plotting\nproseq_tes_long['CoSE'] = proseq_tes_long['CoSE'].astype(cat_type)", "_____no_output_____" ] ], [ [ "### Figure S7D", "_____no_output_____" ] ], [ [ "my_colours = ['#FA8657', '#FBC17D', '#81176D', '#43006A']\nplt_cose_TESPROseq = (ggplot\n (data=proseq_tes_long, mapping=aes( x='CoSE', y = 'PROseq_counts', fill = 'CoSE')) + \n geom_violin(width = 0.8) +\n geom_boxplot(width = 0.3, fill = 'white', alpha = 0.4) +\n theme_linedraw(base_size = 12) +\n theme(axis_text_x=element_text(rotation=45, hjust=1)) +\n# theme(figure_size = (2.5,4)) +\n theme(figure_size = (3,4)) +\n ylab('PROseq Read Counts TES to +1 kb (log2)') +\n ylim(1, 15) +\n# scale_y_log10(limits = (0.000001, 5)) +\n# scale_y_log10() +\n scale_fill_manual(values = my_colours)\n )\nplt_cose_TESPROseq", "_____no_output_____" ], [ "# Combine reads that have been classifed by splicing status into a single file, adding a new column to record splicing status\nalldata = []\nfor file in dataFiles:\n# df = pd.read_csv(file, delimiter = '\\t', names = ['chr', 'start', 'end', 'name', 'score', 'strand', 'readStart', 'readEnd', 'rgb', 'blocks', 'blockSizes', 'blockStarts'])\n df = pd.read_csv(file, delimiter = '\\t', names = ['chr', 'start', 'end', 'name', 'score', 'strand', 'readStart', 'readEnd', 'rgb', 'blocks', 'blockSizes', 'blockStarts', 'status', 'treatment'])\n# splicing_status = file.split('/')[2]\n# df['status'] = splicing_status\n alldata.append(df)\ndata = pd.concat(alldata)", "_____no_output_____" ], [ "# Define a function to get the 5' end coordiates for each read\ndef get_5end_coord(df):\n plus = df.loc[df['strand'] == '+']\n minus = df.loc[df['strand'] == '-']\n columns = ['chr', 'start', 'end', 'name', 'score', 'strand', 'readStart', 'readEnd', 'rgb', 'blocks', 'blockSizes', 'blockStarts', 'status', 'treatment']\n \n plus['end'] = plus['start'] + 1\n plus_out = plus[columns]\n \n minus['start'] = minus['end'] - 1\n minus_out = minus[columns]\n \n out = pd.concat([plus_out, minus_out])\n \n out.to_csv('data_combined_5end.bed', sep = '\\t', index = False, header = False)", "_____no_output_____" ], [ "# Create a BED file with 5' end coordinate for combined long read data with splicing status classification\nget_5end_coord(data)", "_____no_output_____" ], [ "# Bedtools intersect 5' end of reads with active transcripts - write entire read a (IN A TERMINAL WINDOW)\n################################################################################################################\n# bedtools intersect -wo -s -a data_combined_5end.bed -b ../annotation_files/active_transcripts.bed > fiveEnd_intersect_active_transcripts.txt\n################################################################################################################", "_____no_output_____" ], [ "# Read in result of bedtools intersect: r_ indicates read info, t_ indicates transcript annotation info\nintersect = pd.read_csv('fiveEnd_intersect_active_transcripts.txt', \n delimiter = '\\t', \n names = ['r_chr', 'r_fiveEnd_start', 'r_fiveEnd_end', 'r_name', 'r_score', 'r_strand', 'r_readStart', 'r_readEnd', 'r_rgb', 'r_blocks', 'r_blockSizes', 'r_blockStarts', 'splicing_status', 'treatment', 't_chr', 't_start', 't_end', 't_name', 't_score', 't_strand', 'overlaps'])", "_____no_output_____" ], [ "# For reach row, compare whether or not the readEnd is past the transcript end, if so add 1 to cleavage status\n\ndistance_past_PAS = 50 # set cutoff distance for the read end to be past the annotated PAS\n\nintersect_plus = intersect.loc[intersect['r_strand'] == \"+\"]\nintersect_minus = intersect.loc[intersect['r_strand'] == \"-\"]\n\nconditions_plus = [intersect_plus['r_readEnd'] > intersect_plus['t_end'].astype(int) + distance_past_PAS,\n intersect_plus['r_readEnd'] <= intersect_plus['t_end'].astype(int) + distance_past_PAS]\nconditions_minus = [intersect_minus['r_readStart'] < intersect_minus['t_start'].astype(int) - distance_past_PAS,\n intersect_minus['r_readStart'] >= intersect_minus['t_start'].astype(int) - distance_past_PAS]\n\noutputs = [1,0]\nintersect_plus['uncleaved'] = np.select(conditions_plus, outputs, np.NaN)\nintersect_minus['uncleaved'] = np.select(conditions_minus, outputs, np.NaN)\ni = pd.concat([intersect_plus, intersect_minus])\n\ng = i.groupby('r_name').agg({'uncleaved':'sum', # count the number of reads with 3' end past transcript PAS\n 'splicing_status':'first', # record splicing status for each read\n 'treatment':'first', # record treatment condiditon for each read\n 'overlaps':'sum'}) # count the total number of transcript overlaps\n\ng['cleavage_ratio'] = g['uncleaved']/g['overlaps'] # calculate how many times a transcript is called as uncleaved for all of the transcript annotations that it overlaps\ng['cleavage_status'] = np.where(g['cleavage_ratio'] ==1,'uncleaved', 'cleaved') # only classify a read as \"uncleaved\" if the 3' end is past the PAS for ALL transcript annotations that it overlaps with", "_____no_output_____" ], [ "# Calculate fraction of reads that are in each splicing category for cleaved/uncleaved reads\ntotal_uncleaved = len(g.loc[g['cleavage_status'] == 'uncleaved'])\ntotal_cleaved = len(g.loc[g['cleavage_status'] == 'cleaved'])\n\nall_spliced_cleaved = len(g.loc[(g['splicing_status'] == 'all_spliced') & (g['cleavage_status'] == 'cleaved')])\npartially_spliced_cleaved = len(g.loc[(g['splicing_status'] == 'partially_spliced') & (g['cleavage_status'] == 'cleaved')])\nall_unspliced_cleaved = len(g.loc[(g['splicing_status'] == 'all_unspliced') & (g['cleavage_status'] == 'cleaved')])\n\nall_spliced_uncleaved = len(g.loc[(g['splicing_status'] == 'all_spliced') & (g['cleavage_status'] == 'uncleaved')])\npartially_spliced_uncleaved = len(g.loc[(g['splicing_status'] == 'partially_spliced') & (g['cleavage_status'] == 'uncleaved')])\nall_unspliced_uncleaved = len(g.loc[(g['splicing_status'] == 'all_unspliced') & (g['cleavage_status'] == 'uncleaved')])\n\ndata_list = [['uncleaved', 'all_spliced', all_spliced_uncleaved, total_uncleaved],\n ['uncleaved', 'partially_spliced', partially_spliced_uncleaved, total_uncleaved],\n ['uncleaved', 'all_unspliced', all_unspliced_uncleaved, total_uncleaved],\n ['cleaved', 'all_spliced', all_spliced_cleaved, total_cleaved],\n ['cleaved', 'partially_spliced', partially_spliced_cleaved, total_cleaved],\n ['cleaved', 'all_unspliced', all_unspliced_cleaved, total_cleaved]]\n\n# Create the pandas DataFrame \ndf = pd.DataFrame(data_list, columns = ['cleavage_status', 'splicing_status', 'count', 'total']) \ndf['fraction'] = df['count']/df['total']\ndf", "_____no_output_____" ], [ "print('Number of Cleaved reads: ' + str(total_cleaved))\nprint('Number of Uncleaved reads: ' + str(total_uncleaved))", "Number of Cleaved reads: 172612\nNumber of Uncleaved reads: 5694\n" ] ], [ [ "### Figure 6C", "_____no_output_____" ] ], [ [ "my_colours = ['#43006A', '#FBC17D', '#81176D']\nplt_splicing_cleavage_fraction = (ggplot\n (data=df, mapping=aes(x='cleavage_status', y='fraction', fill = 'splicing_status')) + \n geom_bar(stat = 'identity', position = 'stack', colour = 'black') +\n theme_linedraw(base_size = 12) +\n theme(figure_size = (3,6)) +\n xlab(\"3' End Cleavage Status\") +\n ylab('Fraction of Long Reads') +\n scale_fill_manual(values = my_colours)\n )\nplt_splicing_cleavage_fraction", "_____no_output_____" ] ], [ [ "### Save output figures", "_____no_output_____" ] ], [ [ "plt_splicing_cleavage_fraction.save('fraction_uncleaved_unspliced_reads.pdf') # Fig 6C\nplt_PAS_coverage.save('coverage_downstream_PAS_splicing_status.pdf') # Fig 6D\nplt_cose_TESPROseq.save('PROseq_counts_TES_by_CoSE.pdf') # Fig S7D", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a52bec76cc470f2233291f2e0ef3039a93a8168
46,550
ipynb
Jupyter Notebook
tutorials/Tutorial3_Basic_QA_Pipeline_without_Elasticsearch.ipynb
tanay1337/haystack
07bd3c50ead83ec934fcc9eaf425b7dca44add79
[ "Apache-2.0" ]
null
null
null
tutorials/Tutorial3_Basic_QA_Pipeline_without_Elasticsearch.ipynb
tanay1337/haystack
07bd3c50ead83ec934fcc9eaf425b7dca44add79
[ "Apache-2.0" ]
null
null
null
tutorials/Tutorial3_Basic_QA_Pipeline_without_Elasticsearch.ipynb
tanay1337/haystack
07bd3c50ead83ec934fcc9eaf425b7dca44add79
[ "Apache-2.0" ]
null
null
null
103.674833
2,883
0.41493
[ [ [ "# Build a QA System Without Elasticsearch\n\n[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial3_Basic_QA_Pipeline_without_Elasticsearch.ipynb)\n\nHaystack provides alternatives to Elasticsearch for developing quick prototypes.\n\nYou can use an `InMemoryDocumentStore` or a `SQLDocumentStore`(with SQLite) as the document store.\n\nIf you are interested in more feature-rich Elasticsearch, then please refer to the Tutorial 1. ", "_____no_output_____" ], [ "### Prepare environment\n\n#### Colab: Enable the GPU runtime\nMake sure you enable the GPU runtime to experience decent speed in this tutorial.\n**Runtime -> Change Runtime type -> Hardware accelerator -> GPU**\n\n<img src=\"https://raw.githubusercontent.com/deepset-ai/haystack/master/docs/_src/img/colab_gpu_runtime.jpg\">", "_____no_output_____" ] ], [ [ "# Make sure you have a GPU running\n!nvidia-smi", "_____no_output_____" ], [ "# Install the latest release of Haystack in your own environment \n#! pip install farm-haystack\n\n# Install the latest master of Haystack\n!pip install grpcio-tools==1.34.1\n!pip install git+https://github.com/deepset-ai/haystack.git\n", "_____no_output_____" ], [ "from haystack.preprocessor.cleaning import clean_wiki_text\nfrom haystack.preprocessor.utils import convert_files_to_dicts, fetch_archive_from_http\nfrom haystack.reader.farm import FARMReader\nfrom haystack.reader.transformers import TransformersReader\nfrom haystack.utils import print_answers", "_____no_output_____" ] ], [ [ "## Document Store\n", "_____no_output_____" ] ], [ [ "# In-Memory Document Store\nfrom haystack.document_store.memory import InMemoryDocumentStore\ndocument_store = InMemoryDocumentStore()", "_____no_output_____" ], [ "# SQLite Document Store\n# from haystack.document_store.sql import SQLDocumentStore\n# document_store = SQLDocumentStore(url=\"sqlite:///qa.db\")", "_____no_output_____" ] ], [ [ "## Preprocessing of documents\n\nHaystack provides a customizable pipeline for:\n - converting files into texts\n - cleaning texts\n - splitting texts\n - writing them to a Document Store\n\nIn this tutorial, we download Wikipedia articles on Game of Thrones, apply a basic cleaning function, and index them in Elasticsearch.", "_____no_output_____" ] ], [ [ "# Let's first get some documents that we want to query\n# Here: 517 Wikipedia articles for Game of Thrones\ndoc_dir = \"data/article_txt_got\"\ns3_url = \"https://s3.eu-central-1.amazonaws.com/deepset.ai-farm-qa/datasets/documents/wiki_gameofthrones_txt.zip\"\nfetch_archive_from_http(url=s3_url, output_dir=doc_dir)\n\n# convert files to dicts containing documents that can be indexed to our datastore\n# You can optionally supply a cleaning function that is applied to each doc (e.g. to remove footers)\n# It must take a str as input, and return a str.\ndicts = convert_files_to_dicts(dir_path=doc_dir, clean_func=clean_wiki_text, split_paragraphs=True)\n\n# We now have a list of dictionaries that we can write to our document store.\n# If your texts come from a different source (e.g. a DB), you can of course skip convert_files_to_dicts() and create the dictionaries yourself.\n# The default format here is: {\"name\": \"<some-document-name>, \"text\": \"<the-actual-text>\"}\n\n# Let's have a look at the first 3 entries:\nprint(dicts[:3])\n# Now, let's write the docs to our DB.\ndocument_store.write_documents(dicts)", "04/28/2020 15:06:07 - INFO - haystack.indexing.io - Found data stored in `data/article_txt_got`. Delete this first if you really want to fetch new data.\n04/28/2020 15:06:07 - INFO - haystack.indexing.io - Wrote 517 docs to DB\n" ] ], [ [ "## Initalize Retriever, Reader & Pipeline\n\n### Retriever\n\nRetrievers help narrowing down the scope for the Reader to smaller units of text where a given question could be answered. \n\nWith InMemoryDocumentStore or SQLDocumentStore, you can use the TfidfRetriever. For more retrievers, please refer to the tutorial-1.", "_____no_output_____" ] ], [ [ "# An in-memory TfidfRetriever based on Pandas dataframes\n\nfrom haystack.retriever.sparse import TfidfRetriever\nretriever = TfidfRetriever(document_store=document_store)", "04/28/2020 15:07:34 - INFO - haystack.retriever.tfidf - Found 2811 candidate paragraphs from 517 docs in DB\n" ] ], [ [ "### Reader\n\nA Reader scans the texts returned by retrievers in detail and extracts the k best answers. They are based\non powerful, but slower deep learning models.\n\nHaystack currently supports Readers based on the frameworks FARM and Transformers.\nWith both you can either load a local model or one from Hugging Face's model hub (https://huggingface.co/models).\n\n**Here:** a medium sized RoBERTa QA model using a Reader based on FARM (https://huggingface.co/deepset/roberta-base-squad2)\n\n**Alternatives (Reader):** TransformersReader (leveraging the `pipeline` of the Transformers package)\n\n**Alternatives (Models):** e.g. \"distilbert-base-uncased-distilled-squad\" (fast) or \"deepset/bert-large-uncased-whole-word-masking-squad2\" (good accuracy)\n\n**Hint:** You can adjust the model to return \"no answer possible\" with the no_ans_boost. Higher values mean the model prefers \"no answer possible\"\n\n#### FARMReader", "_____no_output_____" ] ], [ [ "# Load a local model or any of the QA models on\n# Hugging Face's model hub (https://huggingface.co/models)\n\nreader = FARMReader(model_name_or_path=\"deepset/roberta-base-squad2\", use_gpu=True)", "04/28/2020 15:07:40 - INFO - farm.utils - device: cpu n_gpu: 0, distributed training: False, automatic mixed precision training: None\n04/28/2020 15:07:40 - INFO - farm.infer - Could not find `deepset/roberta-base-squad2` locally. Try to download from model hub ...\n04/28/2020 15:07:45 - WARNING - farm.modeling.language_model - Could not automatically detect from language model name what language it is. \n\t We guess it's an *ENGLISH* model ... \n\t If not: Init the language model by supplying the 'language' param.\n04/28/2020 15:07:49 - WARNING - farm.modeling.prediction_head - Some unused parameters are passed to the QuestionAnsweringHead. Might not be a problem. Params: {\"loss_ignore_index\": -1}\n04/28/2020 15:07:54 - INFO - farm.utils - device: cpu n_gpu: 0, distributed training: False, automatic mixed precision training: None\n" ] ], [ [ "#### TransformersReader", "_____no_output_____" ] ], [ [ "# Alternative:\n# reader = TransformersReader(model_name_or_path=\"distilbert-base-uncased-distilled-squad\", tokenizer=\"distilbert-base-uncased\", use_gpu=-1)", "_____no_output_____" ] ], [ [ "### Pipeline\n\nWith a Haystack `Pipeline` you can stick together your building blocks to a search pipeline.\nUnder the hood, `Pipelines` are Directed Acyclic Graphs (DAGs) that you can easily customize for your own use cases.\nTo speed things up, Haystack also comes with a few predefined Pipelines. One of them is the `ExtractiveQAPipeline` that combines a retriever and a reader to answer our questions.\nYou can learn more about `Pipelines` in the [docs](https://haystack.deepset.ai/docs/latest/pipelinesmd).", "_____no_output_____" ] ], [ [ "from haystack.pipeline import ExtractiveQAPipeline\npipe = ExtractiveQAPipeline(reader, retriever)", "_____no_output_____" ] ], [ [ "## Voilà! Ask a question!", "_____no_output_____" ] ], [ [ "# You can configure how many candidates the reader and retriever shall return\n# The higher top_k_retriever, the better (but also the slower) your answers.\nprediction = pipe.run(query=\"Who is the father of Arya Stark?\", top_k_retriever=10, top_k_reader=5)", "04/28/2020 15:07:54 - INFO - haystack.retriever.tfidf - Identified 10 candidates via retriever:\n paragraph_id document_id text\n 2721 f258f55f534d1a8b3644c3b1bd2d9069 \\n===Arya Stark===\\n'''Arya Stark''' portrayed by Maisie Williams. Arya Stark of House Stark is the younger daughter and third child of Lord Eddard and Catelyn Stark of Winterfell. Ever the tomboy, Arya would rather be training to use weapons than sewing with a needle. She names her direwolf Nymeria, after a legendary warrior queen.\n 2210 2d9538e229b8272de9b6f74bf8cdd270 \\n====Season 8====\\nArya reunites with Jon, Gendry, and the Hound, who have all journeyed to Winterfell with Daenerys Targaryen's forces to make a stand against the approaching White Walkers. Arya asks Gendry, who is forging dragonglass into weapons, to make her a special dragonglass staff. When Gendry gives it to Arya, he tells her he is the bastard son of Robert Baratheon. Aware of their chances of dying in the upcoming battle and Arya wanting to experience sex, Arya and Gendry sleep together. Later that night, Arya hears the signal alerting her that the White Walkers' army has arrived.\\nArya fights in the battle against the dead with Sandor Clegane and Beric Dondarrion. Beric sacrifices himself to allow Arya and the Hound to escape the wights. A battered Arya sprints through the corridors of Winterfell and encounters Melisandre, who suggests to Arya that she is meant to kill the Night King. In the Godswood, just as the Night King is about to kill Bran, Arya sneaks up and stabs the Night King with the Valyrian steel dagger Bran gave her. Upon killing the Night King, the White Walkers and wights are all destroyed. \\nIn the aftermath of the battle, Arya is proposed to by Gendry, who had just been legitimised as a Baratheon by Daenerys. Arya declines, as she does not want the life of a lady. Sansa and Arya tell Jon they don't trust Daenerys, but Jon defends her. Arya learns that Jon is the son of her aunt, Lyanna Stark, and Rhaegar Targaryen after Jon swears her and Sansa to secrecy about his true parentage.\\nArya journeys south to King's Landing with the Hound to kill Cersei. The two infiltrate the Red Keep with the civilians Cersei is using to deter Daenerys' attack. Despite the city's surrender to Daenerys, she begins laying waste to the populace atop of Drogon. In his mission for revenge against his brother, the Mountain, the Hound seeks out the Mountain but urges Arya to leave and give up her quest for revenge to avoid a life consumed by it. Arya thanks the Hound, calling him by his name for the first time. She tries and fails to save the smallfolk, narrowly avoiding being incinerated in Daenerys' attack on the city, but survives. In the aftermath, Arya is reunited with Jon and warns him that he and the Starks are not safe from Daenerys. Jon tries but is unable to dissuade Daenerys from further destruction and ultimately assassinates her. He is imprisoned. Weeks later, Arya joins the other lords and ladies of Westeros in a council to decide who shall lead the Seven Kingdoms. Bran is chosen as king, though Arya abstains from voting as Sansa declares the North's independence. Arya, Sansa, and Bran bid Jon farewell as he is exiled. \\nArya reveals that she is leaving Westeros to see what lies west of the continent. She embarks on her voyage aboard a Stark ship.\n 2203 2d9538e229b8272de9b6f74bf8cdd270 \\n====Season 1====\\nArya accompanies her father Ned and her sister Sansa to King's Landing. Before their departure, Arya's half-brother Jon Snow gifts Arya a sword which she dubs \"Needle\". On the Kingsroad, Arya is sparring with a butcher's boy, Mycah, when Sansa's betrothed Prince Joffrey Baratheon attacks Mycah, prompting Arya's direwolf Nymeria to bite Joffrey. Arya shoos Nymeria away so she is not killed, but is furious when Sansa later refuses to support her version of events. Mycah is later killed by Joffrey's bodyguard Sandor \"The Hound\" Clegane, earning him Arya's hatred. Ned arranges for Arya to have sword lessons with the Braavosi Syrio Forel, who later defends her from Ser Meryn Trant after Joffrey ascends to the throne and kills the Stark household. Arya flees the Red Keep, accidentally killing a stable boy in her escape, hiding out as a beggar in the streets of King's Landing. Ned is eventually taken to the Great Sept of Baelor to face judgment; he spots Arya in the crowd, and alerts the Night's Watch recruiter Yoren to her presence. Yoren prevents Arya from witnessing Ned's execution and has her pose as a boy, \"Arry\", to avoid detection as she joins Yoren's recruits traveling north to Castle Black.\n 546 5719fd2f8b3bafdc028f1e043301cd05 \\n===''A Game of Thrones''===\\nSansa Stark begins the novel by being betrothed to Crown Prince Joffrey Baratheon, believing Joffrey to be a gallant prince. While Joffrey and Sansa are walking through the woods, Joffrey notices Arya sparring with the butcher's boy, Mycah. A fight breaks out and Joffrey is attacked by Nymeria (Arya's direwolf) after Joffrey threatens to hurt Arya. Sansa lies to King Robert about the circumstances of the fight in order to protect both Joffrey and her sister Arya. Since Arya ran off with her wolf to save it, Sansa's wolf is killed instead, estranging the Stark daughters.\\nDuring the Tourney of the Hand to honour her father Lord Eddard Stark, Sansa Stark is enchanted by the knights performing in the event. At the request of his mother, Queen Cersei Lannister, Joffrey spends a portion of the tourney with Sansa, but near the end he commands his guard Sandor Clegane, better known as The Hound, to take her back to her quarters. Sandor explains how his older brother, Gregor, aka \"Mountain that Rides\" pushed his face into a brazier of hot coals, for playing with one of his wooden toys.\\nAfter Eddard discovers the truth of Joffrey's paternity, he tells Sansa that they will be heading back to Winterfell. Sansa is devastated and wishes to stay in King's Landing, so she runs off to inform Queen Cersei of her father's plans, unwittingly providing Cersei with the information needed to arrest her father. After Robert dies, Sansa begs Joffrey to show mercy on her father and he agrees, if Ned will swear an oath of loyalty, but executes him anyway, in front of Sansa. Sansa is now effectively a hostage in King's Landing and finally sees Joffrey's true nature, after he forces her to look at the tarred head of her now-deceased father.\n 1435 54fa6e9a31fd8e0cac24b34d95085424 \\n===In Braavos===\\nLady Crane returns to her chambers to find a wounded Arya hiding inside, and helps stitch her wounds. She tells Arya that, thanks to her warning, she mutilated her would-be killer Bianca's face before kicking her out of the acting company. She then offers to have Arya join them, but she refuses, saying that she intends to travel west of Westeros to see the edge of the world. As Arya recovers, the Waif arrives and kills Lady Crane, intending to kill Arya as well. Arya flees through the streets of Braavos, but during the chase, Arya's wounds reopen and she limps back to her hideout with the Waif in pursuit. As the Waif closes in, Arya extinguishes the candle lighting the room; having trained while blinded for several weeks, Arya has the upper hand.\\nAt the House of Black and White, Jaqen follows a bloodtrail to the Hall of Faces, where he finds the Waif's face before being held at sword-point by Arya. Jaqen congratulates Arya for finally becoming No One. However, she rejects the title, asserting her identity as Arya Stark before turning and leaving, announcing that she is \"going home.\" Jaqen proudly watches on as she leaves.\n 460 f72a43a5163da9b8ffc2672df09099be \\n== Characters ==\\nThe tale is told through the eyes of 9 recurring POV characters plus one prologue POV character:\\n* Prologue: Maester Cressen, maester at Dragonstone\\n* Tyrion Lannister, youngest son of Lord Tywin Lannister, a dwarf and a brother to Queen Cersei, and the acting Hand of the King\\n* Lady Catelyn Stark, of House Tully, widow of Eddard Stark, Lord of Winterfell\\n* Ser Davos Seaworth, a smuggler turned knight in the service of King Stannis Baratheon, often called the Onion Knight\\n* Sansa Stark, eldest daughter of Eddard Stark and Catelyn Stark, held captive by Queen Cersei at King's Landing\\n* Arya Stark, youngest daughter of Eddard Stark and Catelyn Stark, missing and presumed dead\\n* Bran Stark, second son of Eddard Stark and Catelyn Stark and heir to Winterfell and the King in the North\\n* Jon Snow, bastard son of Eddard Stark, and a man of the Night's Watch\\n* Theon Greyjoy, heir to the Seastone Chair and former ward of Lord Eddard Stark\\n* Queen Daenerys Targaryen, the Unburnt and Mother of Dragons, of the Targaryen dynasty\n 2196 2d9538e229b8272de9b6f74bf8cdd270 \\n==== ''A Game of Thrones'' ====\\nArya adopts a direwolf cub, which she names Nymeria after a legendary warrior queen. She travels with her father, Eddard, to King's Landing when he is made Hand of the King. Before she leaves, her half-brother Jon Snow has a smallsword made for her as a parting gift, which she names \"Needle\" after her least favorite ladylike activity.\\nWhile taking a walk together, Prince Joffrey and her sister Sansa happen upon Arya and her friend, the low-born butcher apprentice Mycah, sparring in the woods with broomsticks. Arya defends Mycah from Joffrey's torments and her direwolf Nymeria helps Arya fight off Joffrey, wounding his arm in the process. Knowing that Nymeria will likely be killed in retribution, Arya chases her wolf away; but Sansa's direwolf Lady is killed in Nymeria's stead and Mycah is hunted down and killed by Sandor Clegane, Joffrey's bodyguard.\\nIn King's Landing, her father discovers Arya's possession of Needle, but instead of confiscating it he arranges for fencing lessons under the Braavosi swordmaster Syrio Forel, who teaches her the style of fighting known as \"water dancing\". After her father's arrest, Syrio is killed protecting her and Arya narrowly escapes capture. She later witnesses the public execution of her father before falling under the protection of the Night's Watch recruiter Yoren.\n 2209 2d9538e229b8272de9b6f74bf8cdd270 \\n====Season 7====\\nTaking the face of Walder Frey, Arya gathers the men of House Frey for a feast before killing them all with poisoned wine. Arya then journeys south, intending to travel to King's Landing to assassinate Cersei (now Queen of the Seven Kingdoms following the extinction of House Baratheon). However, Arya changes her mind after learning from Hot Pie that Jon has ousted House Bolton from Winterfell and has been crowned King in the North, and decides to return to her ancestral home. Along the way she encounters a wolf pack led by her long-lost direwolf Nymeria. Nymeria recognizes Arya, but she has grown feral and ignores Arya when she asks her to come North with her.\\nArriving at Winterfell, Arya finds that Jon has traveled to Dragonstone but is reunited with Sansa and Bran. Bran reveals his knowledge of Arya's kill list through greenseeing and presents her with a Valyrian steel dagger, which had been given to him by Littlefinger. Arya is also reunited with Brienne, who continues to serve the Starks, and manages to equal the female warrior during sparring despite her smaller size.\\nLittlefinger seeks to increase his influence on Sansa by driving a wedge between the Stark sisters. To this end, he allows Arya to witness him receiving a confidential message obtained from Maester Luwin's records. Arya breaks into Littlefinger's quarters to steal the message, which is a plea sent by Sansa following Ned's imprisonment to Robb imploring him to bend the knee to Joffrey. Outraged, Arya confronts Sansa and is unconvinced by her explanation that she did so to try and save Ned's life. Later, Arya catches Sansa looking at her collection of faces and threatens Sansa before leaving. Some time later, Sansa summons Arya to the great hall and begins an accusation of treason and murder; however, the accusation is directed towards Littlefinger, whose crimes have been discovered by Bran's greenseeing. Despite Littlefinger's pleas for mercy, Sansa sentences Littlefinger to death and Arya cuts his throat with the Valyrian steel dagger. The Stark sisters later resolve their differences, and acknowledge that the Starks must stay together to survive winter.\n 568 647298c3d183ab1dba03a447092e8763 \\n=== Arya Stark ===\\nArya Stark is the third child and younger daughter of Eddard and Catelyn Stark. She serves as a POV character for 33 chapters throughout ''A Game of Thrones'', ''A Clash of Kings'', ''A Storm of Swords'', ''A Feast for Crows'', and ''A Dance with Dragons''. So far she is the only character to appear in all 5 books as a POV character.\\nIn the HBO television adaptation, she is portrayed by Maisie Williams.\n 311 e7adfa870b0e451f0cacdab756e231e3 \\n===On the Kingsroad===\\nCity Watchmen search the caravan for Gendry but are turned away by Yoren. Gendry tells Arya Stark that he knows she is a girl, and she reveals she is actually Arya Stark after learning that her father met Gendry before he was executed.\n" ], [ "# prediction = pipe.run(query=\"Who created the Dothraki vocabulary?\", top_k_reader=5)\n# prediction = pipe.run(query=\"Who is the sister of Sansa?\", top_k_reader=5)", "_____no_output_____" ], [ "print_answers(prediction, details=\"minimal\")", "[ { 'answer': 'Eddard',\n 'context': 's Nymeria after a legendary warrior queen. She travels '\n \"with her father, Eddard, to King's Landing when he is made \"\n 'Hand of the King. Before she leaves,'},\n { 'answer': 'Ned',\n 'context': '\\n'\n '====Season 1====\\n'\n 'Arya accompanies her father Ned and her sister Sansa to '\n \"King's Landing. Before their departure, Arya's \"\n 'half-brother Jon Snow gifts A'},\n { 'answer': 'Lord Eddard and Catelyn Stark',\n 'context': 'k of House Stark is the younger daughter and third child '\n 'of Lord Eddard and Catelyn Stark of Winterfell. Ever the '\n 'tomboy, Arya would rather be trainin'},\n { 'answer': 'Lord Eddard Stark',\n 'context': 'ark daughters.\\n'\n 'During the Tourney of the Hand to honour her father Lord '\n 'Eddard Stark, Sansa Stark is enchanted by the knights '\n 'performing in the event.'},\n { 'answer': 'Robert Baratheon',\n 'context': 'hen Gendry gives it to Arya, he tells her he is the '\n 'bastard son of Robert Baratheon. Aware of their chances of '\n 'dying in the upcoming battle and Arya w'}]\n" ] ], [ [ "## About us\n\nThis [Haystack](https://github.com/deepset-ai/haystack/) notebook was made with love by [deepset](https://deepset.ai/) in Berlin, Germany\n\nWe bring NLP to the industry via open source! \nOur focus: Industry specific language models & large scale QA systems. \n \nSome of our other work: \n- [German BERT](https://deepset.ai/german-bert)\n- [GermanQuAD and GermanDPR](https://deepset.ai/germanquad)\n- [FARM](https://github.com/deepset-ai/FARM)\n\nGet in touch:\n[Twitter](https://twitter.com/deepset_ai) | [LinkedIn](https://www.linkedin.com/company/deepset-ai/) | [Slack](https://haystack.deepset.ai/community/join) | [GitHub Discussions](https://github.com/deepset-ai/haystack/discussions) | [Website](https://deepset.ai)\n\nBy the way: [we're hiring!](https://apply.workable.com/deepset/) ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
4a52c233be9ff71d1762d3f085461fb646f475cb
207,668
ipynb
Jupyter Notebook
1.Study/2. with computer/3.Deep_Learning_code/7. Tensorflow/5. CNN/3. CNN_Fashion-MNIST.ipynb
jskim0406/Study
07b559b95f8f658303ee53114107ae35940a6080
[ "MIT" ]
null
null
null
1.Study/2. with computer/3.Deep_Learning_code/7. Tensorflow/5. CNN/3. CNN_Fashion-MNIST.ipynb
jskim0406/Study
07b559b95f8f658303ee53114107ae35940a6080
[ "MIT" ]
null
null
null
1.Study/2. with computer/3.Deep_Learning_code/7. Tensorflow/5. CNN/3. CNN_Fashion-MNIST.ipynb
jskim0406/Study
07b559b95f8f658303ee53114107ae35940a6080
[ "MIT" ]
null
null
null
207,668
207,668
0.945788
[ [ [ "from tensorflow.keras.datasets.fashion_mnist import load_data\n\n(x_train, y_train), (x_test, y_test) = load_data()\nprint(x_train.shape, x_test.shape, y_train.shape, y_test.shape)\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\nnp.random.seed(777)\n\nclass_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n\nsample_size = 9\nrandom_idx = np.random.randint(60000, size=sample_size)\n\nfig = plt.figure(figsize=(5,5))\n\nfor i, idx in enumerate(random_idx):\n plt.subplot(3,3, i+1)\n plt.xticks([])\n plt.yticks([])\n plt.imshow(x_train[i], cmap='gray')\n plt.xlabel(class_names[y_train[i]])\nplt.style.use(\"seaborn\")\nplt.show()\n\n# valid dataset + normalization\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.3, random_state=777)\n\nx_train = np.reshape(x_train/255, (-1,28,28,1))\nx_val = np.reshape(x_val/255, (-1,28,28,1))\nx_test = np.reshape(x_test/255, (-1,28,28,1))\n\ny_train = to_categorical(y_train)\ny_val = to_categorical(y_val)\ny_test = to_categorical(y_test)", "(60000, 28, 28) (10000, 28, 28) (60000,) (10000,)\n" ], [ "from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten, Dense", "_____no_output_____" ], [ "# 모델 구성\nmodel = Sequential([\n # (conv - act - pool)\n Conv2D(filters=16, kernel_size=3, padding='same', activation='relu', input_shape=(28,28,1)), # MLP에서 첫 Input시, Flattened 된 상태로..\n MaxPool2D(pool_size=(2,2), strides=2, padding='same'),\n Conv2D(filters=32, kernel_size=3, padding='same', activation='relu',), \n MaxPool2D(pool_size=(2,2), strides=2, padding='same'),\n Conv2D(filters=64, kernel_size=3, padding='same', activation='relu',), \n MaxPool2D(pool_size=(2,2), strides=2, padding='same'),\n Flatten(),\n Dense(64, activation='relu'),\n Dense(10, activation='softmax')\n])", "_____no_output_____" ], [ "# compile, 학습과정 설정\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])\n\nhistory = model.fit(x_train, y_train, epochs=30, batch_size=128, validation_data=(x_val,y_val))", "Epoch 1/30\n329/329 [==============================] - 2s 6ms/step - loss: 0.6670 - acc: 0.7569 - val_loss: 0.4363 - val_acc: 0.8401\nEpoch 2/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.4025 - acc: 0.8561 - val_loss: 0.3605 - val_acc: 0.8691\nEpoch 3/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.3483 - acc: 0.8743 - val_loss: 0.3385 - val_acc: 0.8751\nEpoch 4/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.3055 - acc: 0.8884 - val_loss: 0.3038 - val_acc: 0.8943\nEpoch 5/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.2806 - acc: 0.8980 - val_loss: 0.2831 - val_acc: 0.8998\nEpoch 6/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.2623 - acc: 0.9037 - val_loss: 0.2890 - val_acc: 0.8939\nEpoch 7/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.2470 - acc: 0.9096 - val_loss: 0.2672 - val_acc: 0.9059\nEpoch 8/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.2305 - acc: 0.9167 - val_loss: 0.2586 - val_acc: 0.9070\nEpoch 9/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.2172 - acc: 0.9220 - val_loss: 0.2659 - val_acc: 0.9042\nEpoch 10/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.2066 - acc: 0.9250 - val_loss: 0.2615 - val_acc: 0.9054\nEpoch 11/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.1942 - acc: 0.9293 - val_loss: 0.2432 - val_acc: 0.9176\nEpoch 12/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.1866 - acc: 0.9325 - val_loss: 0.2442 - val_acc: 0.9151\nEpoch 13/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.1766 - acc: 0.9347 - val_loss: 0.2538 - val_acc: 0.9067\nEpoch 14/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.1675 - acc: 0.9383 - val_loss: 0.2496 - val_acc: 0.9138\nEpoch 15/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.1587 - acc: 0.9421 - val_loss: 0.2726 - val_acc: 0.9043\nEpoch 16/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.1442 - acc: 0.9476 - val_loss: 0.2460 - val_acc: 0.9128\nEpoch 17/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.1430 - acc: 0.9484 - val_loss: 0.2467 - val_acc: 0.9140\nEpoch 18/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.1311 - acc: 0.9524 - val_loss: 0.2424 - val_acc: 0.9193\nEpoch 19/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.1246 - acc: 0.9538 - val_loss: 0.2670 - val_acc: 0.9130\nEpoch 20/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.1135 - acc: 0.9588 - val_loss: 0.2684 - val_acc: 0.9164\nEpoch 21/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.1105 - acc: 0.9594 - val_loss: 0.3006 - val_acc: 0.9088\nEpoch 22/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.1035 - acc: 0.9619 - val_loss: 0.2812 - val_acc: 0.9156\nEpoch 23/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.1006 - acc: 0.9632 - val_loss: 0.2819 - val_acc: 0.9146\nEpoch 24/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.0889 - acc: 0.9680 - val_loss: 0.2944 - val_acc: 0.9178\nEpoch 25/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.0856 - acc: 0.9685 - val_loss: 0.3044 - val_acc: 0.9146\nEpoch 26/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.0819 - acc: 0.9699 - val_loss: 0.3036 - val_acc: 0.9133\nEpoch 27/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.0739 - acc: 0.9727 - val_loss: 0.3042 - val_acc: 0.9172\nEpoch 28/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.0720 - acc: 0.9735 - val_loss: 0.3181 - val_acc: 0.9099\nEpoch 29/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.0610 - acc: 0.9777 - val_loss: 0.3319 - val_acc: 0.9160\nEpoch 30/30\n329/329 [==============================] - 2s 5ms/step - loss: 0.0586 - acc: 0.9787 - val_loss: 0.3256 - val_acc: 0.9147\n" ], [ "hist_dict = history.history\nloss = hist_dict['loss']\nval_loss = hist_dict['val_loss']\n\nacc = hist_dict['acc']\nval_acc = hist_dict['val_acc']\n\nepochs = range(1, len(loss)+1)\n\nfig = plt.figure(figsize=(10,5))\n\n# loss 그리기\nax1 = fig.add_subplot(1,2,1)\nax1.plot(epochs, loss, color = 'blue', label = 'train_loss')\nax1.plot(epochs, val_loss, color = 'red', label = 'val_loss')\nax1.set_title(\"Loss per epoch(overfitted)\")\nax1.set_xlabel(\"epoch\")\nax1.set_ylabel(\"loss\")\nax1.legend()\n\n# acc 그리기\nax2 = fig.add_subplot(1,2,2)\nax2.plot(epochs, acc, color = 'blue', label = 'train_acc')\nax2.plot(epochs, val_acc, color = 'red', label = 'val_acc')\nax2.set_title(\"Acc per epoch(overfitted)\")\nax2.set_xlabel(\"epoch\")\nax2.set_ylabel(\"acc\")\nax2.legend()\n\nplt.style.use(\"seaborn\")\nplt.show()", "_____no_output_____" ], [ "model.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 28, 28, 16) 160 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 14, 14, 16) 0 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 14, 14, 32) 4640 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 7, 7, 32) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 7, 7, 64) 18496 \n_________________________________________________________________\nmax_pooling2d_2 (MaxPooling2 (None, 4, 4, 64) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 1024) 0 \n_________________________________________________________________\ndense (Dense) (None, 64) 65600 \n_________________________________________________________________\ndense_1 (Dense) (None, 10) 650 \n=================================================================\nTotal params: 89,546\nTrainable params: 89,546\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "from tensorflow.keras.utils import plot_model\nplot_model(model, './model.png', show_shapes=True)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
4a52db6eddd3305f276d3dcbddb567c13ee3b093
4,836
ipynb
Jupyter Notebook
ipynb/Germany-Rheinland-Pfalz-LK-Alzey-Worms.ipynb
skirienko/oscovida.github.io
eda5412d02365a8a000239be5480512c53bee8c2
[ "CC-BY-4.0" ]
null
null
null
ipynb/Germany-Rheinland-Pfalz-LK-Alzey-Worms.ipynb
skirienko/oscovida.github.io
eda5412d02365a8a000239be5480512c53bee8c2
[ "CC-BY-4.0" ]
null
null
null
ipynb/Germany-Rheinland-Pfalz-LK-Alzey-Worms.ipynb
skirienko/oscovida.github.io
eda5412d02365a8a000239be5480512c53bee8c2
[ "CC-BY-4.0" ]
null
null
null
29.668712
192
0.519024
[ [ [ "# Germany: LK Alzey-Worms (Rheinland-Pfalz)\n\n* Homepage of project: https://oscovida.github.io\n* Plots are explained at http://oscovida.github.io/plots.html\n* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Rheinland-Pfalz-LK-Alzey-Worms.ipynb)", "_____no_output_____" ] ], [ [ "import datetime\nimport time\n\nstart = datetime.datetime.now()\nprint(f\"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}\")", "_____no_output_____" ], [ "%config InlineBackend.figure_formats = ['svg']\nfrom oscovida import *", "_____no_output_____" ], [ "overview(country=\"Germany\", subregion=\"LK Alzey-Worms\", weeks=5);", "_____no_output_____" ], [ "overview(country=\"Germany\", subregion=\"LK Alzey-Worms\");", "_____no_output_____" ], [ "compare_plot(country=\"Germany\", subregion=\"LK Alzey-Worms\", dates=\"2020-03-15:\");\n", "_____no_output_____" ], [ "# load the data\ncases, deaths = germany_get_region(landkreis=\"LK Alzey-Worms\")\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/Germany-Rheinland-Pfalz-LK-Alzey-Worms.ipynb)\n- and wait (~1 to 2 minutes)\n- Then press SHIFT+RETURN to advance code cell to code cell\n- See http://jupyter.org for more details on how to use Jupyter Notebook", "_____no_output_____" ], [ "# Acknowledgements:\n\n- Johns Hopkins University provides data for countries\n- Robert Koch Institute provides data for within Germany\n- Atlo Team for gathering and providing data from Hungary (https://atlo.team/koronamonitor/)\n- Open source and scientific computing community for the data tools\n- Github for hosting repository and html files\n- Project Jupyter for the Notebook and binder service\n- The H2020 project Photon and Neutron Open Science Cloud ([PaNOSC](https://www.panosc.eu/))\n\n--------------------", "_____no_output_____" ] ], [ [ "print(f\"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and \"\n f\"deaths at {fetch_deaths_last_execution()}.\")", "_____no_output_____" ], [ "# to force a fresh download of data, run \"clear_cache()\"", "_____no_output_____" ], [ "print(f\"Notebook execution took: {datetime.datetime.now()-start}\")\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
4a52f275aa08caeb612fd7a273b4df78ebc6a786
190,519
ipynb
Jupyter Notebook
Base Network Quadratic Cost Function and L2 Regularization_Training data vs. max accuracy.ipynb
CalPolyPat/phys202-project
1b9612103797d84d4c10f5ee10f55776cb3d5222
[ "MIT" ]
null
null
null
Base Network Quadratic Cost Function and L2 Regularization_Training data vs. max accuracy.ipynb
CalPolyPat/phys202-project
1b9612103797d84d4c10f5ee10f55776cb3d5222
[ "MIT" ]
null
null
null
Base Network Quadratic Cost Function and L2 Regularization_Training data vs. max accuracy.ipynb
CalPolyPat/phys202-project
1b9612103797d84d4c10f5ee10f55776cb3d5222
[ "MIT" ]
null
null
null
580.85061
158,588
0.93261
[ [ [ "import numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nmatplotlib.style.use('ggplot')\nfrom mpl_toolkits.mplot3d import Axes3D\nimport IPython.html.widgets as widg\nfrom IPython.display import clear_output\nimport sys\n%matplotlib inline", ":0: FutureWarning: IPython widgets are experimental and may change in the future.\n" ], [ "class Network:\n def __init__(self, shape):\n self.shape = np.array(shape) #shape is array-like, i.e. (2,3,4) is a 2 input, 3 hidden node, 4 output network\n self.weights = [np.random.ranf((self.shape[i],self.shape[i-1]))*.1 for i in range(1,len(self.shape))]\n self.biases = [np.random.ranf((self.shape[i],))*.1 for i in range(1,len(self.shape))]\n self.errors = [np.random.ranf((self.shape[i],)) for i in range(1,len(self.shape))]\n self.eta = .2\n self.lam = .01\n def sigmoid(self, inputs):\n return 1/(1+np.exp(-inputs))\n def feedforward(self, inputs):\n assert inputs.shape==self.shape[0] #inputs must feed directly into the first layer.\n self.activation = [np.zeros((self.shape[i],)) for i in range(len(self.shape))]\n self.activation[0] = inputs\n for i in range(1,len(self.shape)):\n self.activation[i]=self.sigmoid(np.dot(self.weights[i-1],self.activation[i-1])+self.biases[i-1])\n return self.activation[-1]\n def comp_error(self, answer):\n assert answer.shape==self.activation[-1].shape\n self.errors[-1] = (self.activation[-1]-answer)*np.exp(np.dot(self.weights[-1],self.activation[-2])+self.biases[-1])/(np.exp(np.dot(self.weights[-1],self.activation[-2])+self.biases[-1])+1)**2\n for i in range(len(self.shape)-2, 0, -1):\n self.errors[i-1] = self.weights[i].transpose().dot(self.errors[i])*np.exp(np.dot(self.weights[i-1],self.activation[i-1])+self.biases[i-1])/(np.exp(np.dot(self.weights[i-1],self.activation[i-1])+self.biases[i-1])+1)**2\n def grad_descent(self):\n for i in range(len(self.biases)):\n self.biases[i]=self.biases[i]-self.eta*self.errors[i]\n for i in range(len(self.weights)):\n for j in range(self.weights[i].shape[0]):\n for k in range(self.weights[i].shape[1]):\n self.weights[i][j,k] = (1-self.eta*self.lam/1000)*self.weights[i][j,k] - self.eta*self.activation[i][k]*self.errors[i][j]\n def train(self, inputs, answer):\n self.feedforward(inputs)\n self.comp_error(answer)\n self.grad_descent()", "_____no_output_____" ], [ "n1 = Network([2,15,1])\nprint n1.feedforward(np.array([1,2]))\nfor i in range(1000):\n n1.train(np.array([1,200]), np.array([.5]))\nprint n1.feedforward(np.array([1,2]))", "[ 0.60766229]\n[ 0.51267858]\n" ], [ "from sklearn.datasets import load_digits\ndigits = load_digits()\nprint(digits.data[0]*.01)", "[ 0. 0. 0.05 0.13 0.09 0.01 0. 0. 0. 0. 0.13 0.15\n 0.1 0.15 0.05 0. 0. 0.03 0.15 0.02 0. 0.11 0.08 0. 0.\n 0.04 0.12 0. 0. 0.08 0.08 0. 0. 0.05 0.08 0. 0.\n 0.09 0.08 0. 0. 0.04 0.11 0. 0.01 0.12 0.07 0. 0.\n 0.02 0.14 0.05 0.1 0.12 0. 0. 0. 0. 0.06 0.13 0.1 0.\n 0. 0. ]\n" ], [ "iden = np.eye(10)\nacc = np.zeros((50,))\nnum = Network([64, 5, 10])\nprint num.feedforward(digits.data[89]*.01)\nfor i in range(50):\n for dig, ans in zip(digits.data[1:1000],digits.target[1:1000]):\n num.train(dig*.01,iden[ans])\n cor = 0\n for dig, ans in zip(digits.data, digits.target):\n if num.feedforward(dig*.01).argmax()==ans:\n cor += 1\n acc[i] = cor/float(len(digits.data))\nprint num.feedforward(digits.data[90]*.01), digits.target[90]", "[ 0.54114131 0.51659175 0.56711444 0.53051343 0.53188782 0.54929502\n 0.54569186 0.53265305 0.54667034 0.54503374]\n[ 1.64052258e-04 6.45932711e-01 4.64939649e-02 4.23163277e-02\n 1.47599511e-01 3.03545078e-02 1.26097215e-03 4.23561304e-01\n 9.66540964e-02 1.59261814e-02] 1\n" ], [ "plt.figure(figsize=(15,10))\nplt.plot(np.linspace(0,50,50),acc)", "_____no_output_____" ], [ "iden = np.eye(10)\nacc = np.zeros((1000,2000))\nf = plt.figure(figsize = (15,50))\nfor h in range(1, 101):\n num = Network([64, 14, 10])\n print str(((2000*(h-1))/(2000.*(100))))\n for i in range(2000):\n for dig, ans in zip(digits.data[1:h],digits.target[1:h]):\n num.train(dig*.01,iden[ans])\n cor = 0\n for dig, ans in zip(digits.data, digits.target):\n if num.feedforward(dig*.01).argmax()==ans:\n cor += 1\n acc[h-1,i] = cor/float(len(digits.data))\nnp.savetxt(\"Accuracy_Data_run_7_a.dat\", acc)", "_____no_output_____" ], [ "def plot_epochs(az_angle, eleva):\n fig = plt.figure(figsize=(15, 10))\n ax = fig.add_subplot(111, projection='3d')\n X, Y = np.meshgrid(np.linspace(0,2000,2000), np.linspace(8,14, 7))\n ax.plot_surface(X, Y, acc)\n ax.view_init(elev=eleva, azim=az_angle)", "_____no_output_____" ], [ "widg.interact(plot_epochs, az_angle=(0, 360, 1), eleva=(0,20,1))", "_____no_output_____" ], [ "print acc\n", "[[ 0.10183639 0.10183639 0.10183639 ..., 0.97161937 0.97161937\n 0.97161937]\n [ 0.10183639 0.10183639 0.10183639 ..., 0.97328881 0.97328881\n 0.97328881]\n [ 0.10183639 0.10183639 0.10183639 ..., 0.97217585 0.97217585\n 0.97217585]\n ..., \n [ 0.10183639 0.10183639 0.10183639 ..., 0.96939343 0.96939343\n 0.96939343]\n [ 0.10183639 0.10183639 0.10183639 ..., 0.97273233 0.97273233\n 0.97273233]\n [ 0.10183639 0.10183639 0.10183639 ..., 0.97106288 0.97106288\n 0.97106288]]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a52f43498ff745d5e680bd4ca0c1631657db870
18,186
ipynb
Jupyter Notebook
cv_hmdd_4s_proposed_gap.ipynb
iamsoroush/DeepEEGAbstractor
3b83570b8edca63a0132b98729cd7e5f4a9d355c
[ "MIT" ]
1
2022-03-11T05:52:18.000Z
2022-03-11T05:52:18.000Z
cv_hmdd_4s_proposed_gap.ipynb
iamsoroush/DeepEEGAbstractor
3b83570b8edca63a0132b98729cd7e5f4a9d355c
[ "MIT" ]
null
null
null
cv_hmdd_4s_proposed_gap.ipynb
iamsoroush/DeepEEGAbstractor
3b83570b8edca63a0132b98729cd7e5f4a9d355c
[ "MIT" ]
null
null
null
37.966597
250
0.404652
[ [ [ "<a href=\"https://colab.research.google.com/github/iamsoroush/DeepEEGAbstractor/blob/master/cv_hmdd_4s_proposed_gap.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "#@title # Clone the repository and upgrade Keras {display-mode: \"form\"}\n\n!git clone https://github.com/iamsoroush/DeepEEGAbstractor.git\n!pip install --upgrade keras", "_____no_output_____" ], [ "#@title # Imports {display-mode: \"form\"}\n\nimport os\nimport pickle\nimport sys\nsys.path.append('DeepEEGAbstractor')\n\nimport numpy as np\n\nfrom src.helpers import CrossValidator\nfrom src.models import SpatioTemporalWFB, TemporalWFB, TemporalDFB, SpatioTemporalDFB\nfrom src.dataset import DataLoader, Splitter, FixedLenGenerator\n\nfrom google.colab import drive\ndrive.mount('/content/gdrive')", "_____no_output_____" ], [ "#@title # Set data path {display-mode: \"form\"}\n\n#@markdown ---\n#@markdown Type in the folder in your google drive that contains numpy _data_ folder:\n\nparent_dir = 'soroush'#@param {type:\"string\"}\ngdrive_path = os.path.abspath(os.path.join('gdrive/My Drive', parent_dir))\ndata_dir = os.path.join(gdrive_path, 'data')\ncv_results_dir = os.path.join(gdrive_path, 'cross_validation')\nif not os.path.exists(cv_results_dir):\n os.mkdir(cv_results_dir)\n\nprint('Data directory: ', data_dir)\nprint('Cross validation results dir: ', cv_results_dir)", "_____no_output_____" ], [ "#@title ## Set Parameters\n\nbatch_size = 80\nepochs = 50\nk = 10\nt = 10\ninstance_duration = 4 #@param {type:\"slider\", min:3, max:10, step:0.5}\ninstance_overlap = 1 #@param {type:\"slider\", min:0, max:3, step:0.5}\nsampling_rate = 256 #@param {type:\"number\"}\nn_channels = 20 #@param {type:\"number\"}\ntask = 'hmdd'\ndata_mode = 'cross_subject'", "_____no_output_____" ], [ "#@title ## Spatio-Temporal WFB\n\nmodel_name = 'ST-WFB-GAP'\n\ntrain_generator = FixedLenGenerator(batch_size=batch_size,\n duration=instance_duration,\n overlap=instance_overlap,\n sampling_rate=sampling_rate,\n is_train=True)\n\ntest_generator = FixedLenGenerator(batch_size=8,\n duration=instance_duration,\n overlap=instance_overlap,\n sampling_rate=sampling_rate,\n is_train=False)\n\nparams = {'task': task,\n 'data_mode': data_mode,\n 'main_res_dir': cv_results_dir,\n 'model_name': model_name,\n 'epochs': epochs,\n 'train_generator': train_generator,\n 'test_generator': test_generator,\n 't': t,\n 'k': k,\n 'channel_drop': True}\n\nvalidator = CrossValidator(**params)\n\ndataloader = DataLoader(data_dir,\n task,\n data_mode,\n sampling_rate,\n instance_duration,\n instance_overlap)\ndata, labels = dataloader.load_data()\n\ninput_shape = (sampling_rate * instance_duration,\n n_channels)\n\nmodel_obj = SpatioTemporalWFB(input_shape,\n model_name=model_name)\n\nscores = validator.do_cv(model_obj,\n data,\n labels)", "_____no_output_____" ], [ "#@title ## Temporal WFB\n\nmodel_name = 'T-WFB-GAP'\n\ntrain_generator = FixedLenGenerator(batch_size=batch_size,\n duration=instance_duration,\n overlap=instance_overlap,\n sampling_rate=sampling_rate,\n is_train=True)\n\ntest_generator = FixedLenGenerator(batch_size=8,\n duration=instance_duration,\n overlap=instance_overlap,\n sampling_rate=sampling_rate,\n is_train=False)\n\nparams = {'task': task,\n 'data_mode': data_mode,\n 'main_res_dir': cv_results_dir,\n 'model_name': model_name,\n 'epochs': epochs,\n 'train_generator': train_generator,\n 'test_generator': test_generator,\n 't': t,\n 'k': k,\n 'channel_drop': True}\n\nvalidator = CrossValidator(**params)\n\ndataloader = DataLoader(data_dir,\n task,\n data_mode,\n sampling_rate,\n instance_duration,\n instance_overlap)\ndata, labels = dataloader.load_data()\n\ninput_shape = (sampling_rate * instance_duration,\n n_channels)\n\nmodel_obj = TemporalWFB(input_shape,\n model_name=model_name)\n\nscores = validator.do_cv(model_obj,\n data,\n labels)", "_____no_output_____" ], [ "#@title ## Spatio-Temporal DFB\n\nmodel_name = 'ST-DFB-GAP'\n\ntrain_generator = FixedLenGenerator(batch_size=batch_size,\n duration=instance_duration,\n overlap=instance_overlap,\n sampling_rate=sampling_rate,\n is_train=True)\n\ntest_generator = FixedLenGenerator(batch_size=8,\n duration=instance_duration,\n overlap=instance_overlap,\n sampling_rate=sampling_rate,\n is_train=False)\n\nparams = {'task': task,\n 'data_mode': data_mode,\n 'main_res_dir': cv_results_dir,\n 'model_name': model_name,\n 'epochs': epochs,\n 'train_generator': train_generator,\n 'test_generator': test_generator,\n 't': t,\n 'k': k,\n 'channel_drop': True}\n\nvalidator = CrossValidator(**params)\n\ndataloader = DataLoader(data_dir,\n task,\n data_mode,\n sampling_rate,\n instance_duration,\n instance_overlap)\ndata, labels = dataloader.load_data()\n\ninput_shape = (sampling_rate * instance_duration,\n n_channels)\n\nmodel_obj = SpatioTemporalDFB(input_shape,\n model_name=model_name)\n\nscores = validator.do_cv(model_obj,\n data,\n labels)", "_____no_output_____" ], [ "#@title ## Spatio-Temporal DFB (Normalized Kernels)\n\nmodel_name = 'ST-DFB-NK-GAP'\n\ntrain_generator = FixedLenGenerator(batch_size=batch_size,\n duration=instance_duration,\n overlap=instance_overlap,\n sampling_rate=sampling_rate,\n is_train=True)\n\ntest_generator = FixedLenGenerator(batch_size=8,\n duration=instance_duration,\n overlap=instance_overlap,\n sampling_rate=sampling_rate,\n is_train=False)\n\nparams = {'task': task,\n 'data_mode': data_mode,\n 'main_res_dir': cv_results_dir,\n 'model_name': model_name,\n 'epochs': epochs,\n 'train_generator': train_generator,\n 'test_generator': test_generator,\n 't': t,\n 'k': k,\n 'channel_drop': True}\n\nvalidator = CrossValidator(**params)\n\ndataloader = DataLoader(data_dir,\n task,\n data_mode,\n sampling_rate,\n instance_duration,\n instance_overlap)\ndata, labels = dataloader.load_data()\n\ninput_shape = (sampling_rate * instance_duration,\n n_channels)\n\nmodel_obj = SpatioTemporalDFB(input_shape,\n model_name=model_name,\n normalize_kernels=True)\n\nscores = validator.do_cv(model_obj,\n data,\n labels)", "_____no_output_____" ], [ "#@title ## Temporal DFB\n\nmodel_name = 'T-DFB-GAP'\n\ntrain_generator = FixedLenGenerator(batch_size=batch_size,\n duration=instance_duration,\n overlap=instance_overlap,\n sampling_rate=sampling_rate,\n is_train=True)\n\ntest_generator = FixedLenGenerator(batch_size=8,\n duration=instance_duration,\n overlap=instance_overlap,\n sampling_rate=sampling_rate,\n is_train=False)\n\nparams = {'task': task,\n 'data_mode': data_mode,\n 'main_res_dir': cv_results_dir,\n 'model_name': model_name,\n 'epochs': epochs,\n 'train_generator': train_generator,\n 'test_generator': test_generator,\n 't': t,\n 'k': k,\n 'channel_drop': True}\n\nvalidator = CrossValidator(**params)\n\ndataloader = DataLoader(data_dir,\n task,\n data_mode,\n sampling_rate,\n instance_duration,\n instance_overlap)\ndata, labels = dataloader.load_data()\n\ninput_shape = (sampling_rate * instance_duration,\n n_channels)\n\nmodel_obj = TemporalDFB(input_shape,\n model_name=model_name)\n\nscores = validator.do_cv(model_obj,\n data,\n labels)", "_____no_output_____" ], [ "#@title ## Temporal DFB (Normalized Kernels)\n\nmodel_name = 'T-DFB-NK-GAP'\n\ntrain_generator = FixedLenGenerator(batch_size=batch_size,\n duration=instance_duration,\n overlap=instance_overlap,\n sampling_rate=sampling_rate,\n is_train=True)\n\ntest_generator = FixedLenGenerator(batch_size=8,\n duration=instance_duration,\n overlap=instance_overlap,\n sampling_rate=sampling_rate,\n is_train=False)\n\nparams = {'task': task,\n 'data_mode': data_mode,\n 'main_res_dir': cv_results_dir,\n 'model_name': model_name,\n 'epochs': epochs,\n 'train_generator': train_generator,\n 'test_generator': test_generator,\n 't': t,\n 'k': k,\n 'channel_drop': True}\n\nvalidator = CrossValidator(**params)\n\ndataloader = DataLoader(data_dir,\n task,\n data_mode,\n sampling_rate,\n instance_duration,\n instance_overlap)\ndata, labels = dataloader.load_data()\n\ninput_shape = (sampling_rate * instance_duration,\n n_channels)\n\nmodel_obj = TemporalDFB(input_shape,\n model_name=model_name,\n normalize_kernels=True)\n\nscores = validator.do_cv(model_obj,\n data,\n labels)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a52f9f811d9f0a329d9236f40c5211c16e998c2
7,477
ipynb
Jupyter Notebook
02 - Installing the necessities for Part 1 of the course.ipynb
AccordionGuy/JavaScript-Course-2020
5dd847ee5da44dbeb1a1af962575d47a9899ddd4
[ "BSD-3-Clause" ]
null
null
null
02 - Installing the necessities for Part 1 of the course.ipynb
AccordionGuy/JavaScript-Course-2020
5dd847ee5da44dbeb1a1af962575d47a9899ddd4
[ "BSD-3-Clause" ]
null
null
null
02 - Installing the necessities for Part 1 of the course.ipynb
AccordionGuy/JavaScript-Course-2020
5dd847ee5da44dbeb1a1af962575d47a9899ddd4
[ "BSD-3-Clause" ]
null
null
null
48.23871
356
0.642771
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4a53024b487c8c6d6857b9a93510fe8939a2c4d6
4,419
ipynb
Jupyter Notebook
index.ipynb
Varunvaruns9/einsteinpy
befc0879c65a53b811e7d6a9ec47675ae28a08c5
[ "MIT" ]
1
2019-03-08T16:13:56.000Z
2019-03-08T16:13:56.000Z
index.ipynb
Varunvaruns9/einsteinpy
befc0879c65a53b811e7d6a9ec47675ae28a08c5
[ "MIT" ]
null
null
null
index.ipynb
Varunvaruns9/einsteinpy
befc0879c65a53b811e7d6a9ec47675ae28a08c5
[ "MIT" ]
1
2022-03-19T18:46:13.000Z
2022-03-19T18:46:13.000Z
49.1
222
0.728898
[ [ [ "# Gallery of examples\n\n![logo_text.png](docs/source/_static/EinsteinPy_trans.png)\n\nHere you can browse a gallery of examples using EinsteinPy in the form of Jupyter notebooks.", "_____no_output_____" ], [ "## [Visualizing advance of perihelion of a test particle in Schwarzschild space-time](docs/source/examples/Visualizing_advance_of_perihelion_of_a_test_particle_in_Schwarzschild_space-time.ipynb)\n\n[![orbit](docs/source/examples/perihelion_advance.png)](docs/source/examples/Visualizing_advance_of_perihelion_of_a_test_particle_in_Schwarzschild_space-time.ipynb)\n\n## [Animations in EinsteinPy](docs/source/examples/Animations_in_EinsteinPy.ipynb)\n\n[![animation](docs/source/examples/scatter_animation.gif)](docs/source/examples/Animations_in_EinsteinPy.ipynb)\n\n## [Analysing Earth using EinsteinPy!](docs/source/examples/Analysing_Earth_using_EinsteinPy!.ipynb)\n\n[![orbit](docs/source/examples/earth.png)](docs/source/examples/Analysing_Earth_using_EinsteinPy!.ipynb)\n\n## [Symbolically Understanding Christoffel Symbol and Riemann Metric Tensor using EinsteinPy](docs/source/examples/Symbolically_Understanding_Christoffel_Symbol_and_Riemann_Curvature_Tensor_using_EinsteinPy.ipynb)\n\n[![symbol](docs/source/examples/symbol.png)](docs/source/examples/Symbolically_Understanding_Christoffel_Symbol_and_Riemann_Curvature_Tensor_using_EinsteinPy.ipynb)\n\n## [Visualizing frame dragging in Kerr spacetime](docs/source/examples/Visualizing_frame_dragging_in_Kerr_spacetime.ipynb)\n\n[![drag](docs/source/examples/drag.png)](docs/source/examples/Visualizing_frame_dragging_in_Kerr_spacetime.ipynb)\n\n## [Visualizing event horizon and ergosphere of Kerr black hole](docs/source/examples/Visualizing_event_horizon_and_ergosphere_of_Kerr_black_hole.ipynb)\n\n[![orbit](docs/source/examples/kerrblackhole.png)](docs/source/examples/Visualizing_event_horizon_and_ergosphere_of_Kerr_black_hole.ipynb)\n\n\n## [Spatial Hypersurface Embedding for Schwarzschild Space-Time!](docs/source/examples/Plotting_spacial_hypersurface_embedding_for_schwarzschild_spacetime.ipynb)\n\n[![orbit](docs/source/examples/hypersurface_surface.png)](docs/source/examples/Plotting_spacial_hypersurface_embedding_for_schwarzschild_spacetime.ipynb)\n\n\n## [Playing with Contravariant and Covariant Indices in Tensors(Symbolic)](docs/source/examples/Playing_with_Contravariant_and_Covariant_Indices_in_Tensors(Symbolic).ipynb)\n\n[![orbit](docs/source/examples/contravariant_symbolic.png)](docs/source/examples/Playing_with_Contravariant_and_Covariant_Indices_in_Tensors(Symbolic).ipynb)\n\n## [Ricci Tensor and Scalar Curvature calculations using Symbolic module](docs/source/examples/Ricci_Tensor_and_Scalar_Curvature_symbolic_calculation.ipynb)\n\n[![symbol](docs/source/examples/GregorioRicciCurbastro.jpg)](docs/source/examples/Ricci_Tensor_and_Scalar_Curvature_symbolic_calculation.ipynb)\n<center><em>Gregorio Ricci-Curbastro</em></center>\n\n## [Weyl Tensor calculations using Symbolic module](docs/source/examples/Weyl_Tensor_symbolic_calculation.ipynb)\n\n[![symbol](docs/source/examples/HermannWeyl.jpeg)](docs/source/examples/Weyl_Tensor_symbolic_calculation.ipynb)\n<center><em>Hermann Weyl</em></center>\n\n## [Eisntein Tensor calculations using Symbolic module](docs/source/examples/Einstein_Tensor_symbolic_calculation.ipynb)\n\n[![symbol](docs/source/examples/einstein.png)](docs/source/examples/Einstein_Tensor_symbolic_calculation.ipynb)", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown" ] ]
4a53174bc3c2687b7b6d3bf18bc6b9afea90359f
202,474
ipynb
Jupyter Notebook
project4_stackoverflow.ipynb
asunaidi/stack-overflow-survey
6022223c2d856127093ce7fcf13126c660b9dd0d
[ "FTL", "CNRI-Python" ]
null
null
null
project4_stackoverflow.ipynb
asunaidi/stack-overflow-survey
6022223c2d856127093ce7fcf13126c660b9dd0d
[ "FTL", "CNRI-Python" ]
null
null
null
project4_stackoverflow.ipynb
asunaidi/stack-overflow-survey
6022223c2d856127093ce7fcf13126c660b9dd0d
[ "FTL", "CNRI-Python" ]
null
null
null
85.21633
18,964
0.748185
[ [ [ "# Project4 : Stackworkflow Survey Results\n", "_____no_output_____" ], [ "### Import necessary libraries\n", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ] ], [ [ "### Load the data", "_____no_output_____" ] ], [ [ "# Load in the Stackoverflow survey results.\nsurvey_results = pd.read_csv('survey_results_public.csv')\n\n# Load in the survey questions file.\nfeat_info = pd.read_csv('survey_results_schema.csv')", "_____no_output_____" ], [ "#data dimensions\nn_rows,n_cols = survey_results.shape\nprint(\"Total number of participants: {} for {} questions\".format(n_rows,n_cols))", "Total number of participants: 51392 for 154 questions\n" ], [ "#take a look at how the data look like\nsurvey_results.head()", "_____no_output_____" ], [ "#plot top unique values against their percentages\ndef plot_percentages(stat):\n if stat.shape[0] > 10:\n plt.barh(stat.iloc[0:9, 0], stat.iloc[0:9, 2])\n else:\n plt.barh(stat.iloc[:, 0], stat.iloc[:, 2])\n \n\n\n# a function to view for a given feature, the count and percentage of each value \n# the feature here should be a question where multiple selection is not allowed\ndef feature_stat_single(feature_name, df):\n feature_value_counts = df[feature_name].value_counts().reset_index()\n feature_value_counts.rename(columns={'index': feature_name, feature_name: 'count'}, inplace=True)\n feature_value_counts['percentage'] = feature_value_counts['count']/np.sum(feature_value_counts['count']) * 100\n plot_percentages(feature_value_counts)\n display(feature_value_counts)\n return feature_value_counts\n \n# a function to view for a given feature, the count and percentage of each value \n# the feature here should be a question where multiple selection is allowed\ndef feature_stats_multiple(feature_name, df):\n n_participants = df.shape[0]\n df[feature_name] = df[feature_name].str.split('; ')\n all_values = np.hstack(df[feature_name])\n #remove missing values as the propotion of the missing values differes among different sub-groups like students/professionals\n #so this difference will mess up the comparison between them\n all_values = all_values[~(all_values=='nan')]\n all_values = pd.Series(all_values).value_counts().reset_index()\n all_values.rename(columns={'index': feature_name, 0: 'count'}, inplace=True)\n all_values['percentage'] = all_values['count']/n_participants * 100\n plot_percentages(all_values)\n display(all_values)\n return all_values\n\n\npd.options.mode.chained_assignment = None", "_____no_output_____" ] ], [ [ "### There are many quesions I'm interested to see how the Sack Overflow data would answer:\n### Q1: Are the languages used in industry by professional developers being taught in universities? In other words: Do universities teach students useful materials to prepare them for their future careers as developers?", "_____no_output_____" ] ], [ [ "#let's start by investigating the distribution of the participants' profession\nprofession_stat = feature_stat_single('Professional', survey_results);", "_____no_output_____" ], [ "#although we have much fewer students than professional developers, the number of students is high enough to answer the question\n#so now I will create two dataframes, one for students, and the other of professional developers\n\nprofessional=survey_results[survey_results['Professional']=='Professional developer']\nstudents=survey_results[survey_results['Professional']=='Student']", "_____no_output_____" ], [ "#now let's check the employment status of students to make sure that we take into account employed students\nstud_emp = feature_stat_single('EmploymentStatus', students);", "_____no_output_____" ], [ "#as seen above, almost have of the students are either working for a company or independently so it would be interesting to \n#make a languages-comparison between employed students and not employed students\nstud_not_employed= students[students['EmploymentStatus'].isin(['Not employed, and not looking for work','Not employed, but looking for work'])]\nstud_employed= students[students['EmploymentStatus'].isin(['Employed full-time','Employed part-time', 'Independent contractor, freelancer, or self-employed'])]\n", "_____no_output_____" ], [ "feature_stats_multiple('HaveWorkedLanguage', stud_not_employed);", "_____no_output_____" ], [ "#note that the percentages won't add up to 100 as each participant was allowed to choose multiple languages\nfeature_stats_multiple('HaveWorkedLanguage', stud_employed);", "_____no_output_____" ] ], [ [ "comparing the languages used by employed students and un-employed students: \n- the most common language used is the same at both of them: Java. I was expecting this result as universities tend to use Java to teach object-oriented programming to students.\n- there is a clear difference in the percentages of using Javascript and SQL. These two languages are more popular ampong employed students as they are widely used in indstry. SQL is needed to interact with database and it's really hard to find a company without a database. On the other hand, most un-employed students would not necessarily have access to a database. Javascript is an essential language for web development which is mostly what you will end up doing at somepoint as a professional developer in the industry and even elementary schools need websites nowadays.\n", "_____no_output_____" ] ], [ [ "#I want to check out the employment status of professional developers to remove the unemployed ones jsut to make sure they \n#won't affect the comparsion\nprof_emp = feature_stat_single('EmploymentStatus', professional);", "_____no_output_____" ], [ "#as seen above, most of professional are employed, I will keep the first three highest values and remove the rest\nprof_employed= professional[professional['EmploymentStatus'].isin(['Employed full-time','Employed part-time', 'Independent contractor, freelancer, or self-employed'])]", "_____no_output_____" ], [ "feature_stats_multiple('HaveWorkedLanguage', prof_employed);", "_____no_output_____" ] ], [ [ "comparing the languages used by employed professional developers and un-employed students: \n- the number of different languages used in both groups is the same but the percentage of the language usage differes.\n- the differences I mentioned in the earlier comparison above can be seen even clearer here: Javascript and SQL is used 20% more by developers in industry than it's used among univirsity students. I personally think we should pay more attention to these languages as they're more likely to be required in students' future careers.", "_____no_output_____" ], [ "### Q2: I heard in many occasions people saying that it's better to work in a small company as it makes you feel more included and it allows you to handle important projects all by yourself and see the results of your work directly in front of your eyes which is something you won't necessarily get when working for a big company. I also heard other people saying that it's more secure to work in big companies because of their resources. Can this dataset prove any of these rumors?", "_____no_output_____" ] ], [ [ "#to start answering this question, let's explore the the company size column\nfeature_stat_single('CompanySize', survey_results);", "_____no_output_____" ], [ "# from the above distribution, it seems like we have a wide variety of sizes in the data\n# the main focus here is to see the impact of the company size on job satisfaction and salary\n# hence, I will check the availability of the data in the target columns and view the distribution again\nprint('number of missing values in Salary column: {}'.format(survey_results['Salary'].isna().sum()))\ndisplay(survey_results[(pd.isnull(survey_results['Salary']))].EmploymentStatus.unique())\nprint('number of missing values in Career Satisfaction column: {}'.format(survey_results['CareerSatisfaction'].isna().sum()))\nprint('number of missing values in Job Satisfaction column: {}'.format(survey_results['JobSatisfaction'].isna().sum()))", "number of missing values in Salary column: 38501\n" ], [ "#I will divide the company size based on Salary as it's the column that has the highest number of missing data\n#there are a lot of missing data for the salary column which is totally understandable as some participants are not employed\n#and salary is also a sensitive information that not everyone is willing to share\n#to answer the second question, I will take a subset of the data where missing values of salary are removed\nsalary_clean = survey_results[~(pd.isnull(survey_results['Salary']))]\n#show a histogram of the salary column\nplt.hist(salary_clean['Salary'], bins=50)\nplt.xlabel('Salary')\nplt.ylabel('Frequency')\nplt.grid(True)\nplt.show()", "_____no_output_____" ], [ "# we have 0 as a value here which maybe due to the vlounteering work or maybe to the fact that not eveyone would \n# necessarily provide the true information, I will print the number of participants who reported that they\n# recieve less than 50 annually\nprint('number of low values in Salary column: {}'.format( survey_results[survey_results['Salary'] < 50].shape[0] ))\n", "number of low values in Salary column: 51\n" ], [ "#I decided not to remove the low salary values as they might indicate something and they are not a lot anyways.\n# After removing a big amount of data, it's good review the histogram of company size again\nfeature_stat_single('CompanySize', salary_clean);", "_____no_output_____" ], [ "# Now, I will divide the companies into 3 categories based on the company size and availability of data as follows: \n# small companies: [1, 99]\n# medium companies: [100, 999]\n# big companies: [999 or more]\n# for salary & career/job satisfaction \nbig_company_salary =salary_clean[salary_clean['CompanySize'].isin(['1,000 to 4,999 employees', '5,000 to 9,999 employees', '10,000 or more employees'])]\nbig_company_salary_mean = round(big_company_salary['Salary'].mean(),2)\nmedium_company_salary =salary_clean[salary_clean['CompanySize'].isin(['100 to 499 employees', '500 to 999 employees'])]\nmedium_company_salary_mean = round(medium_company_salary['Salary'].mean(),2)\nsmall_company_salary =salary_clean[salary_clean['CompanySize'].isin(['Fewer than 10 employees', '10 to 19 employees', '20 to 99 employees'])]\nsmall_company_salary_mean = round(small_company_salary['Salary'].mean(),2)", "_____no_output_____" ], [ "# I will use the same above categories for job/career satisfaction after missing data removal\ncareerSatisfaction_clean = survey_results[~(pd.isnull(survey_results['CareerSatisfaction']))]\nbig_company_careerSat =careerSatisfaction_clean[careerSatisfaction_clean['CompanySize'].isin(['1,000 to 4,999 employees', '5,000 to 9,999 employees', '10,000 or more employees'])]\nbig_company_careerSat_mean = round(big_company_careerSat['CareerSatisfaction'].mean(),2)\nmedium_company_careerSat =careerSatisfaction_clean[careerSatisfaction_clean['CompanySize'].isin(['100 to 499 employees', '500 to 999 employees'])]\nmedium_company_careerSat_mean = round(medium_company_careerSat['CareerSatisfaction'].mean(),2)\nsmall_company_careerSat =careerSatisfaction_clean[careerSatisfaction_clean['CompanySize'].isin(['Fewer than 10 employees', '10 to 19 employees', '20 to 99 employees'])]\nsmall_company_careerSat_mean = round(small_company_careerSat['CareerSatisfaction'].mean(),2)", "_____no_output_____" ], [ "jobSatisfaction_clean = survey_results[~(pd.isnull(survey_results['JobSatisfaction']))]\nbig_company_jobSat =jobSatisfaction_clean[jobSatisfaction_clean['CompanySize'].isin(['1,000 to 4,999 employees', '5,000 to 9,999 employees', '10,000 or more employees'])]\nbig_company_jobSat_mean = round(big_company_jobSat['JobSatisfaction'].mean(),2)\nmedium_company_jobSat =jobSatisfaction_clean[jobSatisfaction_clean['CompanySize'].isin(['100 to 499 employees', '500 to 999 employees'])]\nmedium_company_jobSat_mean = round(medium_company_jobSat['JobSatisfaction'].mean(),2)\nsmall_company_jobSat =jobSatisfaction_clean[jobSatisfaction_clean['CompanySize'].isin(['Fewer than 10 employees', '10 to 19 employees', '20 to 99 employees'])]\nsmall_company_jobSat_mean = round(small_company_jobSat['JobSatisfaction'].mean(),2)", "_____no_output_____" ], [ "comparison = np.array([['','Salary','Job Satisfaction', 'Career Satisfaction'],\n ['Small Companies',small_company_salary_mean,small_company_jobSat_mean, small_company_careerSat_mean],\n ['Medium Companies',medium_company_salary_mean,medium_company_jobSat_mean,medium_company_careerSat_mean],\n ['Big Companies',big_company_salary_mean,big_company_jobSat_mean,big_company_careerSat_mean]])\n \ncomparison_df = pd.DataFrame(data=comparison[1:,1:],index=comparison[1:,0],columns=comparison[0,1:])\n\nprint(comparison_df)", " Salary Job Satisfaction Career Satisfaction\nSmall Companies 47675.31 6.98 7.33\nMedium Companies 57665.93 6.92 7.39\nBig Companies 68496.75 6.83 7.37\n" ] ], [ [ "- from the comparison above, we can see that almost all company types' employees have similar average value of career satisfaction. On the other hand, Big companies' employees are almost 0.1 les statisfied in their job compared to the other 2 categories. \n- There is a clear difference in salaries between big, medium and small companies where big companies pay the highest average salary to their employees which proves the security people talk about.", "_____no_output_____" ], [ "### Q3: What are the strongest motivations behind people leaving their coding job?", "_____no_output_____" ] ], [ [ "#There are some questions the participants were asked when they answered that they used to work beofre \n#as a programmer but they no longer do. I will print out all the questions below\nprint('You said before that you used to code as part of your job, but no longer do. To what extent do you agree or disagree with the following statements?')\nleaving_coding_job_cols = np.array(['ExCoderReturn', 'ExCoderNotForMe', 'ExCoderBalance', 'ExCoder10Years', 'ExCoderBelonged', 'ExCoderSkills','ExCoderWillNotCode', 'ExCoderActive'])\nfor col in leaving_coding_job_cols:\n print('- '+feat_info[feat_info.Column == col]['Question'].values[0][147:])", "You said before that you used to code as part of your job, but no longer do. To what extent do you agree or disagree with the following statements?\n- If money weren't an issue, I would take a coding job again\n- Working as a developer just wasn't for me\n- I have better work-life balance now than I did as a developer\n- My career is going the way I thought it would 10 years ago\n- When I was a developer, I didn't feel like I belonged with my colleagues\n- I don't think my coding skills are up to date\n- I probably won't code for a living ever again\n- I'm still active in the developer community\n" ], [ "#since only the people whe left a developer job would get those questions, we will definitely find missing values\n#I'll print now the values distribution of one of those questions\nprint('number of missing values in ExCoderReturn column: {}'.format(survey_results['ExCoderReturn'].isna().sum()))\nfeature_stat_single('ExCoderReturn', survey_results);", "number of missing values in ExCoderReturn column: 50469\n" ], [ "#these columns are categorical in type and they have a huge number of missing values so they need to be cleaned and encoded \nencoding = {'Strongly disagree': 1, 'Disagree': 2, 'Somewhat agree': 3,'Agree': 4, 'Strongly agree': 5}\nleaving_reasons_clean = survey_results.copy()\nfor col in leaving_coding_job_cols:\n leaving_reasons_clean = leaving_reasons_clean[~(pd.isnull(leaving_reasons_clean[col]))]\n leaving_reasons_clean = leaving_reasons_clean.replace({col:encoding})", "_____no_output_____" ], [ "leaving_reasons_means = dict(zip(leaving_coding_job_cols, np.random.randint(1, size=8)))", "_____no_output_____" ], [ "for col in leaving_coding_job_cols:\n leaving_reasons_means[col] = round(leaving_reasons_clean[col].mean(),2)", "_____no_output_____" ], [ "leaving_reasons_means\n", "_____no_output_____" ] ], [ [ "853 responses showed that: \nmost of the developers who left their coding jobs they agree on the following statements:\n- If money weren't an issue, I would take a coding job again\n- I don't think my coding skills are up to date\n- I'm still active in the developer community\n- My career is going the way I thought it would 10 years ago\n- I have better work-life balance now than I did as a developer\n\nand disagree on:\n- Working as a developer just wasn't for me\n- When I was a developer, I didn't feel like I belonged with my colleagues\n\nin the middle:\n- I probably won't code for a living ever again\n\nIt seems like those who left coding jobs still enjoy coding and they still do it but they don't believe it's good for a living as it doesn't pay enough.\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
4a53220668d57af1efb2bd91e578bbe462ed3a87
45,013
ipynb
Jupyter Notebook
notebooks/Repairing_Code.ipynb
TheV1rtuoso/debuggingbook
dd4a1605cff793f614e67fbaef74de7d20e0519c
[ "MIT" ]
107
2020-09-27T13:33:26.000Z
2022-03-21T10:45:04.000Z
notebooks/Repairing_Code.ipynb
TheV1rtuoso/debuggingbook
dd4a1605cff793f614e67fbaef74de7d20e0519c
[ "MIT" ]
26
2020-10-23T14:43:04.000Z
2022-03-03T15:06:52.000Z
notebooks/Repairing_Code.ipynb
TheV1rtuoso/debuggingbook
dd4a1605cff793f614e67fbaef74de7d20e0519c
[ "MIT" ]
20
2021-03-04T11:49:09.000Z
2022-03-23T06:16:36.000Z
24.006933
510
0.527848
[ [ [ "# Third Project - Automated Repair", "_____no_output_____" ], [ "## Overview", "_____no_output_____" ], [ "### The Task\n\nFor the first two submissions we asked you to implement a _Debugger_ as well as an _Input Reducer_. Both of these tools are used to help the developer to locate bugs and then manually fix them.\n\nIn this project, you will implement a technique of automatic code repair. To do so, you will extend the `Repairer` introduced in the [Repairing Code Automatically](https://www.debuggingbook.org/beta/html/Repairer.html) chapter of [The Debugging Book](https://www.debuggingbook.org/beta).\n\nYour own `Repairer` should automatically generate _repair suggestions_ to the faulty functions we provide later in this notebook. This can be achieved, for instance, by changing various components of the mutator, changing the debugger, or the reduction algorithm. However, you are neither reguired to make all these changes nor required to limit yourself to the changes proposed here.", "_____no_output_____" ], [ "### The Submission\n\nThe time frame for this project is **3 weeks**, and the deadline is **Februrary 5th, 23:59**. \n\nThe submission should be in form of a Jupyter notebook and you are expected to hand in the submission as a .zip-archive. The notebook should, apart from the code itself, also provide sufficient explanations and reasoning (in markdown cells) behind the decisions that lead to the solution provided. Projects that do not include explanations cannot get more than **15 points**.", "_____no_output_____" ] ], [ [ "import bookutils", "_____no_output_____" ], [ "# ignore\nfrom typing import Any, Callable, Optional, Tuple, List", "_____no_output_____" ] ], [ [ "## A Faulty Function and How to Repair It\nBefore discussing how to use and extend the Repairer, we first start by introducing a new (and highly complex) function that is supposed to return the larger of two values.", "_____no_output_____" ] ], [ [ "def larger(x: Any, y: Any) -> Any:\n if x < y:\n return x\n return y", "_____no_output_____" ] ], [ [ "Unfortunately, we introduced a bug which makes the function behave the exact opposite way as it is supposed to:", "_____no_output_____" ] ], [ [ "larger(1, 3)", "_____no_output_____" ] ], [ [ "To fix this issue, we could try to debug it, using the tools we have already seen. However, given the complexity of the function under test (sorry for the irony), we might want to automatically repair the function, using the *Repairer* introduced in *The Debugging Book*.\n\nTo do so, we first need to define set of test cases, which help the *Repairer* in fixing the function.", "_____no_output_____" ] ], [ [ "def larger_testcase() -> Tuple[int, int]:\n x = random.randrange(100)\n y = random.randrange(100)\n return x, y", "_____no_output_____" ], [ "def larger_test(x: Any, y: Any) -> None:\n m = larger(x, y)\n assert m == max(x, y), f\"expected {max(x, y)}, but got {m}\"", "_____no_output_____" ], [ "import math\nimport random", "_____no_output_____" ], [ "random.seed(42)", "_____no_output_____" ] ], [ [ "Let us generate a random test case for our function:", "_____no_output_____" ] ], [ [ "larger_input = larger_testcase()\nprint(larger_input)", "_____no_output_____" ] ], [ [ "and then feed it into our `larger_test()`:", "_____no_output_____" ] ], [ [ "from ExpectError import ExpectError", "_____no_output_____" ], [ "with ExpectError():\n larger_test(*larger_input)", "_____no_output_____" ] ], [ [ "As expected, we got an error – the `larger()` function has adefect.", "_____no_output_____" ], [ "For a complete test suite, we need a set of passing and failing tests. To be sure we have both, we create functions which produce dedicated inputs:", "_____no_output_____" ] ], [ [ "def larger_passing_testcase() -> Tuple:\n while True:\n try:\n x, y = larger_testcase()\n larger_test(x, y)\n return x, y\n except AssertionError:\n pass", "_____no_output_____" ], [ "def larger_failing_testcase() -> Tuple:\n while True:\n try:\n x, y = larger_testcase()\n larger_test(x, y)\n except AssertionError:\n return x, y", "_____no_output_____" ], [ "passing_input = larger_passing_testcase()\nprint(passing_input)", "_____no_output_____" ] ], [ [ "With `passing_input`, our `larger()` function produces a correct result, and its test function does not fail.", "_____no_output_____" ] ], [ [ "larger_test(*passing_input)", "_____no_output_____" ], [ "failing_input = larger_failing_testcase()\nprint(failing_input)", "_____no_output_____" ] ], [ [ "While `failing_input` leads to an error:", "_____no_output_____" ] ], [ [ "with ExpectError():\n larger_test(*failing_input)", "_____no_output_____" ] ], [ [ "With the above defined functions, we can now start to create a number of passing and failing tests:", "_____no_output_____" ] ], [ [ "TESTS = 100", "_____no_output_____" ], [ "LARGER_PASSING_TESTCASES = [larger_passing_testcase()\n for i in range(TESTS)]", "_____no_output_____" ], [ "LARGER_FAILING_TESTCASES = [larger_failing_testcase()\n for i in range(TESTS)]", "_____no_output_____" ], [ "from StatisticalDebugger import OchiaiDebugger", "_____no_output_____" ] ], [ [ "Next, let us use _statistical debugging_ to identify likely faulty locations. The `OchiaiDebugger` ranks individual code lines by how frequently they are executed in failing runs (and not in passing runs).", "_____no_output_____" ] ], [ [ "larger_debugger = OchiaiDebugger()", "_____no_output_____" ], [ "for x, y in LARGER_PASSING_TESTCASES + LARGER_FAILING_TESTCASES:\n with larger_debugger:\n larger_test(x, y)", "_____no_output_____" ] ], [ [ "Given the results of statistical debugging, we can now use the *Repairer* introduced in the book to repair our function. Here we use the default implementation which is initialized with the simple _StatementMutator_ mutator.", "_____no_output_____" ] ], [ [ "from Repairer import Repairer\nfrom Repairer import ConditionMutator, CrossoverOperator\nfrom Repairer import DeltaDebugger", "_____no_output_____" ], [ "repairer = Repairer(larger_debugger, log=True)", "_____no_output_____" ], [ "best_tree, fitness = repairer.repair() # type: ignore", "_____no_output_____" ] ], [ [ "The *Repairer* successfully produced a fix.", "_____no_output_____" ], [ "## Implementation\n\nAs stated above, the goal of this project is to implement a repairer capable of producing a fix to the functions defined in *the Evaluation section*, as well as secret functions. \nTo do this, you need to work with the _Repairer_ class from the book.\nThe _Repairer_ class is very configurable, so that it is easy to update and plug in various components: the fault localization (pass a different debugger that is a subclass of DifferenceDebugger), the mutation operator (set mutator_class to a subclass of `StatementMutator`), the crossover operator (set crossover_class to a subclass of `CrossoverOperator`), and the reduction algorithm (set reducer_class to a subclass of `Reducer`). You may change any of these components or make other changes at will.", "_____no_output_____" ], [ "For us to be able to test your implementation, you will have to implement the `debug_and_repair()` function defined here.", "_____no_output_____" ] ], [ [ "from bookutils import print_content, show_ast", "_____no_output_____" ], [ "def debug_and_repair(f: Callable,\n testcases: List[Tuple[Any, ...]],\n test_function: Callable,\n log: bool = False) -> Optional[str]:\n '''\n Debugs a function with the given testcases and the test_function\n and tries to repair it afterwards.\n\n Parameters\n ----------\n f : function\n The faulty function, to be debugged and repaired\n testcases : List\n A list that includes test inputs for the function under test\n test_function : function\n A function that takes the test inputs and tests whether the\n function under test produces the correct output.\n log: bool\n Turn logging on/off.\n Returns\n -------\n str\n The repaired version of f as a string.\n '''\n\n # TODO: implement this function\n\n return None", "_____no_output_____" ] ], [ [ "The function `debug_and_repair()` is the function that needs to implement everything. We will provide you with the function to be repaired, as well as testcases for this function and a test-function. Let us show you how the function can be used and should behave:", "_____no_output_____" ] ], [ [ "random.seed(42)", "_____no_output_____" ], [ "import ast", "_____no_output_____" ], [ "def simple_debug_and_repair(f: Callable,\n testcases: List[Tuple[Any, ...]],\n test_function: Callable, \n log: bool = False) -> str:\n '''\n Debugs a function with the given testcases and the test_function\n and tries to repair it afterwards.\n\n Parameters\n ----------\n f : function\n The faulty function, to be debugged and repaired\n testcases : List\n A list that includes test inputs for the function under test\n test_function : function\n A function, that takes the test inputs and tests whether the\n function under test produces the correct output.\n log: bool\n Turn logging on/off.\n Returns\n -------\n str\n The repaired version of f as a string.\n '''\n\n debugger = OchiaiDebugger()\n\n for i in testcases:\n with debugger:\n test_function(*i) # Ensure that you use *i here.\n\n repairer = Repairer(debugger,\n mutator_class=ConditionMutator,\n crossover_class=CrossoverOperator,\n reducer_class=DeltaDebugger,\n log=log)\n\n # Ensure that you specify a sufficient number of\n # iterations to evolve.\n best_tree, fitness = repairer.repair(iterations=100) # type: ignore\n\n return ast.unparse(best_tree)", "_____no_output_____" ] ], [ [ "Here we again used the _Ochiai_ statistical debugger and the _Repairer_ described in [The Debugging Book](https://www.debuggingbook.org/beta/html/Repairer.html). In contrast to the initial example, now we used another type of mutator – `ConditionMutator`. It can successfully fix the `larger` function as well.", "_____no_output_____" ] ], [ [ "repaired = simple_debug_and_repair(larger,\n LARGER_PASSING_TESTCASES +\n LARGER_FAILING_TESTCASES,\n larger_test, False)\nprint_content(repaired, '.py')", "_____no_output_____" ] ], [ [ "Although `simple_debug_and_repair` produced a correct solution for our example, it does not generalize to other functions. \nSo your task is to create the `debug_and_repair()` function which can be applied on any faulty function.", "_____no_output_____" ], [ "Apart from the function `debug_and_repair()`, you may of course implement your own classes. Make sure, however, that you are using these classes within `debug_and_repair()`. Also, keep in mind to tune the _iteration_ parameter of the `Repairer` so that it has sufficient number of generation to evolve. As it may take too much time to find a solution for an ill-programmed repairer (e.g., consider an infinite `while`loop introduced in the fix), we impose a _10-minute timeout_ for each repair.", "_____no_output_____" ], [ "## Evaluation", "_____no_output_____" ], [ "Having you implement `debug_and_repair()` allows us to easily test your implementation by calling the function with its respective arguments and testing the correctness of its output. In this section, we will provide you with some test cases as well as the testing framework for this project. This will help you to assess the quality of your work. \n\nWe define functions as well as test-case generators for these functions. The functions given here should be considered as **public tests**. If you pass all public tests, without hard-coding the solutions, you are guaranteed to achieve **10 points**. The secret tests for the remaining 10 must-have-points have similar defects.", "_____no_output_____" ], [ "### Factorial\n\nThe first function we implement is a _factorial_ function. It is supposed to compute the following formula: \n\\begin{equation*}\nn! = \\textit{factorial}(n) = \\prod_{k=1}^{n}k, \\quad \\text{for $k\\geq 1$}\n\\end{equation*}", "_____no_output_____" ], [ "Here we define three faulty functions `factorial1`, `factorial2`, and `factorial3` that are supposed to compute the factorial.", "_____no_output_____" ] ], [ [ "def factorial1(n): # type: ignore\n res = 1\n for i in range(1, n):\n res *= i\n return res", "_____no_output_____" ] ], [ [ "From the first sight, `factorial1` looks to be correctly implemented, still it produces the wrong answer:", "_____no_output_____" ] ], [ [ "factorial1(5)", "_____no_output_____" ] ], [ [ "while the correct value for 5! is 120.", "_____no_output_____" ] ], [ [ "def factorial_testcase() -> int:\n n = random.randrange(100)\n return n", "_____no_output_____" ], [ "def factorial1_test(n: int) -> None:\n m = factorial1(n)\n assert m == math.factorial(n)", "_____no_output_____" ], [ "def factorial_passing_testcase() -> Tuple:\n while True:\n try:\n n = factorial_testcase()\n factorial1_test(n)\n return (n,)\n except AssertionError:\n pass", "_____no_output_____" ], [ "def factorial_failing_testcase() -> Tuple:\n while True:\n try:\n n = factorial_testcase()\n factorial1_test(n)\n except AssertionError:\n return (n,)", "_____no_output_____" ], [ "FACTORIAL_PASSING_TESTCASES_1 = [factorial_passing_testcase() for i in range(TESTS)]", "_____no_output_____" ], [ "FACTORIAL_FAILING_TESTCASES_1 = [factorial_failing_testcase() for i in range(TESTS)]", "_____no_output_____" ] ], [ [ "As we can see, our simple Repairer cannot produce a fix. (Or more precisely, the \"fix\" it produces is pretty much pointless.)", "_____no_output_____" ] ], [ [ "repaired = \\\n simple_debug_and_repair(factorial1,\n FACTORIAL_PASSING_TESTCASES_1 +\n FACTORIAL_FAILING_TESTCASES_1,\n factorial1_test, True)", "_____no_output_____" ] ], [ [ "The problem is that the current `Repairer` does not provide a suitable mutation to change the right part of the code.\n\nHow can we repair this? Consider extending `StatementMutator` operator such that it can mutate various parts of the code, such as ranges, arithmetic operations, variable names etc. (As a reference of how to do that, look at the `ConditionMutator` class.)", "_____no_output_____" ], [ "The next faulty function is `factorial2()`:", "_____no_output_____" ] ], [ [ "def factorial2(n): # type: ignore\n i = 1\n for i in range(1, n + 1):\n i *= i\n return i", "_____no_output_____" ] ], [ [ "Again, it outputs the incorrect answer:", "_____no_output_____" ] ], [ [ "factorial2(5)", "_____no_output_____" ], [ "def factorial2_test(n: int) -> None:\n m = factorial2(n)\n assert m == math.factorial(n)", "_____no_output_____" ], [ "def factorial_passing_testcase() -> Tuple: # type: ignore\n while True:\n try:\n n = factorial_testcase()\n factorial2_test(n)\n return (n,)\n except AssertionError:\n pass", "_____no_output_____" ], [ "def factorial_failing_testcase() -> Tuple: # type: ignore\n while True:\n try:\n n = factorial_testcase()\n factorial2_test(n)\n except AssertionError:\n return (n,)", "_____no_output_____" ], [ "FACTORIAL_PASSING_TESTCASES_2 = [factorial_passing_testcase()\n for i in range(TESTS)]", "_____no_output_____" ], [ "FACTORIAL_FAILING_TESTCASES_2 = [factorial_failing_testcase()\n for i in range(TESTS)]", "_____no_output_____" ] ], [ [ "The third faulty function is `factorial3()`:", "_____no_output_____" ] ], [ [ "def factorial3(n): # type: ignore\n res = 1\n for i in range(1, n + 1):\n res += i\n return res", "_____no_output_____" ], [ "factorial3(5)", "_____no_output_____" ], [ "def factorial3_test(n: int) -> None:\n m = factorial3(n)\n assert m == math.factorial(n)", "_____no_output_____" ], [ "def factorial_passing_testcase() -> Tuple: # type: ignore\n while True:\n try:\n n = factorial_testcase()\n factorial3_test(n)\n return (n,)\n except AssertionError:\n pass", "_____no_output_____" ], [ "def factorial_failing_testcase() -> Tuple: # type: ignore\n while True:\n try:\n n = factorial_testcase()\n factorial3_test(n)\n except AssertionError:\n return (n,)", "_____no_output_____" ], [ "FACTORIAL_PASSING_TESTCASES_3 = [factorial_passing_testcase()\n for i in range(TESTS)]", "_____no_output_____" ], [ "FACTORIAL_FAILING_TESTCASES_3 = [factorial_failing_testcase()\n for i in range(TESTS)]", "_____no_output_____" ] ], [ [ "### Middle\n\nThe following faulty function is the already well known _Middle_ function, though with another defect.", "_____no_output_____" ] ], [ [ "def middle(x, y, z): # type: ignore\n if x < x:\n if y < z:\n return y\n if x < z:\n return z\n return x\n if x < z:\n return x\n if y < z:\n return z\n return y", "_____no_output_____" ] ], [ [ "It should return the second largest number of the input, but it does not:", "_____no_output_____" ] ], [ [ "middle(2, 3, 1)", "_____no_output_____" ], [ "def middle_testcase() -> Tuple:\n x = random.randrange(10)\n y = random.randrange(10)\n z = random.randrange(10)\n return x, y, z", "_____no_output_____" ], [ "def middle_test(x: int, y: int, z: int) -> None:\n m = middle(x, y, z)\n assert m == sorted([x, y, z])[1]", "_____no_output_____" ], [ "def middle_passing_testcase() -> Tuple:\n while True:\n try:\n x, y, z = middle_testcase()\n middle_test(x, y, z)\n return x, y, z\n except AssertionError:\n pass", "_____no_output_____" ], [ "def middle_failing_testcase() -> Tuple:\n while True:\n try:\n x, y, z = middle_testcase()\n middle_test(x, y, z)\n except AssertionError:\n return x, y, z", "_____no_output_____" ], [ "MIDDLE_PASSING_TESTCASES = [middle_passing_testcase()\n for i in range(TESTS)]", "_____no_output_____" ], [ "MIDDLE_FAILING_TESTCASES = [middle_failing_testcase()\n for i in range(TESTS)]", "_____no_output_____" ] ], [ [ "### Power\n\nThe power function should implement the following formular:\n\\begin{equation*}\n\\textit{power}(x, n) = x^n, \\quad \\text{for $x\\geq 0$ and $n \\geq 0$}\n\\end{equation*}", "_____no_output_____" ] ], [ [ "def power(x, n): # type: ignore\n res = 1\n for i in range(0, x):\n res *= n\n return res", "_____no_output_____" ] ], [ [ "However, this `power()` function either has an uncommon interpretation of $x^y$ – or it is simply wrong:", "_____no_output_____" ] ], [ [ "power(2, 5)", "_____no_output_____" ] ], [ [ "We go with the simpler explanation that `power()` is wrong. The correct value, of course, should be $2^5 = 32$.", "_____no_output_____" ] ], [ [ "def power_testcase() -> Tuple:\n x = random.randrange(100)\n n = random.randrange(100)\n return x, n", "_____no_output_____" ], [ "def power_test(x: int, n: int) -> None:\n m = power(x, n)\n assert m == pow(x, n)", "_____no_output_____" ], [ "def power_passing_testcase() -> Tuple:\n while True:\n try:\n x, n = power_testcase()\n power_test(x, n)\n return x, n\n except AssertionError:\n pass", "_____no_output_____" ], [ "def power_failing_testcase() -> Tuple:\n while True:\n try:\n x, n = power_testcase()\n power_test(x, n)\n except AssertionError:\n return x, n", "_____no_output_____" ], [ "POWER_PASSING_TESTCASES = [power_passing_testcase()\n for i in range(TESTS)]", "_____no_output_____" ], [ "POWER_FAILING_TESTCASES = [power_failing_testcase()\n for i in range(TESTS)]", "_____no_output_____" ] ], [ [ "### Tester Class", "_____no_output_____" ], [ "To make it convenient to test your solution we provide a testing framework:", "_____no_output_____" ] ], [ [ "import re", "_____no_output_____" ], [ "class Test:\n def __init__(self,\n function: Callable,\n testcases: List, \n test_function: Callable,\n assert_function: Callable) -> None:\n self.function = function\n self.testcases = testcases\n self.test_function = test_function\n self.assert_function = assert_function\n\n def run(self, repair_function: Callable) -> None:\n repaired = repair_function(self.function,\n self.testcases,\n self.test_function)\n repaired = re.sub(self.function.__name__, 'foo', repaired)\n exec(repaired, globals())\n\n for test in self.testcases:\n res = foo(*test) # type: ignore\n assert res == self.assert_function(*test)", "_____no_output_____" ], [ "def middle_assert(x, y, z): # type: ignore\n return sorted([x, y, z])[1]", "_____no_output_____" ], [ "test0 = Test(factorial1, FACTORIAL_PASSING_TESTCASES_1 + FACTORIAL_FAILING_TESTCASES_1, factorial1_test, math.factorial)\ntest1 = Test(factorial2, FACTORIAL_PASSING_TESTCASES_2 + FACTORIAL_FAILING_TESTCASES_2, factorial2_test, math.factorial)\ntest2 = Test(factorial3, FACTORIAL_PASSING_TESTCASES_3 + FACTORIAL_FAILING_TESTCASES_3, factorial3_test, math.factorial)\ntest3 = Test(middle, MIDDLE_PASSING_TESTCASES + MIDDLE_FAILING_TESTCASES, middle_test, middle_assert)\ntest4 = Test(power, POWER_PASSING_TESTCASES + POWER_FAILING_TESTCASES, power_test, pow)", "_____no_output_____" ], [ "tests = [test0, test1, test2, test3, test4]", "_____no_output_____" ], [ "class Tester:\n def __init__(self, function: Callable, tests: List) -> None:\n self.function = function\n self.tests = tests\n random.seed(42) # We use this seed for our evaluation; don't change it.\n\n def run_tests(self) -> None:\n for test in self.tests:\n try:\n test.run(self.function)\n print(f'Test {test.function.__name__}: OK')\n except AssertionError:\n print(f'Test {test.function.__name__}: Failed')", "_____no_output_____" ], [ "tester = Tester(simple_debug_and_repair, tests) # TODO: replace simple_debug_and_repair by your debug_and_repair function\ntester.run_tests()", "_____no_output_____" ] ], [ [ "By executing the `Tester` as shown above, you can assess the quality of your repairing approach, by testing your own `debug_and_repair()` function.", "_____no_output_____" ], [ "## Grading\n\nYour project will be graded by _automated tests_. The tests are executed in the same manner as shown above.\nIn total there are **20 points** + **10 bonus points** to be awarded for this project. **20 points** for the must-haves, **10 bonus points** for may-haves.", "_____no_output_____" ], [ "### Must-Haves (20 points)\n\nMust haves include an implementation of the `debug_and_repair` function in a way that it automatically repairs faulty functions given sufficiantly large test suites.\n**10 points** are awarded for passing the tests in this notebook. Each passing test being worth two points.\n**10 points** are awarded for passing secret tests.", "_____no_output_____" ], [ "### May-Haves (10 points)\n\nMay-haves will also be tested with secret tests, and award **2 points** each. The may-have-features for this project are a more robust implementation, that is able to cope with a wider range of defects:\n\n* Infinite loops\n* Infinite recursion (`RecursionError` in Python)\n* Type errors (`TypeError` in Python)\n* Undefined identifiers (`NameError` in Python)", "_____no_output_____" ], [ "### General Rules\n\nYou need to achieve at least **10 points** to be awarded any points at all. \nTests must be passed without hard-coding results, otherwise no points are awarded. \nYour code needs to be sufficiently documented in order to achieve points!", "_____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" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4a532638668ad68c02f5aceec8bcf2f870519a5b
15,478
ipynb
Jupyter Notebook
neural_style_transfer.ipynb
dcastf01/Actividad_vision_artificial
b89bd043a6e72908466048e25897ecef34727497
[ "MIT" ]
null
null
null
neural_style_transfer.ipynb
dcastf01/Actividad_vision_artificial
b89bd043a6e72908466048e25897ecef34727497
[ "MIT" ]
null
null
null
neural_style_transfer.ipynb
dcastf01/Actividad_vision_artificial
b89bd043a6e72908466048e25897ecef34727497
[ "MIT" ]
null
null
null
34.31929
254
0.518736
[ [ [ "<a href=\"https://colab.research.google.com/github/dcastf01/Actividad_vision_artificial/blob/main/neural_style_transfer.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# Neural style transfer\n\n**Author:** [fchollet](https://twitter.com/fchollet)<br>\n**Date created:** 2016/01/11<br>\n**Last modified:** 2020/05/02<br>\n**Description:** Transfering the style of a reference image to target image using gradient descent.", "_____no_output_____" ], [ "## Introduction\n\nStyle transfer consists in generating an image\nwith the same \"content\" as a base image, but with the\n\"style\" of a different picture (typically artistic).\nThis is achieved through the optimization of a loss function\nthat has 3 components: \"style loss\", \"content loss\",\nand \"total variation loss\":\n\n- The total variation loss imposes local spatial continuity between\nthe pixels of the combination image, giving it visual coherence.\n- The style loss is where the deep learning keeps in --that one is defined\nusing a deep convolutional neural network. Precisely, it consists in a sum of\nL2 distances between the Gram matrices of the representations of\nthe base image and the style reference image, extracted from\ndifferent layers of a convnet (trained on ImageNet). The general idea\nis to capture color/texture information at different spatial\nscales (fairly large scales --defined by the depth of the layer considered).\n- The content loss is a L2 distance between the features of the base\nimage (extracted from a deep layer) and the features of the combination image,\nkeeping the generated image close enough to the original one.\n\n**Reference:** [A Neural Algorithm of Artistic Style](\n http://arxiv.org/abs/1508.06576)\n", "_____no_output_____" ], [ "## Setup\n", "_____no_output_____" ] ], [ [ "import numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.applications import vgg19\n\nbase_image_path = keras.utils.get_file(\"paris.jpg\", \"https://i.imgur.com/F28w3Ac.jpg\")\nstyle_reference_image_path = keras.utils.get_file(\n \"starry_night.jpg\", \"https://i.imgur.com/9ooB60I.jpg\"\n)\nresult_prefix = \"paris_generated\"\n\n# Weights of the different loss components\ntotal_variation_weight = 1e-6\nstyle_weight = 1e-6\ncontent_weight = 2.5e-8\n\n# Dimensions of the generated picture.\nwidth, height = keras.preprocessing.image.load_img(base_image_path).size\nimg_nrows = 400\nimg_ncols = int(width * img_nrows / height)\n", "_____no_output_____" ] ], [ [ "## Let's take a look at our base (content) image and our style reference image\n", "_____no_output_____" ] ], [ [ "from IPython.display import Image, display\n\ndisplay(Image(base_image_path))\ndisplay(Image(style_reference_image_path))\n", "_____no_output_____" ] ], [ [ "## Image preprocessing / deprocessing utilities\n", "_____no_output_____" ] ], [ [ "\ndef preprocess_image(image_path):\n # Util function to open, resize and format pictures into appropriate tensors\n img = keras.preprocessing.image.load_img(\n image_path, target_size=(img_nrows, img_ncols)\n )\n img = keras.preprocessing.image.img_to_array(img)\n img = np.expand_dims(img, axis=0)\n img = vgg19.preprocess_input(img)\n return tf.convert_to_tensor(img)\n\n\ndef deprocess_image(x):\n # Util function to convert a tensor into a valid image\n x = x.reshape((img_nrows, img_ncols, 3))\n # Remove zero-center by mean pixel\n x[:, :, 0] += 103.939\n x[:, :, 1] += 116.779\n x[:, :, 2] += 123.68\n # 'BGR'->'RGB'\n x = x[:, :, ::-1]\n x = np.clip(x, 0, 255).astype(\"uint8\")\n return x\n\n", "_____no_output_____" ] ], [ [ "## Compute the style transfer loss\n\nFirst, we need to define 4 utility functions:\n\n- `gram_matrix` (used to compute the style loss)\n- The `style_loss` function, which keeps the generated image close to the local textures\nof the style reference image\n- The `content_loss` function, which keeps the high-level representation of the\ngenerated image close to that of the base image\n- The `total_variation_loss` function, a regularization loss which keeps the generated\nimage locally-coherent\n", "_____no_output_____" ] ], [ [ "# The gram matrix of an image tensor (feature-wise outer product)\n\n\ndef gram_matrix(x):\n x = tf.transpose(x, (2, 0, 1))\n features = tf.reshape(x, (tf.shape(x)[0], -1))\n gram = tf.matmul(features, tf.transpose(features))\n return gram\n\n\n# The \"style loss\" is designed to maintain\n# the style of the reference image in the generated image.\n# It is based on the gram matrices (which capture style) of\n# feature maps from the style reference image\n# and from the generated image\n\n\ndef style_loss(style, combination):\n S = gram_matrix(style)\n C = gram_matrix(combination)\n channels = 3\n size = img_nrows * img_ncols\n return tf.reduce_sum(tf.square(S - C)) / (4.0 * (channels ** 2) * (size ** 2))\n\n\n# An auxiliary loss function\n# designed to maintain the \"content\" of the\n# base image in the generated image\n\n\ndef content_loss(base, combination):\n return tf.reduce_sum(tf.square(combination - base))\n\n\n# The 3rd loss function, total variation loss,\n# designed to keep the generated image locally coherent\n\n\ndef total_variation_loss(x):\n a = tf.square(\n x[:, : img_nrows - 1, : img_ncols - 1, :] - x[:, 1:, : img_ncols - 1, :]\n )\n b = tf.square(\n x[:, : img_nrows - 1, : img_ncols - 1, :] - x[:, : img_nrows - 1, 1:, :]\n )\n return tf.reduce_sum(tf.pow(a + b, 1.25))\n\n", "_____no_output_____" ] ], [ [ "Next, let's create a feature extraction model that retrieves the intermediate activations\nof VGG19 (as a dict, by name).\n", "_____no_output_____" ] ], [ [ "# Build a VGG19 model loaded with pre-trained ImageNet weights\nmodel = vgg19.VGG19(weights=\"imagenet\", include_top=False)\n\n# Get the symbolic outputs of each \"key\" layer (we gave them unique names).\noutputs_dict = dict([(layer.name, layer.output) for layer in model.layers])\n\n# Set up a model that returns the activation values for every layer in\n# VGG19 (as a dict).\nfeature_extractor = keras.Model(inputs=model.inputs, outputs=outputs_dict)\n", "_____no_output_____" ] ], [ [ "Finally, here's the code that computes the style transfer loss.\n", "_____no_output_____" ] ], [ [ "# List of layers to use for the style loss.\nstyle_layer_names = [\n \"block1_conv1\",\n \"block2_conv1\",\n \"block3_conv1\",\n \"block4_conv1\",\n \"block5_conv1\",\n]\n# The layer to use for the content loss.\ncontent_layer_name = \"block5_conv2\"\n\n\ndef compute_loss(combination_image, base_image, style_reference_image):\n input_tensor = tf.concat(\n [base_image, style_reference_image, combination_image], axis=0\n )\n features = feature_extractor(input_tensor)\n\n # Initialize the loss\n loss = tf.zeros(shape=())\n\n # Add content loss\n layer_features = features[content_layer_name]\n base_image_features = layer_features[0, :, :, :]\n combination_features = layer_features[2, :, :, :]\n loss = loss + content_weight * content_loss(\n base_image_features, combination_features\n )\n # Add style loss\n for layer_name in style_layer_names:\n layer_features = features[layer_name]\n style_reference_features = layer_features[1, :, :, :]\n combination_features = layer_features[2, :, :, :]\n sl = style_loss(style_reference_features, combination_features)\n loss += (style_weight / len(style_layer_names)) * sl\n\n # Add total variation loss\n loss += total_variation_weight * total_variation_loss(combination_image)\n return loss\n\n", "_____no_output_____" ] ], [ [ "## Add a tf.function decorator to loss & gradient computation\n\nTo compile it, and thus make it fast.\n", "_____no_output_____" ] ], [ [ "\[email protected]\ndef compute_loss_and_grads(combination_image, base_image, style_reference_image):\n with tf.GradientTape() as tape:\n loss = compute_loss(combination_image, base_image, style_reference_image)\n grads = tape.gradient(loss, combination_image)\n return loss, grads\n\n", "_____no_output_____" ] ], [ [ "## The training loop\n\nRepeatedly run vanilla gradient descent steps to minimize the loss, and save the\nresulting image every 100 iterations.\n\nWe decay the learning rate by 0.96 every 100 steps.\n", "_____no_output_____" ] ], [ [ "optimizer = keras.optimizers.SGD(\n keras.optimizers.schedules.ExponentialDecay(\n initial_learning_rate=100.0, decay_steps=100, decay_rate=0.96\n )\n)\n\nbase_image = preprocess_image(base_image_path)\nstyle_reference_image = preprocess_image(style_reference_image_path)\ncombination_image = tf.Variable(preprocess_image(base_image_path))\n\niterations = 4000\nfor i in range(1, iterations + 1):\n loss, grads = compute_loss_and_grads(\n combination_image, base_image, style_reference_image\n )\n optimizer.apply_gradients([(grads, combination_image)])\n if i % 100 == 0:\n print(\"Iteration %d: loss=%.2f\" % (i, loss))\n img = deprocess_image(combination_image.numpy())\n fname = result_prefix + \"_at_iteration_%d.png\" % i\n keras.preprocessing.image.save_img(fname, img)\n", "_____no_output_____" ] ], [ [ "After 4000 iterations, you get the following result:\n", "_____no_output_____" ] ], [ [ "display(Image(result_prefix + \"_at_iteration_4000.png\"))\n", "_____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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a533466678e5c596e64c52277a4470a6a87fa73
11,254
ipynb
Jupyter Notebook
cgames/05_sonic/sonic_a2c.ipynb
deepanshut041/Reinforcement-Learning-Basic
2a4c28008d2fc73441778ebd2f7e7d3db12f17ff
[ "MIT" ]
21
2020-01-25T12:04:24.000Z
2022-03-13T10:14:36.000Z
cgames/05_sonic/sonic_a2c.ipynb
deepanshut041/Reinforcement-Learning-Basic
2a4c28008d2fc73441778ebd2f7e7d3db12f17ff
[ "MIT" ]
null
null
null
cgames/05_sonic/sonic_a2c.ipynb
deepanshut041/Reinforcement-Learning-Basic
2a4c28008d2fc73441778ebd2f7e7d3db12f17ff
[ "MIT" ]
14
2020-05-15T17:14:02.000Z
2022-03-30T12:37:13.000Z
25.577273
117
0.487827
[ [ [ "# Sonic The Hedgehog 1 with Advantage Actor Critic\n\n## Step 1: Import the libraries", "_____no_output_____" ] ], [ [ "import time\nimport retro\nimport random\nimport torch\nimport numpy as np\nfrom collections import deque\nimport matplotlib.pyplot as plt\nfrom IPython.display import clear_output\nimport math\n\n%matplotlib inline", "_____no_output_____" ], [ "import sys\nsys.path.append('../../')\nfrom algos.agents import A2CAgent\nfrom algos.models import ActorCnn, CriticCnn\nfrom algos.preprocessing.stack_frame import preprocess_frame, stack_frame", "_____no_output_____" ] ], [ [ "## Step 2: Create our environment\n\nInitialize the environment in the code cell below.\n", "_____no_output_____" ] ], [ [ "env = retro.make(game='SonicTheHedgehog-Genesis', state='GreenHillZone.Act1', scenario='contest')\nenv.seed(0)", "_____no_output_____" ], [ "# if gpu is to be used\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(\"Device: \", device)", "_____no_output_____" ] ], [ [ "## Step 3: Viewing our Enviroment", "_____no_output_____" ] ], [ [ "print(\"The size of frame is: \", env.observation_space.shape)\nprint(\"No. of Actions: \", env.action_space.n)\nenv.reset()\nplt.figure()\nplt.imshow(env.reset())\nplt.title('Original Frame')\nplt.show()", "_____no_output_____" ], [ "possible_actions = {\n # No Operation\n 0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # Left\n 1: [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n # Right\n 2: [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],\n # Left, Down\n 3: [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0],\n # Right, Down\n 4: [0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0],\n # Down\n 5: [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],\n # Down, B\n 6: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],\n # B\n 7: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n }", "_____no_output_____" ] ], [ [ "### Execute the code cell below to play Pong with a random policy.", "_____no_output_____" ] ], [ [ "def random_play():\n score = 0\n env.reset()\n for i in range(200):\n env.render()\n action = possible_actions[np.random.randint(len(possible_actions))]\n state, reward, done, _ = env.step(action)\n score += reward\n if done:\n print(\"Your Score at end of game is: \", score)\n break\n env.reset()\n env.render(close=True)\nrandom_play()", "_____no_output_____" ] ], [ [ "## Step 4:Preprocessing Frame", "_____no_output_____" ] ], [ [ "plt.figure()\nplt.imshow(preprocess_frame(env.reset(), (1, -1, -1, 1), 84), cmap=\"gray\")\nplt.title('Pre Processed image')\nplt.show()", "_____no_output_____" ] ], [ [ "## Step 5: Stacking Frame", "_____no_output_____" ] ], [ [ "def stack_frames(frames, state, is_new=False):\n frame = preprocess_frame(state, (1, -1, -1, 1), 84)\n frames = stack_frame(frames, frame, is_new)\n\n return frames\n ", "_____no_output_____" ] ], [ [ "## Step 6: Creating our Agent", "_____no_output_____" ] ], [ [ "INPUT_SHAPE = (4, 84, 84)\nACTION_SIZE = len(possible_actions)\nSEED = 0\nGAMMA = 0.99 # discount factor\nALPHA= 0.0001 # Actor learning rate\nBETA = 0.0005 # Critic learning rate\nUPDATE_EVERY = 100 # how often to update the network \n\nagent = A2CAgent(INPUT_SHAPE, ACTION_SIZE, SEED, device, GAMMA, ALPHA, BETA, UPDATE_EVERY, ActorCnn, CriticCnn)", "_____no_output_____" ] ], [ [ "## Step 7: Watching untrained agent play", "_____no_output_____" ] ], [ [ "env.viewer = None\n# watch an untrained agent\nstate = stack_frames(None, env.reset(), True) \nfor j in range(200):\n env.render(close=False)\n action, _, _ = agent.act(state)\n next_state, reward, done, _ = env.step(possible_actions[action])\n state = stack_frames(state, next_state, False)\n if done:\n env.reset()\n break \nenv.render(close=True)", "_____no_output_____" ] ], [ [ "## Step 8: Loading Agent\nUncomment line to load a pretrained agent", "_____no_output_____" ] ], [ [ "start_epoch = 0\nscores = []\nscores_window = deque(maxlen=20)", "_____no_output_____" ] ], [ [ "## Step 9: Train the Agent with Actor Critic", "_____no_output_____" ] ], [ [ "def train(n_episodes=1000):\n \"\"\"\n Params\n ======\n n_episodes (int): maximum number of training episodes\n \"\"\"\n for i_episode in range(start_epoch + 1, n_episodes+1):\n state = stack_frames(None, env.reset(), True)\n score = 0\n\n # Punish the agent for not moving forward\n prev_state = {}\n steps_stuck = 0\n timestamp = 0\n while timestamp < 10000:\n action, log_prob, entropy = agent.act(state)\n next_state, reward, done, info = env.step(possible_actions[action])\n score += reward\n\n timestamp += 1\n # Punish the agent for standing still for too long.\n if (prev_state == info):\n steps_stuck += 1\n else:\n steps_stuck = 0\n prev_state = info\n \n if (steps_stuck > 20):\n reward -= 1\n\n next_state = stack_frames(state, next_state, False)\n agent.step(state, log_prob, entropy, reward, done, next_state)\n state = next_state\n if done:\n break\n scores_window.append(score) # save most recent score\n scores.append(score) # save most recent score\n \n clear_output(True)\n fig = plt.figure()\n ax = fig.add_subplot(111)\n plt.plot(np.arange(len(scores)), scores)\n plt.ylabel('Score')\n plt.xlabel('Episode #')\n plt.show()\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end=\"\")\n \n return scores", "_____no_output_____" ], [ "scores = train(1000)", "_____no_output_____" ], [ "fig = plt.figure()\nax = fig.add_subplot(111)\nplt.plot(np.arange(len(scores)), scores)\nplt.ylabel('Score')\nplt.xlabel('Episode #')\nplt.show()", "_____no_output_____" ] ], [ [ "## Step 10: Watch a Smart Agent!", "_____no_output_____" ] ], [ [ "env.viewer = None\n# watch an untrained agent\nstate = stack_frames(None, env.reset(), True) \nfor j in range(10000):\n env.render(close=False)\n action, _, _ = agent.act(state)\n next_state, reward, done, _ = env.step(possible_actions[action])\n state = stack_frames(state, next_state, False)\n if done:\n env.reset()\n break \nenv.render(close=True)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
4a53348b72fa4aa98d74c1ed611c25c47d794ec4
3,437
ipynb
Jupyter Notebook
data_analysis/numpy.ipynb
linusqzdeng/pyfinance
f8a1c137acbbe4a43d915b2bff15760764a6b97d
[ "MIT" ]
1
2022-01-05T09:28:03.000Z
2022-01-05T09:28:03.000Z
data_analysis/numpy.ipynb
linusqzdeng/pyfinance
f8a1c137acbbe4a43d915b2bff15760764a6b97d
[ "MIT" ]
null
null
null
data_analysis/numpy.ipynb
linusqzdeng/pyfinance
f8a1c137acbbe4a43d915b2bff15760764a6b97d
[ "MIT" ]
1
2022-01-05T01:20:58.000Z
2022-01-05T01:20:58.000Z
19.982558
225
0.451557
[ [ [ "# Numpy tutorial", "_____no_output_____" ] ], [ [ "import numpy as np ", "_____no_output_____" ], [ "data1 = [[[1, 2, 3, 4], [1, 2, 3, 4]], [[4, 3, 2, 1], [1, 2, 3, 4]]]\nnp.array(data1)", "_____no_output_____" ], [ "np.ones((2, 4))", "_____no_output_____" ], [ "# np.identity(6)\nnp.eye(6)", "_____no_output_____" ], [ "arr = np.array([1, 2, 3, 4])\nprint(arr.dtype)\n\narr = arr.astype(np.float64)\nprint(arr.dtype)", "int64\nfloat64\n" ], [ "numeric_string = np.array(['1.0', '3.2', '2.5'], dtype=np.string_)\nnumeric_string = numeric_string.astype(float)\nnumeric_string.dtype", "_____no_output_____" ], [ "arr[1: 3] = 6\nnew_arr = arr[1: 3]", "_____no_output_____" ], [ "new_arr[1] = 123\narr", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a533e1e1d6e0040856bcfa9fb57af4f433778e9
100,739
ipynb
Jupyter Notebook
AlgoTrading/ParameterAnalysis/Getting_Sample_Data.ipynb
xujunhuii/huobi_Python
958df8b22ce774329c7e15a1ecf2f52eea5f6af8
[ "Apache-2.0" ]
null
null
null
AlgoTrading/ParameterAnalysis/Getting_Sample_Data.ipynb
xujunhuii/huobi_Python
958df8b22ce774329c7e15a1ecf2f52eea5f6af8
[ "Apache-2.0" ]
null
null
null
AlgoTrading/ParameterAnalysis/Getting_Sample_Data.ipynb
xujunhuii/huobi_Python
958df8b22ce774329c7e15a1ecf2f52eea5f6af8
[ "Apache-2.0" ]
null
null
null
320.824841
91,464
0.90938
[ [ [ "%load_ext lab_black\n%config Completer.use_jedi = False\nimport pandas as pd\nfrom tqdm import tqdm\nimport time", "The lab_black extension is already loaded. To reload it, use:\n %reload_ext lab_black\n" ], [ "# FILENAME = \"Binance_BTC_1m.csv\"\n# FILENAME = \"Mild_Fluctuate_data.csv\"\n# FILENAME = \"Increasing_Data.csv\"\nFILENAME = \"Decreasing_Data.csv\"\ndata = pd.read_csv(FILENAME)\ndata = data[5000:]\ndata", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\n\n%matplotlib inline\nfig, ax = plt.subplots(figsize=(30, 10))\n# plt.ylim(0, 100)\ndata[[\"Close\"]].plot(ax=ax)", "_____no_output_____" ], [ "# data.to_csv(\"Decreasing_Data.csv\")", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
4a533efae33df0a4e70889a3e566a795cd3c5874
101,643
ipynb
Jupyter Notebook
_notebooks/2020-08-12-NLP.ipynb
amouu/MachineLearning-In-Action
a7cd67f33bed458126d73802427ce43583bb5a6a
[ "Apache-2.0" ]
null
null
null
_notebooks/2020-08-12-NLP.ipynb
amouu/MachineLearning-In-Action
a7cd67f33bed458126d73802427ce43583bb5a6a
[ "Apache-2.0" ]
3
2020-08-25T03:35:13.000Z
2022-02-26T09:50:52.000Z
_notebooks/2020-08-12-NLP.ipynb
amouu/MachineLearning-In-Action
a7cd67f33bed458126d73802427ce43583bb5a6a
[ "Apache-2.0" ]
1
2020-08-25T02:49:08.000Z
2020-08-25T02:49:08.000Z
189.632463
43,504
0.89652
[ [ [ "# 第一次上傳 Jupyter 使用 NLP 作業做範例\n> 都已經是第一次上傳了,一切都還在摸索,不過會努力更新ㄉ.\n\n- toc: true \n- badges: true\n- comments: true\n- categories: [jupyter, NLP, Machine Learning]\n- image: images/chart-preview.png", "_____no_output_____" ], [ "#About\n本篇文章主要展現如何快速搭建資料科學相關部落格,文章內容格式可以使用 *.ipynb 或是 .word 來做撰寫。\n可以先在 Local Machine 使用 ```Make server``` 開啟 Local Blog 之後,再使用 ```make convert``` 來轉換成 *.md \n接著就可以上傳成 Branch, 發動 pull request, 來自動 merge 到 Master ", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np", "_____no_output_____" ] ], [ [ "### Read Dataset from [Sentiment Labelled Sentences Data Set](https://archive.ics.uci.edu/ml/datasets/Sentiment+Labelled+Sentences)", "_____no_output_____" ] ], [ [ "filepath_dict = {'yelp': './sentiment labelled sentences/yelp_labelled.txt',\n 'amazon': './sentiment labelled sentences/amazon_cells_labelled.txt',\n 'imdb': './sentiment labelled sentences/imdb_labelled.txt'}\n\ndf_list = []\nfor source, filepath in filepath_dict.items():\n df = pd.read_csv(filepath, names=['sentence', 'label'], sep='\\t')\n df['source'] = source # Add another column filled with the source name\n df_list.append(df)\n\ndf = pd.concat(df_list)\nprint(df.iloc[0])", "sentence Wow... Loved this place.\nlabel 1\nsource yelp\nName: 0, dtype: object\n" ] ], [ [ "### CountVectorizer", "_____no_output_____" ] ], [ [ "from sklearn.feature_extraction.text import CountVectorizer\n\nsentences = ['John likes ice cream', 'John hates chocolate.']\nvectorizer = CountVectorizer(min_df=0, lowercase=False)\nvectorizer.fit(sentences)\nvectorizer.vocabulary_", "_____no_output_____" ], [ "vectorizer.transform(sentences).toarray()", "_____no_output_____" ] ], [ [ "### Define a Baseline Model", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\n\ndf_yelp = df[df['source'] == 'yelp']\n\nsentences = df_yelp['sentence'].values\ny = df_yelp['label'].values\n\nsentences_train, sentences_test, y_train, y_test = train_test_split(sentences, y, test_size=0.25, random_state=1000)\n\n##\nvectorizer = CountVectorizer()\n\n##\nvectorizer.fit(sentences_train)\n\n##\nX_train = vectorizer.transform(sentences_train)\nX_test = vectorizer.transform(sentences_test)\n\n## Classifier\nclassifier = LogisticRegression()\nclassifier.fit(X_train, y_train)\nscore = classifier.score(X_test, y_test)\nprint(\"Accuracy:\", score)", "Accuracy: 0.796\n" ] ], [ [ "### Apply DNN", "_____no_output_____" ] ], [ [ "from keras.models import Sequential\nfrom keras import layers\n\ninput_dim = X_train.shape[1] # Number of features\nmodel = Sequential()\nmodel.add(layers.Dense(10, input_dim=input_dim, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nmodel.summary()", "Using TensorFlow backend.\nWARNING: Logging before flag parsing goes to stderr.\nW0812 15:03:07.597831 4590767552 deprecation_wrapper.py:119] From /usr/local/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.\n\nW0812 15:03:07.612365 4590767552 deprecation_wrapper.py:119] From /usr/local/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:517: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.\n\nW0812 15:03:07.615277 4590767552 deprecation_wrapper.py:119] From /usr/local/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:4138: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead.\n\nW0812 15:03:07.644843 4590767552 deprecation_wrapper.py:119] From /usr/local/lib/python3.7/site-packages/keras/optimizers.py:790: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead.\n\nW0812 15:03:07.667706 4590767552 deprecation_wrapper.py:119] From /usr/local/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:3376: The name tf.log is deprecated. Please use tf.math.log instead.\n\nW0812 15:03:07.673678 4590767552 deprecation.py:323] From /usr/local/lib/python3.7/site-packages/tensorflow/python/ops/nn_impl.py:180: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.where in 2.0, which has the same broadcast rule as np.where\n" ], [ "history = model.fit(X_train, y_train,epochs=100,verbose=False,validation_data=(X_test, y_test),batch_size=10)", "W0812 15:03:07.856102 4590767552 deprecation_wrapper.py:119] From /usr/local/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:986: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead.\n\n" ], [ "loss, accuracy = model.evaluate(X_train, y_train, verbose=False)\nprint(\"Training Accuracy: {:.4f}\".format(accuracy))\nloss, accuracy = model.evaluate(X_test, y_test, verbose=False)\nprint(\"Testing Accuracy: {:.4f}\".format(accuracy))", "Training Accuracy: 1.0000\nTesting Accuracy: 0.7920\n" ] ], [ [ "### Visualize your report", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nplt.style.use('ggplot')\n\ndef plot_history(history):\n acc = history.history['acc']\n val_acc = history.history['val_acc']\n loss = history.history['loss']\n val_loss = history.history['val_loss']\n x = range(1, len(acc) + 1)\n\n plt.figure(figsize=(12, 5))\n plt.subplot(1, 2, 1)\n plt.plot(x, acc, 'b', label='Training acc')\n plt.plot(x, val_acc, 'r', label='Validation acc')\n plt.title('Training and validation accuracy')\n plt.legend()\n plt.subplot(1, 2, 2)\n plt.plot(x, loss, 'b', label='Training loss')\n plt.plot(x, val_loss, 'r', label='Validation loss')\n plt.title('Training and validation loss')\n plt.legend()\n\nplot_history(history)", "_____no_output_____" ] ], [ [ "### Word Embedding by yourself", "_____no_output_____" ] ], [ [ "from keras.preprocessing.text import Tokenizer\n\ntokenizer = Tokenizer(num_words=5000)\ntokenizer.fit_on_texts(sentences_train)\n\nX_train = tokenizer.texts_to_sequences(sentences_train)\nX_test = tokenizer.texts_to_sequences(sentences_test)\n\nvocab_size = len(tokenizer.word_index) + 1 # Adding 1 because of reserved 0 index\n\nprint(sentences_train[2])\nprint(X_train[2])", "Of all the dishes, the salmon was the best, but all were great.\n[11, 43, 1, 171, 1, 283, 3, 1, 47, 26, 43, 24, 22]\n" ], [ "for word in ['the', 'all', 'happy', 'sad']:\n print('{}: {}'.format(word, tokenizer.word_index[word]))", "the: 1\nall: 43\nhappy: 320\nsad: 450\n" ] ], [ [ "### Different Sequence_length among sentences", "_____no_output_____" ] ], [ [ "from keras.preprocessing.sequence import pad_sequences\n\nmaxlen = 100\n\nX_train = pad_sequences(X_train, padding='post', maxlen=maxlen)\nX_test = pad_sequences(X_test, padding='post', maxlen=maxlen)\n\nprint(X_train[0, :])", "[ 1 10 3 282 739 25 8 208 30 64 459 230 13 1 124 5 231 8\n 58 5 67 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0]\n" ], [ "### Embedding Model", "_____no_output_____" ], [ "from keras.models import Sequential\nfrom keras import layers\n\nembedding_dim = 50\n\nmodel = Sequential()\nmodel.add(layers.Embedding(input_dim=vocab_size, \n output_dim=embedding_dim, \n input_length=maxlen))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(10, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\nmodel.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy'])\nmodel.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_1 (Embedding) (None, 100, 50) 87350 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 5000) 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 10) 50010 \n_________________________________________________________________\ndense_4 (Dense) (None, 1) 11 \n=================================================================\nTotal params: 137,371\nTrainable params: 137,371\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "history = model.fit(X_train, y_train,\n epochs=20,\n verbose=False,\n validation_data=(X_test, y_test),\n batch_size=10)\nloss, accuracy = model.evaluate(X_train, y_train, verbose=False)\nprint(\"Training Accuracy: {:.4f}\".format(accuracy))\nloss, accuracy = model.evaluate(X_test, y_test, verbose=False)\nprint(\"Testing Accuracy: {:.4f}\".format(accuracy))\nplot_history(history)", "Training Accuracy: 1.0000\nTesting Accuracy: 0.7480\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
4a534f095c097a635f5a83ddfb4d6424d1a013b2
89,597
ipynb
Jupyter Notebook
Max/Evaluating-using-Dreams-from-the-orbm.ipynb
garibaldu/multicauseRBM
f64f54435f23d04682ac7c15f895a1cf470c51e8
[ "MIT" ]
null
null
null
Max/Evaluating-using-Dreams-from-the-orbm.ipynb
garibaldu/multicauseRBM
f64f54435f23d04682ac7c15f895a1cf470c51e8
[ "MIT" ]
null
null
null
Max/Evaluating-using-Dreams-from-the-orbm.ipynb
garibaldu/multicauseRBM
f64f54435f23d04682ac7c15f895a1cf470c51e8
[ "MIT" ]
null
null
null
230.920103
13,948
0.912955
[ [ [ "from scipy.special import expit\nfrom rbmpy.rbm import RBM\nfrom rbmpy.sampler import DirtyCorrectionMulDimSampler,VanillaSampler,ContinuousSampler,ContinuousApproxSampler, ContinuousApproxMulDimSampler, ApproximatedSampler, LayerWiseApproxSampler,ApproximatedMulDimSampler\nfrom rbmpy.trainer import VanillaTrainier\nfrom rbmpy.performance import Result\nimport numpy as np\nimport rbmpy.datasets, rbmpy.performance, rbmpy.plotter, pickle, rbmpy.rbm, os, logging, rbmpy.sampler,math\nimport math\nfrom rbmpy.rbm import weights_into_hiddens\nfrom rbmpy.progress import Progress\nfrom scipy.spatial.distance import cosine\n\n\nimport rbmpy.plotter as pp\nfrom numpy import newaxis\nfrom collections import Counter\n\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nlogger = logging.getLogger()\n# Set the logging level to logging.DEBUG \nlogger.setLevel(logging.INFO)\n\n%matplotlib inline", "_____no_output_____" ], [ "with open(\"mnist_data\", 'rb') as f:\n full_mnist_data = pickle.load(f)", "_____no_output_____" ], [ "# load RBMs trained on 2s and 3s", "_____no_output_____" ], [ "two_rbm, two_ds = full_mnist_data[2]\nthree_rbm, three_ds = full_mnist_data[3]", "_____no_output_____" ], [ "def print_weight_info(rbm):\n print(\"min {}\".format(rbm.weights.min()))\n print(\"max {}\".format(rbm.weights.max()))\n print(\"mean {}\".format(rbm.weights.mean()))\n print(\"std {}\".format(rbm.weights.std()))", "_____no_output_____" ], [ "print_weight_info(two_rbm)\nprint_weight_info(three_rbm)", "min -7.086554061133978\nmax 4.129461787946666\nmean -0.419801847192457\nstd 0.916423420203806\nmin -6.465314094074916\nmax 3.9852672863379834\nmean -0.4229784834602937\nstd 0.9214791081351881\n" ], [ "# make a sampler so we can make some dreams from the two and three RBMs\ntwo_sampler = ContinuousSampler(two_rbm)\nthree_sampler = ContinuousSampler(three_rbm)\ntwo_dream = two_sampler.dream(two_rbm, num_gibbs=1)\nthree_dream = three_sampler.dream(three_rbm, num_gibbs=100)\n# so we get a dream visible, but we want $\\phi$ so we can add and smush through sigmoid. so up and down once more\n \ntwo_dream_h = two_sampler.visible_to_hidden(two_dream)\ntwo_dream_phi = np.dot(two_dream_h, two_rbm.weights)\n\nthree_dream_h = three_sampler.visible_to_hidden(three_dream)\nthree_dream_phi = np.dot(three_dream_h, three_rbm.weights)\n\n# sum the phi, then expit\ncomposite_dream = expit(two_dream_phi + three_dream_phi)", "_____no_output_____" ], [ "cheating = True\nif cheating:\n composite_dream = (two_ds[0] + three_ds[0]) / 2.0\n composite_dream = composite_dream.reshape(784)", "_____no_output_____" ] ], [ [ "#Lets take a quick look at the images if instead of combining they had just done their own thing", "_____no_output_____" ] ], [ [ "pp.image(expit(two_dream_phi).reshape(28,28), color_range=(0,1))\npp.image(expit(three_dream_phi).reshape(28,28), color_range=(0,1))", "_____no_output_____" ] ], [ [ "#And now the composition from the generative model\n", "_____no_output_____" ] ], [ [ "pp.image(np.maximum(two_ds[0], three_ds[0]), cmap=plt.cm.gray_r)", "_____no_output_____" ], [ "pp.image(composite_dream.reshape(28,28), cmap=plt.cm.gray_r)", "_____no_output_____" ] ], [ [ "#Now we need to compare the ORBM and RBM at reconstructing", "_____no_output_____" ] ], [ [ "help(orbm_sampler.v_to_v)", "Help on method v_to_v in module rbmpy.sampler:\n\nv_to_v(h_a, h_b, v, num_gibbs=100, logging_freq=None) method of rbmpy.sampler.ContinuousApproxSampler instance\n\n" ], [ "# prepare the ORBM sampler\n# UGh! passing a starting hidden pattern should be optional! \nrand_h_a = np.random.randint(0,2,size=( two_rbm.num_hid())) \nrand_h_b = np.random.randint(0,2,size=( three_rbm.num_hid()))\n\norbm_sampler = ContinuousApproxSampler(two_rbm.weights, three_rbm.weights, two_rbm.hidden_bias, three_rbm.hidden_bias)\norbm_two_recon, orbm_three_recon = orbm_sampler.v_to_v(rand_h_a,rand_h_b, composite_dream, num_gibbs=100)\n\n# we can reuse the continous vanilla samplers from before\nrbm_two_recon = two_sampler.reconstruction_given_visible(composite_dream)\nrbm_three_recon = three_sampler.reconstruction_given_visible(composite_dream)", "_____no_output_____" ], [ "plt.suptitle(\"ORBM Two Reconstruction\")\npp.image(orbm_two_recon.reshape(28,28))\nplt.suptitle(\"ORBM Three Reconstruction\")\npp.image(orbm_three_recon.reshape(28,28))\n\nplt.suptitle(\"RBM Two Reconstruction\")\npp.image(rbm_two_recon.reshape(28,28))\nplt.suptitle(\"RBM Three Reconstruction\")\npp.image(rbm_three_recon.reshape(28,28))", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4a535095c8f697ec38120469e7b50187f2376700
382,012
ipynb
Jupyter Notebook
module4-sequence-your-narrative/4.Assignment/4.Assignment_SequenceYourNarrative.ipynb
CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling
5d5892af20f11a6e6bcb7536f93b90f256788fe5
[ "MIT" ]
null
null
null
module4-sequence-your-narrative/4.Assignment/4.Assignment_SequenceYourNarrative.ipynb
CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling
5d5892af20f11a6e6bcb7536f93b90f256788fe5
[ "MIT" ]
null
null
null
module4-sequence-your-narrative/4.Assignment/4.Assignment_SequenceYourNarrative.ipynb
CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling
5d5892af20f11a6e6bcb7536f93b90f256788fe5
[ "MIT" ]
null
null
null
382,012
382,012
0.867821
[ [ [ "Lambda School Data Science\n\n*Unit 1, Sprint 2, Module 4*\n\n---", "_____no_output_____" ], [ "# SEQUENCE YOUR NARRATIVE ASSIGNMENT\nReplicate the lesson code\n", "_____no_output_____" ] ], [ [ "# import seaborn and show version #.\nimport seaborn as sns\nsns.__version__", "_____no_output_____" ], [ "# import the ibraries we are going to use.\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd", "_____no_output_____" ], [ "def start():\n options = {\n 'display': {\n 'max_columns': None,\n 'max_colwidth': 25,\n 'expand_frame_repr': False, # Don't wrap to multiple pages\n 'max_rows': 14,\n 'max_seq_items': 50, # Max length of printed sequence\n 'precision': 4,\n 'show_dimensions': False\n },\n 'mode': {\n 'chained_assignment': None # Controls SettingWithCopyWarning\n }\n }\n\n for category, option in options.items():\n for op, value in option.items():\n pd.set_option(f'{category}.{op}', value) # Python 3.6+\n\nstart()", "_____no_output_____" ], [ "# load the data set.\nincome = pd.read_csv('https://raw.githubusercontent.com/open-numbers/ddf--gapminder--systema_globalis/master/ddf--datapoints--income_per_person_gdppercapita_ppp_inflation_adjusted--by--geo--time.csv')\n# show the data set headers.\nincome.head(1)", "_____no_output_____" ], [ "# load the data set.\nlifespan = pd.read_csv('https://raw.githubusercontent.com/open-numbers/ddf--gapminder--systema_globalis/master/ddf--datapoints--life_expectancy_years--by--geo--time.csv')\n# show the data set headers.\nlifespan.head(1)", "_____no_output_____" ], [ "# load the data set.\npopulation = pd.read_csv('https://raw.githubusercontent.com/open-numbers/ddf--gapminder--systema_globalis/master/ddf--datapoints--population_total--by--geo--time.csv')\n# show the data set headers.\npopulation.head(1)", "_____no_output_____" ], [ "# load the data set.\nentities = pd.read_csv('https://raw.githubusercontent.com/open-numbers/ddf--gapminder--systema_globalis/master/ddf--entities--geo--country.csv')\n# show the data set headers.\nentities.head(1)", "_____no_output_____" ], [ "# load the data set.\nconcepts = pd.read_csv('https://raw.githubusercontent.com/open-numbers/ddf--gapminder--systema_globalis/master/ddf--concepts.csv')\n# show the data set headers.\nconcepts.head(1)", "_____no_output_____" ], [ "# show the shape of each data frame.\nincome.shape, lifespan.shape, population.shape, entities.shape, concepts.shape", "_____no_output_____" ], [ "# show the data frame with headers.\nincome.head()", "_____no_output_____" ], [ "# show the end of the data set using .tail() to see what the most recent data is.\nlifespan.tail()", "_____no_output_____" ], [ "# see that the population # is not changing in these years so its possible they did not have good data.\npopulation.head()", "_____no_output_____" ], [ "# set a max to the columns we want to see from the data set.\npd.options.display.max_columns = 500\n# show the data set headers.\nentities.head()", "_____no_output_____" ], [ "# look at the value counts for the 'world_6region' column.\nentities.world_6region.value_counts()", "_____no_output_____" ], [ "# show the data set headers.\nconcepts.head()", "_____no_output_____" ] ], [ [ "## Merge data", "_____no_output_____" ] ], [ [ "# merge the 'income' & 'lifespan' data sets.\nmerged1 = pd.merge(income, lifespan)\n# show the shape of the data set.\nprint(merged1.shape)\n# show the data set headers.\nmerged1.head()", "(40437, 4)\n" ], [ "# merge 'merged1' & 'population' data sets.\nmerged2 = pd.merge(merged1, population)\n# show the shape of the data set.\nprint(merged2.shape)\n# show the data set headers.\nmerged2.head()", "(40437, 5)\n" ], [ "# merge 'merged2' data set & the columns we want from 'entities' data set.\ndf = pd.merge(merged2, entities[['country', 'name', 'world_4region', 'world_6region']], \n how='inner', left_on='geo', right_on='country')\n# show the shape of the data frame.\nprint(df.shape)\n# show the data set and headers.\ndf.head()", "(40437, 9)\n" ], [ "# drop the columns we are not going to use with df.drop().\ndf = df.drop(columns=['geo','country'])\n# rename the columns that we are going to use.\ndf = df.rename(columns = {\n 'time': 'year',\n 'income_per_person_gdppercapita_ppp_inflation_adjusted': 'income',\n 'life_expectancy_years': 'lifespan',\n 'population_total': 'population', \n 'name': 'country',\n 'world_4region': 'region4',\n 'world_6region': 'region6'\n})\n# show the shape of the data frame.\nprint(df.shape)\n# show the data set and headers.\ndf.head()", "(40437, 7)\n" ], [ "# check if we have any NA's in the data set.\ndf.isna().sum()", "_____no_output_____" ], [ "# see the counts per column and what data types with .info().\ndf.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 40437 entries, 0 to 40436\nData columns (total 7 columns):\nyear 40437 non-null int64\nincome 40437 non-null int64\nlifespan 40437 non-null float64\npopulation 40437 non-null int64\ncountry 40437 non-null object\nregion4 40437 non-null object\nregion6 40437 non-null object\ndtypes: float64(1), int64(3), object(3)\nmemory usage: 2.5+ MB\n" ], [ "# look at the statistics #'s of the data set (int/float) in the data set.\ndf.describe()", "_____no_output_____" ], [ "# look at the statisitcs #'s of (object) in the data set .\ndf.describe(exclude='number')", "_____no_output_____" ], [ "# look at all the country names using .unique().\ndf.country.unique()", "_____no_output_____" ], [ "# single out a specific country to look at.\nusa = df[df.country == 'United States']\n# set a few year dates to look for infomation specifc to those years.\nusa[usa.year.isin([1818, 1918, 2018])]", "_____no_output_____" ], [ "# single out a specific country to look at.\nchina = df[df.country == 'China']\n\n# set a few year dates to look for infomation specifc to those years.\nchina[china.year.isin([1818, 1918, 2018])]", "_____no_output_____" ], [ "# single out a specific country to look at.\nlesotho = df[df.country == 'Lesotho']\n# set a few year dates to look for infomation specifc to those years.\nlesotho[lesotho.year.isin([1818, 1918, 2018])]", "_____no_output_____" ] ], [ [ "## Plot visualization", "_____no_output_____" ] ], [ [ "# create a data set of just a particular year.\nnow = df[df.year ==2018]\n# show the shape of the data set.\nnow.shape", "_____no_output_____" ], [ "# use .relpot(), to create a scatter plot with color options for 'region6' for 2018.\nsns.relplot(x=\"income\", y=\"lifespan\", hue=\"region6\", size=\"population\",\n sizes=(40, 200), alpha=.5, palette=\"muted\", height=6, data=now);", "_____no_output_____" ] ], [ [ "## Analyze outliers, highest average income in 2018.", "_____no_output_____" ] ], [ [ "# sort the data set by the 'income' column include only 80000 or more, and sort =Flase to put highest income on top.\nnow[now.income > 80000].sort_values(by='income', ascending=False)", "_____no_output_____" ], [ "# add info to aspecific data point, here we will add the 'name' to the top data point 'Qatar'.\n\n# single out the top 'income' country 'Qatar', \nqatar = now[now.country == 'Qatar']\n# find/set the income values for 'Qatar', so the chart has a value.\nqatar_income = qatar.income.values[0]\n# find/set the 'lifepsan' values for 'Qatar', so the chart has a value.\nqatar_lifespan = qatar.lifespan.values[0]", "_____no_output_____" ], [ "# use sns.replot() to create a scatter plot with colors/sizes for the 'region6' based on 'income' & 'lifespan' for 2018.\nsns.relplot(x=\"income\", y=\"lifespan\", hue=\"region6\", size=\"population\",\n sizes=(40, 200), alpha=.5, palette=\"muted\", height=6, data=now);\n# add a title to the chart so it visually makes sense.\nplt.title('Qatar has the highest average incomes in 2018', fontsize=15)\n# add the test of 'Qatar' and a location of the to income data point that is 'Qatar'.\nplt.text(x=qatar_income-7000, y=qatar_lifespan+1, s = 'Qatar = $121,033');", "_____no_output_____" ] ], [ [ "## Analyze outliers, lowest average lifespan in 2018.\n\n", "_____no_output_____" ] ], [ [ "# add info to aspecific data point, here we will add the 'name' to the lowest 'lifespan' data point 'Lesotho'.\n\n# single out the lowest 'lifespan' country 'Lesotho'.\nlesotho = now[now.country == 'Lesotho']\n# find/set the income values for 'Qatar', so the chart has a value.\nlesotho_income = lesotho.income.values[0]\n# find/set the 'lifepsan' values for 'Qatar', so the chart has a value.\nlesotho_lifespan = lesotho.lifespan.values[0]", "_____no_output_____" ], [ "# use sns.replot() to create a scatter plot with colors/sizes for the 'region6' based on 'income' & 'lifespan' for 2018.\nsns.relplot(x=\"income\", y=\"lifespan\", hue=\"region6\", size=\"population\",\n sizes=(40, 200), alpha=.5, palette=\"muted\", height=6, data=now);\n# add a title to the chart so it visually makes sense.\nplt.title('Lesotho has the lowest average lifespan in 2018', fontsize=15)\n# add the test of 'Qatar' and a location of the to income data point that is 'Qatar'.\nplt.text(x=lesotho_income-7000, y=lesotho_lifespan+1, s = 'Lesotho = 51.12 years');", "_____no_output_____" ] ], [ [ "## Plot multiple years", "_____no_output_____" ] ], [ [ "# plot multiple years by setting the years we want to use.\nyears = [1988, 1998, 2008, 2018]\n# use .isin() to remove any years we did not list.\ncenturies = df[df.year.isin(years)]\n# show the data frame shape.\ncenturies.shape", "_____no_output_____" ] ], [ [ "## Point out a story", "_____no_output_____" ] ], [ [ "# use sns.replot() to create a scatter plot with colors/sizes for the 'region6' based on 'income' & 'lifespan' for the years we set.\nsns.relplot(x=\"income\", y=\"lifespan\", hue=\"region6\", size=\"population\", col='year',\n sizes=(40, 200), alpha=.5, palette=\"muted\", height=6, data=centuries);", "_____no_output_____" ] ], [ [ "# STRETCH OPTIONS\n\n## 1. Animate!\n- [Making animations work in Google Colaboratory](https://medium.com/lambda-school-machine-learning/making-animations-work-in-google-colaboratory-new-home-for-ml-prototyping-c6147186ae75)\n- [How to Create Animated Graphs in Python](https://towardsdatascience.com/how-to-create-animated-graphs-in-python-bb619cc2dec1)\n- [The Ultimate Day of Chicago Bikeshare](https://chrisluedtke.github.io/divvy-data.html) (Lambda School Data Science student)\n\n## 2. Work on anything related to your portfolio site / project", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a535cc012aa0ba032bda32ffab69812a910d719
69,720
ipynb
Jupyter Notebook
PyCity.ipynb
LoriWard/pandas-challenge
c10c080db05da3a963d4720a5b61bc4cad5c5c18
[ "MIT" ]
null
null
null
PyCity.ipynb
LoriWard/pandas-challenge
c10c080db05da3a963d4720a5b61bc4cad5c5c18
[ "MIT" ]
null
null
null
PyCity.ipynb
LoriWard/pandas-challenge
c10c080db05da3a963d4720a5b61bc4cad5c5c18
[ "MIT" ]
null
null
null
36.810982
362
0.401334
[ [ [ "# Dependencies and Setup\n\nimport os\nimport pandas as pd\n\n", "_____no_output_____" ], [ "# Files to Load \n\nschool_data_to_load = r\"C:\\Users\\matt\\Desktop\\pandas-challenge\\Resources\\schools_complete.csv\"\nstudent_data_to_load = r\"C:\\Users\\matt\\Desktop\\pandas-challenge\\Resources\\students_complete.csv\"", "_____no_output_____" ], [ "# Read School and Student Data Files \n\nschool_data = pd.read_csv(school_data_to_load)\nstudent_data = pd.read_csv(student_data_to_load)\n\nschool_data.head()\nstudent_data.head()\n\n", "_____no_output_____" ], [ "#Merge the two data files into a single dataset\nschool_data_complete = pd.merge(student_data, school_data, how=\"left\", on=[\"school_name\", \"school_name\"])\nschool_data_complete.head()", "_____no_output_____" ], [ "#District Summary\n\n\n#Total Number of Schools\ntotal_schools = school_data_complete[\"school_name\"].count()\nprint(\"Total Schools:\",total_schools)\n\n\n#Total Number of Students\ntotal_students = school_data_complete[\"student_name\"].count()\nprint(\"Total Students:\",total_students)\n\n\n#Total Budget\ntotal_budget = school_data_complete[\"budget\"].sum()\nprint(\"Total Budget:\",total_budget)\n\n\n#Average Math Score\naverage_math = student_data[\"math_score\"].mean()\nprint(\"Average Math Score:\",average_math)\n\n\n#Average Reading Score\naverage_reading = student_data[\"reading_score\"].mean()\nprint(\"Average Reading Score:\",average_reading )\n\n\n#Percent Passing Math\npassing_math = school_data_complete.loc[student_data[\"math_score\"] >= 70, [\"math_score\"]]\npassing_math_count= passing_math[\"math_score\"].count()\npercent_passing_math = passing_math_count/total_students\nprint(\"% Passing Math:\",percent_passing_math)\n\n\n#Percent Passing Reading\npassing_reading = school_data_complete.loc[student_data[\"reading_score\"] >= 70, [\"reading_score\"]]\npassing_reading_count= passing_reading[\"reading_score\"].count()\npercent_passing_reading = passing_reading_count/total_students\nprint(\"% Passing Reading:\",percent_passing_reading)\n\n\n#Percent Overall Passing (The percentage of students that passed math and reading)\noverall_passing = school_data_complete[(student_data[\"math_score\"] >= 70) & (student_data[\"reading_score\"] >= 70)][\"student_name\"].count()/total_students\nprint (\"% Overall Passing:\",overall_passing)", "Total Schools: 39170\nTotal Students: 39170\nTotal Budget: 82932329558\nAverage Math Score: 78.98537145774827\nAverage Reading Score: 81.87784018381414\n% Passing Math: 0.749808526933878\n% Passing Reading: 0.8580546336482001\n% Overall Passing: 0.6517232575950983\n" ], [ "#District Summary Dataframe\n\ndistrict_summary = pd.DataFrame({\"Total Schools\": [total_schools],\"Total Students\": [total_students],\"Total Budget\":[total_budget],\"Average Math Score\": [average_math],\"Average Reading Score\": [average_reading], \"% Passing Math\":[percent_passing_math],\"% Passing Reading\":[percent_passing_reading],\"% Overall Passing\":[overall_passing]})\n\ndistrict_summary", "_____no_output_____" ], [ "#School Summary \n\n#Group by school name \ngrouped_school = school_data_complete.groupby([\"school_name\"])\n\n#School type\nschool_type = grouped_school[\"type\"].first()\n\n#Total students per school\ntotal_students = grouped_school.size()\n\n#Total budget per school\ntotal_budget = grouped_school[\"budget\"].first()\n\n#Budget per student\nbudget_per_student = total_budget/total_students\n\n#Average math score per school\naverage_math_score = grouped_school[\"math_score\"].mean()\n\n#Average reading score per school\naverage_reading_score = grouped_school[\"reading_score\"].mean()\n\n#Percent passing math\ngrouped_passing_math = school_data_complete[school_data_complete[\"math_score\"]>=70].groupby([\"school_name\"]).size()\npercent_passing_math = (grouped_passing_math/total_students)*100\n\n\n#Percent passing reading\ngrouped_passing_reading = school_data_complete[school_data_complete[\"reading_score\"]>=70].groupby([\"school_name\"]).size()\npercent_passing_reading = (grouped_passing_reading/total_students)*100\n\n\n#Percent passing overall (passing math and reading)\n#THIS IS NOT THE CORRECT PERCENTAGE???????????? NEED TO FIGURE OUT HOW TO GET THE NUMBER WHO PASSED BOTH THEN DIVIDE BY THE TOTAL NUMBER OF STUDENTS\n#percent_overall_passing = (percent_passing_math + percent_passing_reading)/2\noverall_passing = school_data_complete[(school_data_complete[\"reading_score\"] >= 70) & (school_data_complete[\"math_score\"] >= 70)].groupby([\"school_name\"]).size()\n\npercent_overall_passing = (overall_passing/total_students)*100\n\n\n#Create dataframe \nschool={\n 'School Type': school_type,\n 'Total Students':total_students,\n 'Total School Budget': total_budget,\n 'Per Student Budget': budget_per_student,\n 'Average Math Score': average_math_score,\n 'Average Reading Score': average_reading_score,\n '% Passing Math': percent_passing_math,\n '% Passing Reading': percent_passing_reading,\n '% Overall Passing': percent_overall_passing,\n}\n\n\n\nschool_summary = pd.DataFrame(school)\n\n\nschool_summary", "_____no_output_____" ], [ "#Top Performing Schools (By % Overall Passing)\n\ntop_performing_schools = school_summary.nlargest(5, \"% Overall Passing\")\ntop_performing_schools", "_____no_output_____" ], [ "#Bottom Performing Schools (By % Overall Passing)\n\nbottom_performing_schools = school_summary.nsmallest(5, \"% Overall Passing\")\nbottom_performing_schools\n", "_____no_output_____" ], [ "#Average math scores by grade\n\n\n# Calculate the average math score for students of each grade at each school\nschool_math_average_9th = school_data_complete[school_data_complete[\"grade\"]==\"9th\"].groupby(\"school_name\")[\"math_score\"].mean()\n\nschool_math_average_10th = school_data_complete[school_data_complete[\"grade\"]==\"10th\"].groupby(\"school_name\")[\"math_score\"].mean()\n\nschool_math_average_11th = school_data_complete[school_data_complete[\"grade\"]==\"11th\"].groupby(\"school_name\")[\"math_score\"].mean()\n\nschool_math_average_12th = school_data_complete[school_data_complete[\"grade\"]==\"12th\"].groupby(\"school_name\")[\"math_score\"].mean()\n\n# Create a dataframe to hold the above results\ngrade_math_score={\n \"9th grade\":school_math_average_9th,\n \"10th grade\":school_math_average_10th,\n \"11th grade\":school_math_average_11th,\n \"12th grade\":school_math_average_12th,\n }\n\nmath_score_by_grade = pd.DataFrame(grade_math_score)\n\nmath_score_by_grade\n\n\n\n\n\n \n \n \n ", "_____no_output_____" ], [ "#Average reading scores by grade\n\n\n# Calculate the average reading score for students of each grade at each school\nschool_reading_average_9th = school_data_complete[school_data_complete[\"grade\"]==\"9th\"].groupby(\"school_name\")[\"reading_score\"].mean()\n\nschool_reading_average_10th = school_data_complete[school_data_complete[\"grade\"]==\"10th\"].groupby(\"school_name\")[\"reading_score\"].mean()\n\nschool_reading_average_11th = school_data_complete[school_data_complete[\"grade\"]==\"11th\"].groupby(\"school_name\")[\"reading_score\"].mean()\n\nschool_reading_average_12th = school_data_complete[school_data_complete[\"grade\"]==\"12th\"].groupby(\"school_name\")[\"reading_score\"].mean()\n\n# Create a dataframe to hold the above results\ngrade_reading_score={\n \"9th grade\":school_reading_average_9th,\n \"10th grade\":school_reading_average_10th,\n \"11th grade\":school_reading_average_11th,\n \"12th grade\":school_reading_average_12th,\n }\n\nreading_score_by_grade = pd.DataFrame(grade_reading_score)\n\nreading_score_by_grade\n", "_____no_output_____" ], [ "#Scores by School Spending\n\n#Bins for spending ranges\nspending_bins = [0, 585, 630, 645, 675]\nspending_bin_names = [\"<$585\", \"$585-629\", \"$630-644\", \"$645-675\"]\n\n\n#Create school score data frame \nscores__by_spending = school_summary.loc[:,[\"Average Math Score\",\n \"Average Reading Score\",\"% Passing Math\",\n \"% Passing Reading\",\"% Overall Passing\"]]\n\n#Cut scores into spending bins\nscores__by_spending['Spending Ranges (Per Student)']= pd.cut(school_summary['Per Student Budget'],spending_bins,labels=spending_bin_names)\n\n\n#Groupby spending ranges\nscores__by_spending = scores__by_spending.groupby('Spending Ranges (Per Student)').mean()\nscores__by_spending\n\n", "_____no_output_____" ], [ "#Scores by School Size\n\n#Bins for school size ranges\nschool_size_bins = [0, 1000, 2000, 5000]\nschool_size_bin_names = [\"Small (<1000)\", \"Medium (1000-2000)\", \"Large (2000-5000)\"]\n\n\n#Create school score data frame \nscores__by_school_size = school_summary.loc[:,[\"Average Math Score\",\n \"Average Reading Score\",\"% Passing Math\",\n \"% Passing Reading\",\"% Overall Passing\"]]\n\n#Cut scores into school size bins\nscores__by_school_size[\"School Size\"]= pd.cut(school_summary[\"Total Students\"],school_size_bins,labels=school_size_bin_names)\n\n\n#Groupby school size ranges\nscores__by_school_size = scores__by_school_size.groupby(\"School Size\").mean()\nscores__by_school_size", "_____no_output_____" ], [ "#Scores by School Type\n\n\nscores_by_school_type = school_summary[[\"School Type\",\"Average Math Score\",\n \"Average Reading Score\", \n \"% Passing Math\", \n \"% Passing Reading\", \n \"% Overall Passing\"]]\n\n\nscores_by_school_type = scores_by_school_type.groupby(\"School Type\").mean()\nscores_by_school_type", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a537715f476475e52caa82fa6fbca3e9191d3c7
14,768
ipynb
Jupyter Notebook
use_case/use_case_2.ipynb
Sametle06/benchmark_Platform
b2def71ba4293df60f07686977d9edebe4a3dd7b
[ "Unlicense" ]
null
null
null
use_case/use_case_2.ipynb
Sametle06/benchmark_Platform
b2def71ba4293df60f07686977d9edebe4a3dd7b
[ "Unlicense" ]
null
null
null
use_case/use_case_2.ipynb
Sametle06/benchmark_Platform
b2def71ba4293df60f07686977d9edebe4a3dd7b
[ "Unlicense" ]
null
null
null
32.528634
1,203
0.599743
[ [ [ "# Use Case", "_____no_output_____" ], [ "PROFAB is a benchmarking platform that is expected to fill the gap of datasets about protein functions with total 7656 datasets. In addition to protein function datasets, ProFAB provides complete sets of preprocessing-training-evaluation triangle to speed up machine learning usage in biological studies. Since the workflow is dense, an easy to implement user case is prepared. The difference from use_case_1, here, it is shown that how user can import his/her dataset and following ProFAB modules.", "_____no_output_____" ], [ "## 1. Data Importing", "_____no_output_____" ], [ "ProFAB provides users to import their datasets that are not available in ProFAB. To import data, SelfGet() function will be savior:", "_____no_output_____" ] ], [ [ "import sys\nsys.path.insert(0, '../')", "_____no_output_____" ], [ "from profab.import_dataset import SelfGet\ndata = SelfGet(delimiter = '\\t', name = False, label = False).get_data(file_name = \"sample.txt\")", "_____no_output_____" ] ], [ [ "Explanation of parameters is available in \"import_dataset\" section. With these functions, users can manage dataset \nconstruction. If s/he has positive set of any term available in ProFAB, only negative set can be obtained by setting \nparameter 'label' = 'negative'. For example, let's say user has positive set for EC number 1-2-7 and wants to get\nnegative set to use in prediction, following lines can be executed:", "_____no_output_____" ] ], [ [ "from profab.import_dataset import SelfGet, ECNO\nnegative_set = ECNO(label = 'negative').get_data('ecNo_1-2-7')\npositive_set = SelfGet().get_data('users_1-2-7_positive_set.txt')", "_____no_output_____" ] ], [ [ "After loading datasets, preprocessing step comes in.", "_____no_output_____" ], [ "## 2. PreProcessing", "_____no_output_____" ], [ "Preprocessing is applicable in three sections which are featurization, splitting and scaling. ", "_____no_output_____" ], [ "### a. Featurization", "_____no_output_____" ], [ "Featurization is used to convert protein fasta file into numearical feature data with many protein descriptors. Detailed \nexplanation can be found in \"model_preprocess\". This function is only applicable with LINUX and MAC operation systems and input file format must be '.fasta'. Following lines can be run:", "_____no_output_____" ] ], [ [ "from profab.model_preprocess import extract_protein_feature\nextract_protein_feature('edp', 1, \n 'directory_folder_input_file', \n 'sample')", "_____no_output_____" ] ], [ [ "After running this function, a new file that holds numerical features of proteins will be formed and it can be imported via SelfGet() function as shown in previous section.", "_____no_output_____" ], [ "### b. Splitting", "_____no_output_____" ], [ "Another preprocessing module is splitting module that is to prepare train, validation (if needed) and test sets\nfor prediction. Detailed information is available in \"model_preprocess\" and reading it is highly recommended to see how function is working. If one has X (feature matrix) and y\n(label matrix), by defining fraction of test set, splitting can be done:", "_____no_output_____" ] ], [ [ "from profab.model_preprocess import ttv_split\nX_train,X_test,y_train,y_test = ttv_split(X,y,ratio)", "_____no_output_____" ] ], [ [ "Rather than giving all data, user can choose to feed 'ttv_split' function with positive and negative sets and s/he can be obtain splitted data, eventually.", "_____no_output_____" ] ], [ [ "from profab.model_preprocess import ttv_split\nX_train,X_test,y_train,y_test = ttv_split(X_pos,X_neg,ratio)", "_____no_output_____" ] ], [ [ "If data is regression tasked, then y (label matrix) must be given.", "_____no_output_____" ], [ "### c. Scaling", "_____no_output_____" ], [ "Scaling is a function to rearange the range of inputs points. The reason to do it prevent imbalance problem. If data \nis stable then this function is unnecessary to apply. like other preprocessing steps, its detailed introduction can \nfound in 'model_preprocess'. A use case:", "_____no_output_____" ] ], [ [ "from profab.model_preprocess import scale_methods\nX_train,scaler = scale_methods(X_train,scale_type = 'standard')\nX_test = scaler.transform(X_test)", "_____no_output_____" ] ], [ [ "Scaling function returns fitted train (X_train) data and fitting model (scaler) to transform other sets as can be seen in use case. The rest is exactly the same as 'test_file_1'.", "_____no_output_____" ], [ "## 3. Training", "_____no_output_____" ], [ "PROFAB can train any type of data. It provides both classification and regression training. Since our datasets are based on classication of proteins, as an example, classification method will be shown.\n\nAfter training session, outcome of training can be stored in 'model_path' ```if path is not None```. Because this process lasts to long, saving the outcome will be time-saver. Stored model must be exported and be imported with 'pickle' a python based package.", "_____no_output_____" ] ], [ [ "from profab.model_learn import classification_methods\n\n#Let's define model path where training model will be saved.\nmodel_path = 'model_path.txt'\n\nmodel = classification_methods(ml_type = 'logistic_reg',\n X_train = X_train,\n y_train = y_train,\n path = model_path\n )", "_____no_output_____" ] ], [ [ "## 3. Evaluation", "_____no_output_____" ], [ "After training session is done, evaluation can be done with following lines of code. The output of evaluation is given below of code.", "_____no_output_____" ], [ "### a. Get Scores", "_____no_output_____" ] ], [ [ "from profab.model_evaluate import evaluate_score\n\nscore_train,f_train = evaluate_score(model,X_train,y_train,preds = True)\nscore_test,f_test = evaluate_score(model,X_test,y_test,preds = True)\nscore_validation,f_validation = evaluate_score(model,X_validation,y_validation,preds = True)", "_____no_output_____" ] ], [ [ "The score of train and test are given for data: 'ecNo_1-2-7 'target'.", "_____no_output_____" ], [ "### b. Table Formating", "_____no_output_____" ], [ "To get the data in table format, a dictionary that consists of scores of different sets must be given. Following lines of code can be executed to tabularize the results:", "_____no_output_____" ] ], [ [ "#If user wants to see result in a table, following codes can be run:\nfrom profab.model_evaluate import form_table\n\nscore_path = 'score_path.csv' #To save the results.\n\nscores = {'train':score_train,'test':score_test,'validation':score_validation}\n\n#form_table() function will write scores to score_path.\nform_table(scores = scores, path = score_path)", "_____no_output_____" ] ], [ [ "## 5. Working with Multiple Set", "_____no_output_____" ], [ "If user wants to make a prediction uses multiple class, ProFAB can handle this with 'for-loop'. For this case, let's say user has positive and negative datasets for 2 GO terms which names of files are:\n\n - GO_0000018_negative_data.txt\n - GO_0019935_negative_data.txt\n - GO_0000018_positive_data.txt\n - GO_0019935_positive_data.txt\n\nBoth files are tab separated and protein features are described with their name.\nSo, this time using SelfGet() function with parameter 'name' = True will be efficient to load negative datasets.", "_____no_output_____" ] ], [ [ "import sys\nsys.path.insert(0, '../')", "_____no_output_____" ], [ "from profab.import_dataset import GOID, SelfGet\nfrom profab.model_preprocess import ttv_split\nfrom profab.model_learn import classification_methods\nfrom profab.model_evaluate import evaluate_score, multiple_form_table\n\n#GO_List: variable includes GO terms\nGO_list = ['GO_0000018','GO_0019935']\n\n#To hold scores of model performances\nscores = {}\n\nfor go_term in GO_list: \n\n #User imports his/her negative and positive datasets with SelfGet() function\n negative_data_name = go_term + '_negative_data.txt'\n negative_set = SelfGet(name = True).get_data(file_name = negative_data_name)\n positive_data_name = go_term + '_positive_data.txt'\n positive_set = SelfGet(name = True).get_data(file_name = positive_data_name)\n \n #splitting\n X_train,X_test,X_validation,y_train,y_test,y_validation = ttv_split(X_pos = positive_set,\n X_neg = negative_set,\n ratio = [0.1,0.2])\n #prediction\n model = classification_methods(ml_type = 'SVM',\n X_train = X_train,\n X_valid = X_validation,\n y_train = y_train,\n y_valid = y_validation)\n \n #evaluation\n score_train = evaluate_score(model,X_train,y_train) \n score_test = evaluate_score(model,X_test,y_test)\n set_scores = {'train':score_train,'test': score_test}\n scores.update({go_term:set_scores})\n\n#tabularizing the scores\nscore_path = 'score_path.csv'\nmultiple_form_table(scores, score_path)", "SVC(C=49.50251256281407, gamma=0.0517947467923121, kernel='linear',\n max_iter=2500)\nSVC(C=49.50251256281407, gamma=0.0517947467923121, kernel='linear',\n max_iter=2500)\n" ], [ "print(scores)", "{'GO_0000018': {'train': {'Precision': 0.680365296803653, 'Recall': 0.4257142857142857, 'F1-Score': 0.523725834797891, 'F05-Score': 0.6076672104404568, 'Accuracy': 0.7426400759734093, 'MCC': 0.37854022684114785, 'AUC': 0.6630705141231458, 'AUPRC': 0.6484813867005648, 'TP': 149, 'FP': 70, 'TN': 633, 'FN': 201}, 'test': {'Precision': 0.7352941176470589, 'Recall': 0.49019607843137253, 'F1-Score': 0.588235294117647, 'F05-Score': 0.6684491978609626, 'Accuracy': 0.7682119205298014, 'MCC': 0.4531328287625726, 'AUC': 0.7000980392156864, 'AUPRC': 0.6988378132710038, 'TP': 25, 'FP': 9, 'TN': 91, 'FN': 26}}, 'GO_0019935': {'train': {'Precision': 0.765661252900232, 'Recall': 0.6043956043956044, 'F1-Score': 0.67553735926305, 'F05-Score': 0.7268722466960352, 'Accuracy': 0.8022457891453525, 'MCC': 0.543894233191604, 'AUC': 0.7544210756131287, 'AUPRC': 0.7524021030084921, 'TP': 330, 'FP': 101, 'TN': 956, 'FN': 216}, 'test': {'Precision': 0.775, 'Recall': 0.49206349206349204, 'F1-Score': 0.6019417475728155, 'F05-Score': 0.695067264573991, 'Accuracy': 0.8217391304347826, 'MCC': 0.5155438600770936, 'AUC': 0.719085638247315, 'AUPRC': 0.7030969634230503, 'TP': 31, 'FP': 9, 'TN': 158, 'FN': 32}}}\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
4a538960c4e2c7f43f74fec78c892ebee2233cc2
252,925
ipynb
Jupyter Notebook
notebooks/03.10-Creating-Simulation-Classes.ipynb
jckantor/CBE40455-2020
318bd71b7259c6f2f810cc55f268e2477c6b8cfd
[ "MIT" ]
6
2020-08-18T13:22:49.000Z
2020-12-31T23:30:56.000Z
notebooks/03.10-Creating-Simulation-Classes.ipynb
jckantor/CBE40455-2020
318bd71b7259c6f2f810cc55f268e2477c6b8cfd
[ "MIT" ]
null
null
null
notebooks/03.10-Creating-Simulation-Classes.ipynb
jckantor/CBE40455-2020
318bd71b7259c6f2f810cc55f268e2477c6b8cfd
[ "MIT" ]
2
2020-11-07T21:36:12.000Z
2021-12-11T20:38:20.000Z
243.197115
75,216
0.912709
[ [ [ "# Objected-Oriented Simulation\n\nUp to this point we have been using Python generators and shared resources as the building blocks for simulations of complex systems. This can be effective, particularly if the individual agents do not require access to the internal state of other agents. But there are situations where the action of an agent depends on the state or properties of another agent in the simulation. For example, consider this discussion question from the Grocery store checkout example:\n\n>Suppose we were to change one or more of the lanes to a express lanes which handle only with a small number of items, say five or fewer. How would you expect this to change average waiting time? This is a form of prioritization ... are there other prioritizations that you might consider?\n\nThe customer action depends the item limit parameter associated with a checkout lane. This is a case where the action of one agent depends on a property of another. The shared resources builtin to the SimPy library provide some functionality in this regard, but how do add this to the simulations we write?\n\nThe good news is that Python offers a rich array of object oriented programming features well suited to this purpose. The SymPy documentation provides excellent examples of how to create Python objects for use in SymPy. The bad news is that object oriented programming in Python -- while straightforward compared to many other programming languages -- constitutes a steep learning curve for students unfamiliar with the core concepts.\n\nFortunately, since the introduction of Python 3.7 in 2018, the standard libraries for Python have included a simplified method for creating and using Python classes. Using [dataclass](https://realpython.com/python-data-classes/), it easy to create objects for SymPy simulations that retain the benefits of object oriented programming without all of the coding overhead. \n\nThe purpose of this notebook is to introduce the use of `dataclass` in creating SymPy simulations. To the best of the author's knowledge, this is a novel use of `dataclass` and the only example of which the author is aware.", "_____no_output_____" ], [ "## Installations and imports", "_____no_output_____" ] ], [ [ "!pip install sympy", "Requirement already satisfied: sympy in /Users/jeff/opt/anaconda3/lib/python3.7/site-packages (1.5.1)\nRequirement already satisfied: mpmath>=0.19 in /Users/jeff/opt/anaconda3/lib/python3.7/site-packages (from sympy) (1.1.0)\n" ], [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nimport simpy\nimport pandas as pd\nfrom dataclasses import dataclass", "_____no_output_____" ], [ "import sys\nprint(sys.version)", "3.7.4 (default, Aug 13 2019, 15:17:50) \n[Clang 4.0.1 (tags/RELEASE_401/final)]\n" ] ], [ [ "Additional imports are from the `dataclasses` library that has been part of the standard Python distribution since version 3.7. Here we import `dataclass` and `field`.", "_____no_output_____" ] ], [ [ "from dataclasses import dataclass, field", "_____no_output_____" ] ], [ [ "## Introduction to `dataclass`\n\nTutorials and additional documentation:\n\n* [The Ultimate Guide to Data Classes in Python 3.7](https://realpython.com/python-data-classes/): Tutorial article from ReaalPython.com\n* [dataclasses — Data Classes](https://docs.python.org/3/library/dataclasses.html): Official Python documentation.\n* [Data Classes in Python](https://towardsdatascience.com/data-classes-in-python-8d1a09c1294b): Tutorial from TowardsDataScience.com", "_____no_output_____" ], [ "### Creating a `dataclass`\n\nA `dataclass` defines a new class of Python objects. A `dataclass` object takes care of several routine things that you would otherwise have to code, such as creating instances of an object, testing for equality, and other aspects. \n\nAs an example, the following cell shows how to define a dataclass corresponding to a hypothetical Student object. The Student object maintains data associated with instances of a student. The dataclass also defines a function associated with the object.", "_____no_output_____" ] ], [ [ "from dataclasses import dataclass\n\n@dataclass\nclass Student():\n name: str\n graduation_class: int\n dorm: str\n \n def print_name(self):\n print(f\"{self.name} (Class of {self.graduation_class})\")", "_____no_output_____" ] ], [ [ "Let's create an instance of the Student object.", "_____no_output_____" ] ], [ [ "sam = Student(\"Sam Jones\", 2024, \"Alumni\")", "_____no_output_____" ] ], [ [ "Let's see how the `print_name()` function works.", "_____no_output_____" ] ], [ [ "sam.print_name()", "Sam Jones (Class of 2024)\n" ] ], [ [ "The next cell shows how to create a list of students, and how to iterate over a list of students.", "_____no_output_____" ] ], [ [ "# create a list of students\nstudents = [\n Student(\"Sam Jones\", 2024, \"Alumni\"),\n Student(\"Becky Smith\", 2023, \"Howard\"),\n]\n\n# iterate over the list of students to print all of their names\nfor student in students:\n student.print_name()\n print(student.dorm)", "Sam Jones (Class of 2024)\nAlumni\nBecky Smith (Class of 2023)\nHoward\n" ] ], [ [ "Here are a few details you need to use `dataclass` effectively:\n\n* The `class` statement is standard statement for creating a new class of Python objects. The preceding `@dataclass` is a Python 'decorator'. Decorators are Python functions that modify the behavior of subsequent statements. In this case, the `@dataclass` decorator modifies `class` to provide a streamlined syntax for implementing classes.\n* A Python class names begin with a capital letter. In this case `Student` is the class name.\n* The lines following the the class statement declare parameters that will be used by the new class. The parameters can be specified when you create an instance of the dataclass. \n* Each paraameter is followed by type 'hint'. Commonly used type hints are `int`, `float`, `bool`, and `str`. Use the keyword `any` you don't know or can't specify a particular type. Type hints are actually used by type-checking tools and ignored by the python interpreter.\n* Following the parameters, write any functions or generators that you may wish to define for the new class. To access variables unique to an instance of the class, preceed the parameter name with `self`.", "_____no_output_____" ], [ "### Specifying parameter values\n\nThere are different ways of specifying the parameter values assigned to an instance of a dataclass. Here are three particular methods:\n\n* Specify the parameter value when creating a new instance. This is what was done in the Student example above.\n* Provide a default values determined when the dataclass is defined.\n* Provide a default_factory method to create a parameter value when an instance of the dataclass is created.", "_____no_output_____" ], [ "#### Specifying a parameter value when creating a new instance\n\nParameter values can be specified when creating an instance of a dataclass. The parameter values can be specified by position or by name as shown below.", "_____no_output_____" ] ], [ [ "from dataclasses import dataclass\n\n@dataclass\nclass Student():\n name: str\n graduation_year: int\n dorm: str\n \n def print_name(self):\n print(f\"{self.name} (Class of {self.graduation_year})\")\n \nsam = Student(\"Sam Jones\", 2031, \"Alumni\")\nsam.print_name()\n\ngilda = Student(name=\"Gilda Radner\", graduation_year=2030, dorm=\"Howard\")\ngilda.print_name()", "Sam Jones (Class of 2031)\nGilda Radner (Class of 2030)\n" ] ], [ [ "#### Setting default parameter values\n\nSetting a default value for a parameter can save extra typing or coding. More importantly, setting default values makes it easier to maintain and adapt code for other applications, and is a convenient way to handle missing data. \n\nThere are two ways to set default parameter values. For str, int, float, bool, tuple (the immutable types in Python), a default value can be set using `=` as shown in the next cell.", "_____no_output_____" ] ], [ [ "from dataclasses import dataclass\n\n@dataclass\nclass Student():\n name: str = None\n graduation_year: int = None\n dorm: str = None\n \n def print_name(self):\n print(f\"{self.name} (Class of {self.graduation_year})\")\n \njdoe = Student(name=\"John Doe\", dorm=\"Alumni\")\njdoe.print_name()", "John Doe (Class of None)\n" ] ], [ [ "Default parameter values are restricted to 'immutable' types. This technical restriction eliminiates the error-prone practice of use mutable objects, such as lists, as defaults. The difficulty with setting defaults for mutable objects is that all instances of the dataclass share the same value. If one instance of the object changes that value, then all other instances are affected. This leads to unpredictable behavior, and is a particularly nasty bug to uncover and fix.\n\nThere are two ways to provide defaults for mutable parameters such as lists, sets, dictionaries, or arbitrary Python objects. \n\nThe more direct way is to specify a function for constucting the default parameter value using the `field` statement with the `default_factory` option. The default_factory is called when a new instance of the dataclass is created. The function must take no arguments and must return a value that will be assigned to the designated parameter. Here's an example.", "_____no_output_____" ] ], [ [ "from dataclasses import dataclass\n\n@dataclass\nclass Student():\n name: str = None\n graduation_year: int = None\n dorm: str = None\n majors: list = field(default_factory=list)\n \n def print_name(self):\n print(f\"{self.name} (Class of {self.graduation_year})\")\n \n def print_majors(self):\n for n, major in enumerate(self.majors):\n print(f\" {n+1}. {major}\")\n \njdoe = Student(name=\"John Doe\", dorm=\"Alumni\", majors=[\"Math\", \"Chemical Engineering\"])\njdoe.print_name()\njdoe.print_majors()\n\nStudent().print_majors()", "John Doe (Class of None)\n 1. Math\n 2. Chemical Engineering\n" ] ], [ [ "#### Initializing a dataclass with __post_init__(self)\n\nFrequently there are additional steps to complete when creating a new instance of a dataclass. For that purpose, a dataclass may contain an\noptional function with the special name `__post_init__(self)`. If present, that function is run automatically following the creation of a new instance. This feature will be demonstrated in following reimplementation of the grocery store checkout operation.", "_____no_output_____" ], [ "## Using `dataclass` with Simpy", "_____no_output_____" ], [ "### Step 0. A simple model\n\nTo demonstrate the use of classes in SimPy simulations, let's begin with a simple model of a clock using generators.", "_____no_output_____" ] ], [ [ "import simpy\n\ndef clock(id=\"\", t_step=1.0):\n while True:\n print(id, env.now)\n yield env.timeout(t_step)\n \nenv = simpy.Environment()\nenv.process(clock(\"A\"))\nenv.process(clock(\"B\", 1.5))\nenv.run(until=5.0)", "A 0\nB 0\nA 1.0\nB 1.5\nA 2.0\nB 3.0\nA 3.0\nA 4.0\nB 4.5\n" ] ], [ [ "### Step 1. Embed the generator inside of a class", "_____no_output_____" ], [ "As a first step, we rewrite the generator as a Python dataclass named `Clock`. The parameters are given default values, and the generator is incorporated within the Clock object. Note the use of `self` to refer to parameters specific to an instance of the class.", "_____no_output_____" ] ], [ [ "import simpy\nfrom dataclasses import dataclass\n\n@dataclass\nclass Clock():\n id: str = \"\"\n t_step: float = 1.0\n \n def process(self):\n while True:\n print(self.id, env.now)\n yield env.timeout(self.t_step)\n\nenv = simpy.Environment()\nenv.process(Clock(\"A\").process())\nenv.process(Clock(\"B\", 1.5).process())\nenv.run(until=5)", "A 0\nB 0\nA 1.0\nB 1.5\nA 2.0\nB 3.0\nA 3.0\nA 4.0\nB 4.5\n" ] ], [ [ "### Step 2. Eliminate (if possible) global variables\n\nOur definition of clock requires the simulation environment to have a specific name `env`, and assumes env is a global variable. That's generally not a good coding practice because it imposes an assumption on any user of the class, and exposes the internal coding of the class. A much better practice is to use class parameters to pass this data through a well defined interface to the class.", "_____no_output_____" ] ], [ [ "import simpy\nfrom dataclasses import dataclass\n\n@dataclass\nclass Clock():\n env: simpy.Environment\n id: str = \"\"\n t_step: float = 1.0\n \n def process(self):\n while True:\n print(self.id, self.env.now)\n yield self.env.timeout(self.t_step)\n\nenv = simpy.Environment()\nenv.process(Clock(env, \"A\").process())\nenv.process(Clock(env, \"B\", 1.5).process())\nenv.run(until=10)", "A 0\nB 0\nA 1.0\nB 1.5\nA 2.0\nB 3.0\nA 3.0\nA 4.0\nB 4.5\nA 5.0\nB 6.0\nA 6.0\nA 7.0\nB 7.5\nA 8.0\nB 9.0\nA 9.0\n" ] ], [ [ "### Step 3. Encapsulate initializations inside __post_init__", "_____no_output_____" ] ], [ [ "import simpy\nfrom dataclasses import dataclass\n\n@dataclass\nclass Clock():\n env: simpy.Environment\n id: str = \"\"\n t_step: float = 1.0\n \n def __post_init__(self):\n self.env.process(self.process())\n \n def process(self):\n while True:\n print(self.id, self.env.now)\n yield self.env.timeout(self.t_step)\n\nenv = simpy.Environment()\nClock(env, \"A\")\nClock(env, \"B\", 1.5)\nenv.run(until=5)", "A 0\nB 0\nA 1.0\nB 1.5\nA 2.0\nB 3.0\nA 3.0\nA 4.0\nB 4.5\n" ] ], [ [ "## Grocery Store Model\n\nLet's review our model for the grocery store checkout operations. There are multiple checkout lanes, each with potentially different characteristics. With generators we were able to implement differences in the time required to scan items. But another parameter, a limit on number of items that could be checked out in a lane, required a new global list. The reason was the need to access that parameter, something that a generator doesn't allow. This is where classes become important building blocks in creating more complex simulations.\n\nOur new strategy will be encapsulate the generator inside of a dataclass object. Here's what we'll ask each class definition to do:\n\n* Create a parameter corresponding to the simulation environment. This makes our classes reusable in other simulations by eliminating a reference to a globall variable.\n* Create parameters with reasonable defaults values.\n* Initialize any objects used within the class.\n* Register the class generator with the simulation environment.\n", "_____no_output_____" ] ], [ [ "from dataclasses import dataclass\n\n# create simulation models\n@dataclass\nclass Checkout():\n env: simpy.Environment\n lane: simpy.Store = None\n t_item: float = 1/10\n item_limit: int = 25\n t_payment: float = 2.0\n \n def __post_init__(self):\n self.lane = simpy.Store(self.env)\n self.env.process(self.process())\n \n def process(self):\n while True:\n customer_id, cart, enter_time = yield self.lane.get()\n wait_time = env.now - enter_time\n yield env.timeout(self.t_payment + cart*self.t_item)\n customer_log.append([customer_id, cart, enter_time, wait_time, env.now]) \n \n@dataclass\nclass CustomerGenerator():\n env: simpy.Environment\n rate: float = 1.0\n customer_id: int = 1\n \n def __post_init__(self):\n self.env.process(self.process())\n \n def process(self):\n while True:\n yield env.timeout(random.expovariate(self.rate))\n cart = random.randint(1, 25)\n available_checkouts = [checkout for checkout in checkouts if cart <= checkout.item_limit]\n checkout = min(available_checkouts, key=lambda checkout: len(checkout.lane.items))\n yield checkout.lane.put([self.customer_id, cart, env.now])\n self.customer_id += 1\n\ndef lane_logger(t_sample=0.1):\n while True:\n lane_log.append([env.now] + [len(checkout.lane.items) for checkout in checkouts])\n yield env.timeout(t_sample)\n \n# create simulation environment\nenv = simpy.Environment()\n\n# create simulation objects (agents)\nCustomerGenerator(env)\ncheckouts = [\n Checkout(env, t_item=1/5, item_limit=25),\n Checkout(env, t_item=1/5, item_limit=25),\n Checkout(env, item_limit=5),\n Checkout(env),\n Checkout(env),\n]\nenv.process(lane_logger())\n\n# run process\ncustomer_log = []\nlane_log = []\nenv.run(until=600)", "_____no_output_____" ], [ "def visualize():\n\n # extract lane data\n lane_df = pd.DataFrame(lane_log, columns = [\"time\"] + [f\"lane {n}\" for n in range(0, len(checkouts))])\n lane_df = lane_df.set_index(\"time\")\n\n customer_df = pd.DataFrame(customer_log, columns = [\"customer id\", \"cart items\", \"enter\", \"wait\", \"leave\"])\n customer_df[\"elapsed\"] = customer_df[\"leave\"] - customer_df[\"enter\"]\n\n # compute kpi's\n print(f\"Average waiting time = {customer_df['wait'].mean():5.2f} minutes\")\n print(f\"\\nAverage lane queue \\n{lane_df.mean()}\")\n print(f\"\\nOverall aaverage lane queue \\n{lane_df.mean().mean():5.4f}\")\n\n # plot results\n fig, ax = plt.subplots(3, 1, figsize=(12, 7))\n ax[0].plot(lane_df)\n ax[0].set_xlabel(\"time / min\")\n ax[0].set_title(\"length of checkout lanes\")\n ax[0].legend(lane_df.columns)\n\n ax[1].bar(customer_df[\"customer id\"], customer_df[\"wait\"])\n ax[1].set_xlabel(\"customer id\")\n ax[1].set_ylabel(\"minutes\")\n ax[1].set_title(\"customer waiting time\")\n\n ax[2].bar(customer_df[\"customer id\"], customer_df[\"elapsed\"])\n ax[2].set_xlabel(\"customer id\")\n ax[2].set_ylabel(\"minutes\")\n ax[2].set_title(\"total elapsed time\")\n plt.tight_layout()\n \nvisualize()", "Average waiting time = 4.18 minutes\n\nAverage lane queue \nlane 0 1.406500\nlane 1 1.192167\nlane 2 0.050667\nlane 3 0.840000\nlane 4 0.635833\ndtype: float64\n\nOverall aaverage lane queue \n0.8250\n" ] ], [ [ "## Customers as agents", "_____no_output_____" ] ], [ [ "from dataclasses import dataclass\n\n# create simulation models\n@dataclass\nclass Checkout():\n env: simpy.Environment\n lane: simpy.Store = None\n t_item: float = 1/10\n item_limit: int = 25\n t_payment: float = 2.0\n \n def __post_init__(self):\n self.lane = simpy.Store(self.env)\n self.env.process(self.process())\n \n def process(self):\n while True:\n customer_id, cart, enter_time = yield self.lane.get()\n wait_time = env.now - enter_time\n yield env.timeout(self.t_payment + cart*self.t_item)\n customer_log.append([customer_id, cart, enter_time, wait_time, env.now]) \n \n@dataclass\nclass CustomerGenerator():\n env: simpy.Environment\n rate: float = 1.0\n customer_id: int = 1\n \n def __post_init__(self):\n self.env.process(self.process())\n \n def process(self):\n while True:\n yield env.timeout(random.expovariate(self.rate))\n Customer(self.env, self.customer_id)\n self.customer_id += 1\n \n@dataclass\nclass Customer():\n env: simpy.Environment\n id: int = 0\n \n def __post_init__(self):\n self.cart = random.randint(1, 25)\n self.env.process(self.process())\n \n def process(self):\n available_checkouts = [checkout for checkout in checkouts if self.cart <= checkout.item_limit]\n checkout = min(available_checkouts, key=lambda checkout: len(checkout.lane.items))\n yield checkout.lane.put([self.id, self.cart, env.now])\n \n\ndef lane_logger(t_sample=0.1):\n while True:\n lane_log.append([env.now] + [len(checkout.lane.items) for checkout in checkouts])\n yield env.timeout(t_sample)\n \n# create simulation environment\nenv = simpy.Environment()\n\n# create simulation objects (agents)\nCustomerGenerator(env)\ncheckouts = [\n Checkout(env, t_item=1/5, item_limit=25),\n Checkout(env, t_item=1/5, item_limit=25),\n Checkout(env, item_limit=5),\n Checkout(env),\n Checkout(env),\n]\nenv.process(lane_logger())\n\n# run process\ncustomer_log = []\nlane_log = []\nenv.run(until=600)\n\nvisualize()", "Average waiting time = 3.26 minutes\n\nAverage lane queue \nlane 0 1.080167\nlane 1 0.954167\nlane 2 0.063167\nlane 3 0.590333\nlane 4 0.362167\ndtype: float64\n\nOverall aaverage lane queue \n0.6100\n" ] ], [ [ "## Creating Smart Objects", "_____no_output_____" ] ], [ [ "from dataclasses import dataclass, field\nimport pandas as pd\n\n# create simulation models\n@dataclass\nclass Checkout():\n lane: simpy.Store\n t_item: float = 1/10\n item_limit: int = 25\n \n def process(self):\n while True:\n customer_id, cart, enter_time = yield self.lane.get()\n wait_time = env.now - enter_time\n yield env.timeout(t_payment + cart*self.t_item)\n customer_log.append([customer_id, cart, enter_time, wait_time, env.now]) \n \n@dataclass\nclass CustomerGenerator():\n rate: float = 1.0\n customer_id: int = 1\n \n def process(self):\n while True:\n yield env.timeout(random.expovariate(self.rate))\n cart = random.randint(1, 25)\n available_checkouts = [checkout for checkout in checkouts if cart <= checkout.item_limit]\n checkout = min(available_checkouts, key=lambda checkout: len(checkout.lane.items))\n yield checkout.lane.put([self.customer_id, cart, env.now])\n self.customer_id += 1\n\n@dataclass\nclass LaneLogger():\n lane_log: list = field(default_factory=list) # this creates a variable that can be modified\n t_sample: float = 0.1\n lane_df: pd.DataFrame = field(default_factory=pd.DataFrame)\n \n def process(self):\n while True:\n self.lane_log.append([env.now] + [len(checkout.lane.items) for checkout in checkouts])\n yield env.timeout(self.t_sample)\n \n def report(self):\n self.lane_df = pd.DataFrame(self.lane_log, columns = [\"time\"] + [f\"lane {n}\" for n in range(0, N)])\n self.lane_df = self.lane_df.set_index(\"time\")\n print(f\"\\nAverage lane queue \\n{self.lane_df.mean()}\")\n print(f\"\\nOverall average lane queue \\n{self.lane_df.mean().mean():5.4f}\")\n \n def plot(self):\n self.lane_df = pd.DataFrame(self.lane_log, columns = [\"time\"] + [f\"lane {n}\" for n in range(0, N)])\n self.lane_df = self.lane_df.set_index(\"time\") \n fig, ax = plt.subplots(1, 1, figsize=(12, 3))\n ax.plot(self.lane_df)\n ax.set_xlabel(\"time / min\")\n ax.set_title(\"length of checkout lanes\")\n ax.legend(self.lane_df.columns) \n \n# create simulation environment\nenv = simpy.Environment()\n\n# create simulation objects (agents)\ncustomer_generator = CustomerGenerator()\ncheckouts = [\n Checkout(simpy.Store(env), t_item=1/5),\n Checkout(simpy.Store(env), t_item=1/5),\n Checkout(simpy.Store(env), item_limit=5),\n Checkout(simpy.Store(env)),\n Checkout(simpy.Store(env)),\n]\nlane_logger = LaneLogger()\n\n# register agents\nenv.process(customer_generator.process())\nfor checkout in checkouts:\n env.process(checkout.process()) \nenv.process(lane_logger.process())\n\n# run process\nenv.run(until=600)\n\n# plot results\nlane_logger.report()\nlane_logger.plot()", "\nAverage lane queue \nlane 0 1.167000\nlane 1 0.937500\nlane 2 0.056500\nlane 3 0.615833\nlane 4 0.317333\ndtype: float64\n\nOverall average lane queue \n0.6188\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a538a66c2000daf2826f3c4021f702656d50495
20,835
ipynb
Jupyter Notebook
book/week_04/01-Why-Numpy.ipynb
fmaussion/scientific_programming
e757ba944f485b3754fbbe27e289ca03741bb6fa
[ "CC-BY-4.0" ]
26
2018-04-24T13:37:33.000Z
2021-11-29T14:04:35.000Z
book/week_04/01-Why-Numpy.ipynb
fmaussion/scientific_programming
e757ba944f485b3754fbbe27e289ca03741bb6fa
[ "CC-BY-4.0" ]
14
2020-10-07T11:21:20.000Z
2022-03-20T17:39:18.000Z
book/week_04/01-Why-Numpy.ipynb
fmaussion/scientific_programming
e757ba944f485b3754fbbe27e289ca03741bb6fa
[ "CC-BY-4.0" ]
14
2018-04-03T10:17:42.000Z
2021-11-08T14:33:06.000Z
37.405745
807
0.641901
[ [ [ "# 01 - Introduction to numpy: why does numpy exist?", "_____no_output_____" ], [ "You might have read somewhere that Python is \"slow\" in comparison to some other languages. While generally true, this statement has only little meaning without context. As a scripting language (e.g. simplify tasks such as file renaming, data download, etc.), python is fast enough. For *numerical computations* (like the computations done by an atmospheric model or by a machine learning algorithm), \"pure\" Python is very slow indeed. Fortunately, there is a way to overcome this problem!\n\nIn this chapter we are going to explain why the [numpy](http://numpy.org) library was created. Numpy is the fundamental library which transformed the general purpose python language into a scientific language like Matlab, R or IDL.\n\nBefore introducing numpy, we will discuss some of the differences between python and compiled languages widely used in scientific software development (like C and FORTRAN).", "_____no_output_____" ], [ "## Why is python \"slow\"?", "_____no_output_____" ], [ "In the next unit about numbers, we'll learn that the memory consumption of a python ``int`` is larger than the memory needed to store the binary number alone. This overhead in memory consumption is due to the nature of python data types, which are all **objects**. We've already learned that these objects come with certain \"services\".", "_____no_output_____" ], [ "Everything is an object in Python. Yes, even functions are objects! Let me prove it to you:", "_____no_output_____" ] ], [ [ "def useful_function(a, b):\n \"\"\"This function adds two objects together.\n\n Parameters\n ----------\n a : an object\n b : another object\n\n Returns\n -------\n The sum of the two\n \"\"\"\n return a + b", "_____no_output_____" ], [ "type(useful_function)", "_____no_output_____" ], [ "print(useful_function.__doc__)", "_____no_output_____" ] ], [ [ "Functions are objects of type ``function``, and one of their attributes (``__doc__``) gives us access to their **docstring**. During the course of the semester you are going to learn how to use more and more of these object features, and hopefully you are going to like them more and more (at least this is what happened to me).\n\nNow, why does this make python \"slow\"? Well, in simple terms, these \"services\" tend to increase the complexity and the number of operations an interpreter has to perform when running a program. More specialized languages will be less flexible than python, but will be faster at running specialized operations and be less memory hungry (because they don't need this overhead of flexible memory on top of every object).\n\nPython's high-level of abstraction (i.e. python's flexibility) makes it slower than its lower-level counterparts like C or FORTRAN. But, why is that so?", "_____no_output_____" ], [ "## Dynamically versus statically typed languages ", "_____no_output_____" ], [ "Python is a so-called **dynamically typed** language, which means that the **type** of a variable is determined by the interpreter *at run time*. To understand what that means in practice, let's have a look at the following code snippet:", "_____no_output_____" ] ], [ [ "a = 2\nb = 3", "_____no_output_____" ], [ "c = a + b", "_____no_output_____" ] ], [ [ "The line ``c = a + b`` is valid python syntax. The *operation* that has to be applied by the ``+`` operator, however, depends on the type of the variables to be added. Remember what happens when adding two lists for example: ", "_____no_output_____" ] ], [ [ "a = [2]\nb = [3]\na + b", "_____no_output_____" ] ], [ [ "In this simple example it would be theoretically possible for the interpreter to predict which operation to apply beforehand (by parsing all lines of code prior to the action). In most cases, however, this is impossible: for example, a function taking arguments does not know beforehand the type of the arguments it will receive.\n\nLanguages which assess the type of variables *at run time* are called [dynamically typed programming languages](https://en.wikipedia.org/wiki/Category:Dynamically_typed_programming_languages). Matlab, Python or R are examples falling in this category.", "_____no_output_____" ], [ "**Statically typed languages**, however, require the *programmer* to provide the type of variables while writing the code. Here is an example of a program written in C:", "_____no_output_____" ], [ "```c\n#include <stdio.h> \nint main ()\n{\n int a = 2;\n int b = 3;\n int c = a + b;\n printf (\"Sum of two numbers : %d \\n\", c);\n}\n```", "_____no_output_____" ], [ "The major difference with the Python code above is that the programmer indicated the type of the variables when they are assigned. Variable type definition in the code script is an integral part of the C syntax. This applies to the variables themselves, but also to the output of computations. This is a fundamental difference to python, and comes with several advantages. Static typing usually results in code that executes faster: since the program knows the exact data types that are in use, it can predict the memory consumption of operations beforehand and produce optimized machine code. Another advantage is code documentation: the statement ``int c = a + b`` makes it clear that we are adding two numbers while the python equivalent ``c = a + b`` could produce a number, a string, a list, etc.", "_____no_output_____" ], [ "## Compiled versus interpreted languages", "_____no_output_____" ], [ "Statically typed languages often require **compilation**. To run the C code snippet I had to create a new text file (``example.c``), write the code, compile it (``$ gcc -o myprogram example.c``), before finally being able to execute it (``$ ./myprogram``).\n\n[gcc](https://en.wikipedia.org/wiki/GNU_Compiler_Collection) is the compiler I used to translate the C source code (a text file) to a low level language (machine code) in order to create an **executable** (``myprogram``). Later changes to the source code require a new compilation step for the changes to take effect.\n\nBecause of this \"edit-compile-run\" cycle, compiled languages are not interactive: in the C language, there is no equivalent to python's command line interpreter. Compiling complex programs can take up to several hours in some extreme cases. This compilation time, however, is usually associated with faster execution times: as mentioned earlier, the compiler's task is to optimize the program for memory consumption by source code analysis. Often, a compiled program is optimized for the machine architecture it is compiled onto. Like interpreters, there can be different compilers for the same language. They differ in the optimization steps they undertake to make the program faster, and in their support of various hardware architectures.", "_____no_output_____" ], [ "**Interpreters** do not require compilation: they analyze the code at run time. The following code for example is syntactically correct:", "_____no_output_____" ] ], [ [ "def my_func(a, b):\n return a + b", "_____no_output_____" ] ], [ [ "but the *execution* of this code results in a `TypeError` when the variables have the wrong type:", "_____no_output_____" ] ], [ [ "my_func(1, '2')", "_____no_output_____" ] ], [ [ "The interpreter cannot detect these errors before runtime: they happen when the variables are finally added together, not when they are created.", "_____no_output_____" ], [ "**Parenthesis I: python bytecode** \n\nWhen executing a python program from the command line, the CPython interpreter creates a hidden directory called ``__pycache__``. This directory contains [bytecode](https://en.wikipedia.org/wiki/Bytecode) files, which are your python source code files translated to binary files. This is an optimization step which makes subsequent executions of the program run faster. While this conversion step is sometimes called \"compilation\", it should not be mistaken with a C-program compilation: indeed, python bytecode still needs an interpreter to run, while compiled executables can be run without C interpreter.", "_____no_output_____" ], [ "**Parenthesis II: static typing and compilation**\n\nStatically typed languages are often compiled, and dynamically typed languages are often interpreted. While this is a good rule of thumb, this is not always true and the vast landscape of programming languages contains many exceptions. This lecture is only a very short introduction to these concepts: you'll have to refer to more advanced computer science lectures if you want to learn about these topics in more detail. ", "_____no_output_____" ], [ "## Here comes numpy ", "_____no_output_____" ], [ "Let's summarize the two previous chapters: \n- Python is flexible, interactive and slow\n- C is less flexible, non-interactive and fast\n\nThis is a simplification, but not far from the truth. \n\nNow, let's add another obstacle to using python for science: the built-in `list` data type in python is mostly useless for arithmetics or vector computations. Indeed, to add two lists together element-wise (a behavior that you would expect as a scientist), you must write:", "_____no_output_____" ] ], [ [ "def add_lists(A, B):\n \"\"\"Element-wise addition of two lists.\"\"\"\n return [a + b for a, b in zip(A, B)]", "_____no_output_____" ], [ "add_lists([1, 2, 3], [4, 5, 6])", "_____no_output_____" ] ], [ [ "The numpy equivalent is much more intuitive and straightforward:", "_____no_output_____" ] ], [ [ "import numpy as np\n\n\ndef add_arrays(A, B):\n return np.add(A, B)", "_____no_output_____" ], [ "add_arrays([1, 2, 3], [4, 5, 6])", "_____no_output_____" ] ], [ [ "Let's see which of the two functions runs faster:", "_____no_output_____" ] ], [ [ "n = 10\nA = np.random.randn(n)\nB = np.random.randn(n)", "_____no_output_____" ], [ "%timeit add_lists(A, B)", "_____no_output_____" ], [ "%timeit add_arrays(A, B)", "_____no_output_____" ] ], [ [ "Numpy is approximately 5-6 times faster.", "_____no_output_____" ], [ "```{exercise}\nRepeat the performance test with n=100 and n=10000. How does the performance scale with the size of the array? Now repeat the test but make the input arguments ``A`` and ``B`` *lists* instead of numpy arrays. How is the performance comparison in this case? Why?\n```", "_____no_output_____" ], [ "Why is numpy so much faster than pure python? One of the major reasons is **vectorization**, which is the process of applying mathematical operations to *all* elements of an array (\"vector\") at once instead of looping through them like we would do in pure python. \"for loops\" in python are slow because for each addition, python has to:\n- access the elements a and b in the lists A and B\n- check the type of both a and b\n- apply the ``+`` operator on the data they store\n- store the result.\n\nNumpy skips the first two steps and does them only once before the actual operation. What does numpy know about the addition operation that the pure python version can't infer?\n- the type of all numbers to add\n- the type of the output\n- the size of the output array (same as input)\n\nNumpy can use this information to optimize the computation, but this isn't possible without trade-offs. See the following for example:", "_____no_output_____" ] ], [ [ "add_lists([1, 'foo'], [3, 'bar']) # works fine", "_____no_output_____" ], [ "add_arrays([1, 'foo'], [3, 'bar']) # raises a TypeError", "_____no_output_____" ] ], [ [ "$\\rightarrow$ **numpy can only be that fast because the input and output data types are uniform and known before the operation**.", "_____no_output_____" ], [ "Internally, numpy achieves vectorization by relying on a lower-level, statically typed and compiled language: C! At the time of writing, about 35% of the [numpy codebase](https://github.com/numpy/numpy) is written in C/C++. The rest of the codebase offers an interface (a \"layer\") between python and the internal C code. \n\nAs a result, numpy has to be *compiled* at installation. Most users do not notice this compilation step anymore (recent pip and conda installations are shipped with pre-compiled binaries), but installing numpy used to require several minutes on my laptop when I started to learn python myself.", "_____no_output_____" ], [ "## Take home points", "_____no_output_____" ], [ "- The process of \"type checking\" may occur either at compile-time (statically typed language) or at runtime (dynamically typed language). These terms are not usually used in a strict sense.\n- Statically typed languages are often compiled, while dynamically typed languages are interpreted.\n- There is a trade-off between the flexibility of a language and its speed: static typing allows programs to be optimized at compilation time, thus allowing them to run faster. But writing code in a statically typed language is slower, especially for interactive data exploration (not really possible in fact).\n- When speed matters, python allows to use compiled libraries under a python interface. numpy is using C under the hood to optimize its computations.\n- numpy arrays use a continuous block of memory of homogenous data type. This allows for faster memory access and easy vectorization of mathematical operations.", "_____no_output_____" ], [ "## Further reading ", "_____no_output_____" ], [ "I highly recommend to have a look at the first part of Jake Vanderplas' blog post, [Why python is slow](https://jakevdp.github.io/blog/2014/05/09/why-python-is-slow/) (up to the \"hacking\" part). It provides more details and a good visual illustration of the ``c = a + b`` example. The second part is a more involved read, but very interesting too!", "_____no_output_____" ], [ "## Addendum: is python really *that* slow? ", "_____no_output_____" ], [ "The short answer is: yes, python is slower than a number of other languages. You'll find many benchmarks online illustrating it. \n\nIs it bad? \n\nNo. Jake Vanderplas (a well known contributor of the scientific python community) [writes](https://jakevdp.github.io/blog/2014/05/09/why-python-is-slow/#So-Why-Use-Python?):\n\n*As well, it comes down to this: dynamic typing makes Python easier to use than C. It's extremely flexible and forgiving, this flexibility leads to efficient use of development time, and on those occasions that you really need the optimization of C or Fortran, Python offers easy hooks into compiled libraries. It's why Python use within many scientific communities has been continually growing. With all that put together, Python ends up being an extremely efficient language for the overall task of doing science with code.*\n\nIt's the flexibility and readability of python that makes it so popular. Python is the language of choice for major actors like [instagram](https://www.youtube.com/watch?v=66XoCk79kjM) or [spotify](https://labs.spotify.com/2013/03/20/how-we-use-python-at-spotify/), and it has become the high-level interface to highly optimized machine learning libraries like [TensorFlow](https://github.com/tensorflow/tensorflow) or [Torch](http://pytorch.org/). \n\nFor a scientist, writing code efficiently is *much* more important than writing efficient code. Or [is it](https://xkcd.com/1205/)?", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4a539bc5b50262c4fd390e05176e1610975da3e4
134,452
ipynb
Jupyter Notebook
notebooks/with-output/openscale-quality-with-output.ipynb
sakanmfec/cloudpakfordata_workshop
7d19e544c8b7e873ddaf5a26d604d5c15ea11b15
[ "Apache-2.0" ]
10
2020-05-20T07:43:41.000Z
2021-07-02T04:49:52.000Z
notebooks/with-output/openscale-quality-with-output.ipynb
sakanmfec/cloudpakfordata_workshop
7d19e544c8b7e873ddaf5a26d604d5c15ea11b15
[ "Apache-2.0" ]
63
2019-09-18T13:17:38.000Z
2021-06-14T20:59:32.000Z
notebooks/with-output/openscale-quality-with-output.ipynb
sakanmfec/cloudpakfordata_workshop
7d19e544c8b7e873ddaf5a26d604d5c15ea11b15
[ "Apache-2.0" ]
27
2019-11-02T07:42:50.000Z
2021-07-16T14:22:08.000Z
62.448676
12,436
0.491015
[ [ [ "<img src=\"https://github.com/pmservice/ai-openscale-tutorials/raw/master/notebooks/images/banner.png\" align=\"left\" alt=\"banner\">", "_____no_output_____" ], [ "# Working with Watson Machine Learning - Quality Monitor and Feedback Logging", "_____no_output_____" ], [ "### Contents\n\n- [1.0 Install Python Packages](#setup)\n- [2.0 Configure Credentials](#credentials)\n- [3.0 OpenScale configuration](#openscale)\n- [4.0 Get Subscriptions](#subscription)\n- [5.0 Quality monitoring and Feedback logging](#quality)", "_____no_output_____" ], [ "# 1.0 Install Python Packages", "_____no_output_____" ] ], [ [ "!rm -rf /home/spark/shared/user-libs/python3.6*\n\n!pip install --upgrade ibm-ai-openscale==2.2.1 --no-cache | tail -n 1\n!pip install --upgrade watson-machine-learning-client-V4==1.0.55 | tail -n 1\n!pip install --upgrade pyspark==2.3 | tail -n 1", "Requirement already satisfied, skipping upgrade: six in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from h5py->ibm-ai-openscale==2.2.1) (1.12.0)\nRequirement already satisfied, skipping upgrade: docutils<0.16,>=0.10 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from ibm-cos-sdk-core>=2.0.0->ibm-cos-sdk->watson-machine-learning-client-V4==1.0.55) (0.14)\nRequirement already satisfied, skipping upgrade: py4j==0.10.6 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from pyspark==2.3) (0.10.6)\n" ] ], [ [ "### Action: restart the kernel!", "_____no_output_____" ], [ "# 2.0 Configure credentials <a name=\"credentials\"></a>\n\n", "_____no_output_____" ] ], [ [ "import warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ] ], [ [ "The url for `WOS_CREDENTIALS` is the url of the CP4D cluster, i.e. `https://zen-cpd-zen.apps.com`. `username` and `password` must be ones that have cluster admin privileges.", "_____no_output_____" ] ], [ [ "WOS_CREDENTIALS = {\n \"url\": \"https://zen-cpd-zen.cp4d-2bef4fc2b2-0001.us-south.containers.appdomain.cloud\",\n \"username\": \"*****\",\n \"password\": \"*****\"\n}", "_____no_output_____" ], [ "WML_CREDENTIALS = WOS_CREDENTIALS.copy()\nWML_CREDENTIALS['instance_id']='openshift'\nWML_CREDENTIALS['version']='2.5.0'", "_____no_output_____" ], [ "%store -r MODEL_NAME\n%store -r DEPLOYMENT_NAME\n%store -r DEFAULT_SPACE", "_____no_output_____" ] ], [ [ "# 3.0 Configure OpenScale <a name=\"openscale\"></a>", "_____no_output_____" ], [ "The notebook will now import the necessary libraries and configure OpenScale", "_____no_output_____" ] ], [ [ "from watson_machine_learning_client import WatsonMachineLearningAPIClient\nimport json\n\nwml_client = WatsonMachineLearningAPIClient(WML_CREDENTIALS)", "_____no_output_____" ], [ "from ibm_ai_openscale import APIClient4ICP\nfrom ibm_ai_openscale.engines import *\nfrom ibm_ai_openscale.utils import *\nfrom ibm_ai_openscale.supporting_classes import PayloadRecord, Feature\nfrom ibm_ai_openscale.supporting_classes.enums import *", "_____no_output_____" ], [ "ai_client = APIClient4ICP(WOS_CREDENTIALS)\nai_client.version", "_____no_output_____" ] ], [ [ "# 4.0 Get Subscription <a name=\"subscription\"></a>", "_____no_output_____" ] ], [ [ "subscription = None\n\nif subscription is None:\n subscriptions_uids = ai_client.data_mart.subscriptions.get_uids()\n for sub in subscriptions_uids:\n if ai_client.data_mart.subscriptions.get_details(sub)['entity']['asset']['name'] == MODEL_NAME:\n print(\"Found existing subscription.\")\n subscription = ai_client.data_mart.subscriptions.get(sub)\nif subscription is None:\n print(\"No subscription found. Please run openscale-initial-setup.ipynb to configure.\")", "Found existing subscription.\n" ] ], [ [ "### Set Deployment UID", "_____no_output_____" ] ], [ [ "wml_client.set.default_space(DEFAULT_SPACE)", "_____no_output_____" ], [ "wml_deployments = wml_client.deployments.get_details()\ndeployment_uid = None\nfor deployment in wml_deployments['resources']:\n print(deployment['entity']['name'])\n if DEPLOYMENT_NAME == deployment['entity']['name']:\n deployment_uid = deployment['metadata']['guid']\n break\n \nprint(deployment_uid)", "sda-deployment-6-17-2020\n8d1e7718-a378-422e-83f0-3bcbcc2baf34\n" ] ], [ [ "# 5.0 Quality monitoring and Feedback logging\n <a name=\"quality\"></a>", "_____no_output_____" ], [ "## 4.1 Enable quality monitoring", "_____no_output_____" ], [ "The code below waits ten seconds to allow the payload logging table to be set up before it begins enabling monitors. First, it turns on the quality (accuracy) monitor and sets an alert threshold of 70%. OpenScale will show an alert on the dashboard if the model accuracy measurement (area under the curve, in the case of a binary classifier) falls below this threshold.\n\nThe second paramater supplied, min_records, specifies the minimum number of feedback records OpenScale needs before it calculates a new measurement. The quality monitor runs hourly, but the accuracy reading in the dashboard will not change until an additional 50 feedback records have been added, via the user interface, the Python client, or the supplied feedback endpoint.", "_____no_output_____" ] ], [ [ "subscription.quality_monitoring.enable(threshold=0.7, min_records=50)", "_____no_output_____" ] ], [ [ "## 4.2 Feedback logging", "_____no_output_____" ], [ "The code below downloads and stores enough feedback data to meet the minimum threshold so that OpenScale can calculate a new accuracy measurement. It then kicks off the accuracy monitor. The monitors run hourly, or can be initiated via the Python API, the REST API, or the graphical user interface.", "_____no_output_____" ] ], [ [ "!rm additional_feedback_data.json\n!wget https://raw.githubusercontent.com/IBM/monitor-ibm-cloud-pak-with-watson-openscale/master/data/additional_feedback_data.json\n", "rm: cannot remove 'additional_feedback_data.json': No such file or directory\n--2020-06-23 22:27:46-- https://raw.githubusercontent.com/IBM/monitor-ibm-cloud-pak-with-watson-openscale/master/data/additional_feedback_data.json\nResolving raw.githubusercontent.com (raw.githubusercontent.com)... 199.232.8.133\nConnecting to raw.githubusercontent.com (raw.githubusercontent.com)|199.232.8.133|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 16506 (16K) [text/plain]\nSaving to: 'additional_feedback_data.json'\n\n100%[======================================>] 16,506 --.-K/s in 0.001s \n\n2020-06-23 22:27:46 (16.0 MB/s) - 'additional_feedback_data.json' saved [16506/16506]\n\n" ], [ "with open('additional_feedback_data.json') as feedback_file:\n additional_feedback_data = json.load(feedback_file)\nsubscription.feedback_logging.store(additional_feedback_data['data'])", "_____no_output_____" ], [ "subscription.feedback_logging.show_table()", "_____no_output_____" ], [ "run_details = subscription.quality_monitoring.run(background_mode=False)", "\n\n================================================================================\n\n Waiting for end of quality monitoring run 97c61aa0-338a-4d30-b8c7-16bcb12f317f \n\n================================================================================\n\n\n\ncompleted\n\n---------------------------\n Successfully finished run \n---------------------------\n\n\n" ], [ "subscription.quality_monitoring.show_table()", "_____no_output_____" ], [ "%matplotlib inline\n\nquality_pd = subscription.quality_monitoring.get_table_content(format='pandas')\nquality_pd.plot.barh(x='id', y='value');", "_____no_output_____" ], [ "ai_client.data_mart.get_deployment_metrics()", "_____no_output_____" ] ], [ [ "## Congratulations!\n\nYou have finished the hands-on lab for IBM Watson OpenScale. You can now view the OpenScale dashboard by going to the CPD `Home` page, and clicking `Services`. Choose the `OpenScale` tile and click the menu to `Open`. Click on the tile for the model you've created to see Quality monitor. Click on the timeseries graph to get detailed information on transactions during a specific time window.\n\nOpenScale shows model performance over time. You have two options to keep data flowing to your OpenScale graphs:\n * Download, configure and schedule the [model feed notebook](https://raw.githubusercontent.com/emartensibm/german-credit/master/german_credit_scoring_feed.ipynb). This notebook can be set up with your WML credentials, and scheduled to provide a consistent flow of scoring requests to your model, which will appear in your OpenScale monitors.\n * Re-run this notebook. Running this notebook from the beginning will delete and re-create the model and deployment, and re-create the historical data. Please note that the payload and measurement logs for the previous deployment will continue to be stored in your datamart, and can be deleted if necessary.", "_____no_output_____" ], [ "## Authors\n\nEric Martens, is a technical specialist having expertise in analysis and description of business processes, and their translation into functional and non-functional IT requirements. He acts as the interpreter between the worlds of IT and business.\n\nLukasz Cmielowski, PhD, is an Automation Architect and Data Scientist at IBM with a track record of developing enterprise-level applications that substantially increases clients' ability to turn data into actionable knowledge.\n\nZilu (Peter) Tang, is a cognitive developer with experties in deep learning and enterprise AI solutions from Watson Openscale to many other cutting-edge IBM research projects.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ] ]
4a539cfd58ce7be1a39bdab8e811dec96afde944
321,283
ipynb
Jupyter Notebook
dip_notes/13_first_filter.ipynb
ZaynChen/notes
37a71aac067ff86d89fc4654782d9a483472e91f
[ "MulanPSL-1.0" ]
null
null
null
dip_notes/13_first_filter.ipynb
ZaynChen/notes
37a71aac067ff86d89fc4654782d9a483472e91f
[ "MulanPSL-1.0" ]
null
null
null
dip_notes/13_first_filter.ipynb
ZaynChen/notes
37a71aac067ff86d89fc4654782d9a483472e91f
[ "MulanPSL-1.0" ]
null
null
null
2,345.131387
119,178
0.963599
[ [ [ "import numpy as np\n\nfrom utils import *\n", "_____no_output_____" ], [ "def S(v):\n if v > 255: return 255\n if v < 0: return 0\n return (np.uint8)(v)\n\ndef filter(f):\n h = get_length(f, 0)\n w = get_length(f, 1)\n\n g = np.zeros((h, w))\n\n for x in range(1, h-1):\n for y in range(1, w-1):\n g[x, y] = S(f[x, y]*5+f[x-1, y]*(-1)+f[x+1, y]\n * (-1)+f[x, y-1]*(-1)+f[x, y+1]*(-1))\n\n return g\n\ndef filter2(f, mask):\n h = get_length(f, 0)\n w = get_length(f, 1)\n\n M = get_length(mask, 0) // 2\n N = get_length(mask, 1) // 2\n\n g = np.zeros((h, w))\n\n for x in range(M, h-M):\n for y in range(N, w-N):\n s = 0\n for m in range(-M, M+1):\n for n in range(-N, N+1):\n s += f[x+m, y+n] * mask[M+m, N+n]\n g[x, y] = S(s)\n\n return g\n\ndef main(imp):\n f = load_image(imp)\n show_img(\"f\", f)\n\n show_img(\"filter\", filter(f))\n\n mask = np.zeros((3,3))\n mask[0, 1] = mask[1, 0] = mask[1, 2] = mask[2, 1] = -1\n mask[1, 1] = 5\n\n show_img(\"filter2\", filter2(f, mask))\n\nimp = \"images/lena256.bmp\"\nmain(imp)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
4a539f928ff5cdf5d18179418abd15dea7946ad5
118,715
ipynb
Jupyter Notebook
becapredictm_limpieza.ipynb
ederfg/dssbeca18
6c1db5b7968df4280c9df67d576dd668352f2da2
[ "MIT" ]
null
null
null
becapredictm_limpieza.ipynb
ederfg/dssbeca18
6c1db5b7968df4280c9df67d576dd668352f2da2
[ "MIT" ]
null
null
null
becapredictm_limpieza.ipynb
ederfg/dssbeca18
6c1db5b7968df4280c9df67d576dd668352f2da2
[ "MIT" ]
null
null
null
87.742055
42,820
0.631319
[ [ [ "# importamos librerias necesarias\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport numpy as np \nimport pandas as pd ", "_____no_output_____" ], [ "# importando dataset\nbecariospdb = pd.read_csv('perdidadebecas.csv')\nprint(becariospdb.head(1))", " convocatoria region motivo \\\n0 Beca 18 Modalidad Ordinaria 2012 LIMA Becarios que desaprobaron \n\n resolucion_ret_beca fec_resolucion_ret_beca fec_Postulacion \\\n0 RESOLUCION JEFATURAL 2014-11 2012-04 \n\n tipoinstitucion institucioneducativa institucionsede \\\n0 Universidad NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n\n carreradescripcion genero \n0 INGENIERIA GEOLOGICA MASCULINO \n" ], [ "# Tenemos como objetivo predecir el motivo por el cual puede renunciar un becario\n# Para usar la tecnica de arbol de decision solo dos tipos de la categoria motivo\n# Por ello trabajaremos solo con los siguientes: \n# Becarios que desaprobaron = 1 \n# Becarios que abandonaron los estudios (No recibieron subvencion) = 0\n# Por lo tanto eliminamos de la categoria motivo el resto de tipos.\n\nbecariospdbv1 = becariospdb[(becariospdb.motivo !='Becario Egresado Aprobado') &\n (becariospdb.motivo != 'Becarios que renunciaron') &\n (becariospdb.motivo != 'Becario Egresado Desaprobado') &\n (becariospdb.motivo != 'Becarios declarados nulos') &\n (becariospdb.motivo != 'Becarios que falsificaron información') &\n (becariospdb.motivo != 'Becarios que no se presentaron con RJ (No recibieron subvencion)') &\n (becariospdb.motivo != 'Becarios que abandonaron los estudios (Recibieron subvencion)') &\n (becariospdb.motivo != 'Becarios que fallecieron') &\n (becariospdb.motivo != 'Becarios que no se presentaron con RJ (Si recibieron subvencion)') &\n (becariospdb.motivo != 'Becarios observados y/o en regularizacion')]\n", "_____no_output_____" ], [ "print(becariospdbv1)", " convocatoria region \\\n0 Beca 18 Modalidad Ordinaria 2012 LIMA \n1 Beca 18 Modalidad Ordinaria 2012 LIMA \n2 Beca 18 Modalidad Ordinaria 2012 LIMA \n3 Beca 18 Modalidad Ordinaria 2012 LIMA \n4 Beca 18 Modalidad Ordinaria 2012 LIMA \n5 Beca 18 Modalidad Ordinaria 2012 LIMA \n6 Beca 18 Modalidad Ordinaria 2012 LIMA \n7 Beca 18 Modalidad Ordinaria 2012 LIMA \n8 Beca 18 Modalidad Ordinaria 2012 LIMA \n9 Beca 18 Modalidad Ordinaria 2012 LIMA \n10 Beca 18 Modalidad Ordinaria 2012 LIMA \n11 Beca 18 Modalidad Ordinaria 2012 LIMA \n12 Beca 18 Modalidad Ordinaria 2012 LIMA \n13 Beca 18 Modalidad Ordinaria 2012 LIMA \n14 Beca 18 Modalidad Ordinaria 2012 LIMA \n17 Beca 18 Modalidad Ordinaria 2013 LIMA \n18 Beca 18 Modalidad Ordinaria 2013 LIMA \n19 Beca 18 Ordinaria 2015 LIMA \n20 Beca 18 Reparaciones 2012-01 LIMA \n22 Beca 18 Modalidad Ordinaria 2012 LIMA \n23 Beca 18 Modalidad Ordinaria 2012 LIMA \n24 Beca 18 Modalidad Ordinaria 2014 LIMA \n25 Beca 18 VRAEM 2012-01 LIMA \n26 Beca 18 Ordinaria 2015 LIMA \n27 Beca 18 VRAEM 2012-01 LIMA \n28 Beca 18 VRAEM 2012-01 LIMA \n30 Beca 18 VRAEM 2012-01 LIMA \n31 Beca 18 VRAEM 2012-01 LIMA \n32 Beca 18 VRAEM 2012-01 LIMA \n33 Beca 18 Modalidad Ordinaria 2013 LIMA \n... ... ... \n15083 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15084 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15085 Beca 18 Ordinaria 2015 LIMA \n15090 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15091 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15092 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15093 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15095 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15096 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15097 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15098 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15099 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15104 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15105 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15106 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15107 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15113 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15114 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15115 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15132 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15133 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15180 Beca para Poblaciones Vulnerables y en Situaci... CAJAMARCA \n15182 Beca 18 Ordinaria 2015 LAMBAYEQUE \n15183 Beca 18 Ordinaria 2015 LAMBAYEQUE \n15184 Beca 18 Ordinaria 2015 LAMBAYEQUE \n15185 Beca para Poblaciones Vulnerables y en Situaci... CAJAMARCA \n15186 Beca para Poblaciones Vulnerables y en Situaci... CAJAMARCA \n15187 Beca 18 Ordinaria 2015 LAMBAYEQUE \n15188 Beca 18 Ordinaria 2015 LAMBAYEQUE \n15189 Beca 18 Ordinaria 2015 LAMBAYEQUE \n\n motivo \\\n0 Becarios que desaprobaron \n1 Becarios que desaprobaron \n2 Becarios que desaprobaron \n3 Becarios que desaprobaron \n4 Becarios que desaprobaron \n5 Becarios que desaprobaron \n6 Becarios que desaprobaron \n7 Becarios que desaprobaron \n8 Becarios que desaprobaron \n9 Becarios que desaprobaron \n10 Becarios que desaprobaron \n11 Becarios que desaprobaron \n12 Becarios que desaprobaron \n13 Becarios que abandonaron los estudios (No reci... \n14 Becarios que desaprobaron \n17 Becarios que desaprobaron \n18 Becarios que desaprobaron \n19 Becarios que desaprobaron \n20 Becarios que desaprobaron \n22 Becarios que desaprobaron \n23 Becarios que desaprobaron \n24 Becarios que desaprobaron \n25 Becarios que desaprobaron \n26 Becarios que desaprobaron \n27 Becarios que desaprobaron \n28 Becarios que desaprobaron \n30 Becarios que abandonaron los estudios (No reci... \n31 Becarios que abandonaron los estudios (No reci... \n32 Becarios que abandonaron los estudios (No reci... \n33 Becarios que desaprobaron \n... ... \n15083 Becarios que abandonaron los estudios (No reci... \n15084 Becarios que desaprobaron \n15085 Becarios que abandonaron los estudios (No reci... \n15090 Becarios que desaprobaron \n15091 Becarios que abandonaron los estudios (No reci... \n15092 Becarios que abandonaron los estudios (No reci... \n15093 Becarios que abandonaron los estudios (No reci... \n15095 Becarios que abandonaron los estudios (No reci... \n15096 Becarios que abandonaron los estudios (No reci... \n15097 Becarios que abandonaron los estudios (No reci... \n15098 Becarios que abandonaron los estudios (No reci... \n15099 Becarios que abandonaron los estudios (No reci... \n15104 Becarios que abandonaron los estudios (No reci... \n15105 Becarios que abandonaron los estudios (No reci... \n15106 Becarios que abandonaron los estudios (No reci... \n15107 Becarios que abandonaron los estudios (No reci... \n15113 Becarios que abandonaron los estudios (No reci... \n15114 Becarios que abandonaron los estudios (No reci... \n15115 Becarios que abandonaron los estudios (No reci... \n15132 Becarios que abandonaron los estudios (No reci... \n15133 Becarios que abandonaron los estudios (No reci... \n15180 Becarios que desaprobaron \n15182 Becarios que abandonaron los estudios (No reci... \n15183 Becarios que desaprobaron \n15184 Becarios que desaprobaron \n15185 Becarios que desaprobaron \n15186 Becarios que desaprobaron \n15187 Becarios que abandonaron los estudios (No reci... \n15188 Becarios que abandonaron los estudios (No reci... \n15189 Becarios que abandonaron los estudios (No reci... \n\n resolucion_ret_beca fec_resolucion_ret_beca fec_Postulacion \\\n0 RESOLUCION JEFATURAL 2014-11 2012-04 \n1 RESOLUCION JEFATURAL 2013-11 2012-04 \n2 RESOLUCION JEFATURAL 2013-11 2012-04 \n3 RESOLUCION JEFATURAL 2013-11 2012-04 \n4 RESOLUCION JEFATURAL 2013-12 2012-04 \n5 RESOLUCION JEFATURAL NaN 2012-03 \n6 RESOLUCION JEFATURAL 2013-12 2012-03 \n7 RESOLUCION JEFATURAL 2013-12 2012-03 \n8 RESOLUCION JEFATURAL 2013-12 2012-03 \n9 RESOLUCION JEFATURAL 2014-01 2012-03 \n10 RESOLUCION JEFATURAL 2013-11 2012-04 \n11 RESOLUCION JEFATURAL 2013-12 2012-04 \n12 RESOLUCION JEFATURAL 2013-12 2012-04 \n13 RESOLUCION JEFATURAL 2014-02 2012-04 \n14 RESOLUCION JEFATURAL 2013-11 2012-04 \n17 RESOLUCION JEFATURAL 2015-03 2013-01 \n18 RESOLUCION JEFATURAL 2014-11 2013-03 \n19 RESOLUCION JEFATURAL NaN 2015-03 \n20 RESOLUCION JEFATURAL NaN 2012-10 \n22 RESOLUCION JEFATURAL 2013-11 2012-04 \n23 RESOLUCION JEFATURAL 2014-02 2012-04 \n24 RESOLUCION JEFATURAL 2014-12 2014-03 \n25 RESOLUCION JEFATURAL NaN 2012-08 \n26 RESOLUCION JEFATURAL NaN 2015-03 \n27 RESOLUCION JEFATURAL 2014-04 2012-08 \n28 RESOLUCION JEFATURAL NaN 2012-08 \n30 RESOLUCION JEFATURAL 2014-08 2012-08 \n31 RESOLUCION JEFATURAL 2014-10 2012-09 \n32 RESOLUCION JEFATURAL 2014-02 2012-09 \n33 RESOLUCION JEFATURAL 2015-03 2013-03 \n... ... ... ... \n15083 RESOLUCION JEFATURAL 2015-08 2014-10 \n15084 RESOLUCION JEFATURAL NaN 2014-11 \n15085 RESOLUCION JEFATURAL NaN 2015-01 \n15090 RESOLUCION JEFATURAL NaN 2014-10 \n15091 RESOLUCION JEFATURAL 2015-08 2014-10 \n15092 RESOLUCION JEFATURAL 2015-08 2014-10 \n15093 RESOLUCION JEFATURAL 2015-08 2014-10 \n15095 RESOLUCION JEFATURAL 2015-08 2014-12 \n15096 RESOLUCION JEFATURAL 2015-08 2014-12 \n15097 RESOLUCION JEFATURAL 2015-08 2014-12 \n15098 RESOLUCION JEFATURAL 2015-08 2014-12 \n15099 RESOLUCION JEFATURAL 2015-08 2014-10 \n15104 RESOLUCION JEFATURAL 2015-08 2014-10 \n15105 RESOLUCION JEFATURAL 2015-08 2014-12 \n15106 RESOLUCION JEFATURAL 2015-08 2014-12 \n15107 RESOLUCION JEFATURAL 2015-08 2014-12 \n15113 RESOLUCION JEFATURAL 2015-08 2014-11 \n15114 RESOLUCION JEFATURAL 2015-08 2014-12 \n15115 RESOLUCION JEFATURAL 2015-08 2014-11 \n15132 RESOLUCION JEFATURAL 2015-08 2014-10 \n15133 RESOLUCION JEFATURAL 2015-08 2014-10 \n15180 RESOLUCION JEFATURAL NaN 2014-12 \n15182 RESOLUCION JEFATURAL NaN 2015-01 \n15183 RESOLUCION JEFATURAL NaN 2015-01 \n15184 RESOLUCION JEFATURAL NaN 2015-01 \n15185 RESOLUCION JEFATURAL NaN 2014-11 \n15186 RESOLUCION JEFATURAL NaN 2014-12 \n15187 RESOLUCION JEFATURAL NaN 2015-01 \n15188 RESOLUCION JEFATURAL NaN 2015-01 \n15189 RESOLUCION JEFATURAL NaN 2015-01 \n\n tipoinstitucion \\\n0 Universidad \n1 Universidad \n2 Universidad \n3 Universidad \n4 Universidad \n5 Universidad \n6 Universidad \n7 Universidad \n8 Universidad \n9 Universidad \n10 Universidad \n11 Universidad \n12 Universidad \n13 Universidad \n14 Universidad \n17 Universidad \n18 Universidad \n19 Universidad \n20 Universidad \n22 Universidad \n23 Universidad \n24 Universidad \n25 Instituto de Educación Superior Tecnológico \n26 Universidad \n27 Instituto de Educación Superior Tecnológico \n28 Instituto de Educación Superior Tecnológico \n30 Instituto de Educación Superior Tecnológico \n31 Instituto de Educación Superior Tecnológico \n32 Instituto de Educación Superior Tecnológico \n33 Instituto de Educación Superior Tecnológico \n... ... \n15083 Centro de Educación Técnico-Productiva \n15084 Centro de Educación Técnico-Productiva \n15085 Universidad \n15090 Centro de Educación Técnico-Productiva \n15091 Centro de Educación Técnico-Productiva \n15092 Centro de Educación Técnico-Productiva \n15093 Centro de Educación Técnico-Productiva \n15095 Centro de Educación Técnico-Productiva \n15096 Centro de Educación Técnico-Productiva \n15097 Centro de Educación Técnico-Productiva \n15098 Centro de Educación Técnico-Productiva \n15099 Centro de Educación Técnico-Productiva \n15104 Centro de Educación Técnico-Productiva \n15105 Centro de Educación Técnico-Productiva \n15106 Centro de Educación Técnico-Productiva \n15107 Centro de Educación Técnico-Productiva \n15113 Centro de Educación Técnico-Productiva \n15114 Centro de Educación Técnico-Productiva \n15115 Centro de Educación Técnico-Productiva \n15132 Centro de Educación Técnico-Productiva \n15133 Centro de Educación Técnico-Productiva \n15180 Instituto de Educación Superior Tecnológico \n15182 Instituto de Educación Superior Tecnológico \n15183 Instituto de Educación Superior Tecnológico \n15184 Instituto de Educación Superior Tecnológico \n15185 Instituto de Educación Superior Tecnológico \n15186 Instituto de Educación Superior Tecnológico \n15187 Instituto de Educación Superior Tecnológico \n15188 Instituto de Educación Superior Tecnológico \n15189 Instituto de Educación Superior Tecnológico \n\n institucioneducativa institucionsede \\\n0 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n1 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n2 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n3 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n4 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n5 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n6 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n7 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n8 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n9 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n10 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n11 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n12 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n13 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n14 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n17 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n18 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n19 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n20 NACIONAL FEDERICO VILLARREAL SEDE LIMA \n22 NACIONAL FEDERICO VILLARREAL SEDE LIMA \n23 NACIONAL FEDERICO VILLARREAL SEDE LIMA \n24 NACIONAL FEDERICO VILLARREAL SEDE LIMA \n25 IBEROTEC SEDE LINCE \n26 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n27 IBEROTEC SEDE LINCE \n28 IBEROTEC SEDE LINCE \n30 IBEROTEC SEDE LINCE \n31 IBEROTEC SEDE LINCE \n32 IBEROTEC SEDE LINCE \n33 IBEROTEC SEDE LINCE \n... ... ... \n15083 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15084 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15085 FEMENINA DEL SAGRADO CORAZON SEDE LA MOLINA \n15090 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15091 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15092 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15093 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15095 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15096 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15097 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15098 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15099 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15104 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15105 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15106 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15107 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15113 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15114 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15115 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15132 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15133 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15180 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CAJAMARCA \n15182 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CHICLAYO \n15183 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CHICLAYO \n15184 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CHICLAYO \n15185 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CAJAMARCA \n15186 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CAJAMARCA \n15187 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CHICLAYO \n15188 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CHICLAYO \n15189 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CHICLAYO \n\n carreradescripcion genero \n0 INGENIERIA GEOLOGICA MASCULINO \n1 INGENIERIA GEOGRAFICA MASCULINO \n2 QUIMICA MASCULINO \n3 INGENIERIA DE SISTEMAS MASCULINO \n4 INGENIERIA CIVIL MASCULINO \n5 INGENIERIA MECANICA DE FLUIDOS MASCULINO \n6 INGENIERIA CIVIL MASCULINO \n7 INGENIERIA ELECTRONICA MASCULINO \n8 INGENIERIA CIVIL MASCULINO \n9 INGENIERIA ELECTRONICA MASCULINO \n10 ESTADISTICA MASCULINO \n11 INGENIERIA ELECTRICA MASCULINO \n12 INGENIERIA CIVIL MASCULINO \n13 COMPUTACION CIENTIFICA MASCULINO \n14 INGENIERIA DE SOFTWARE MASCULINO \n17 INGENIERIA INDUSTRIAL MASCULINO \n18 INGENIERIA INDUSTRIAL MASCULINO \n19 INGENIERIA ELECTRONICA MASCULINO \n20 INGENIERIA CIVIL MASCULINO \n22 INGENIERIA CIVIL MASCULINO \n23 INGENIERIA AGROINDUSTRIAL MASCULINO \n24 INGENIERIA CIVIL MASCULINO \n25 TELEMATICA MASCULINO \n26 COMPUTACION CIENTIFICA MASCULINO \n27 SISTEMAS DE TELECOMUNICACIONES MASCULINO \n28 SISTEMAS DE TELECOMUNICACIONES MASCULINO \n30 SISTEMAS DE TELECOMUNICACIONES MASCULINO \n31 TELEMATICA MASCULINO \n32 SISTEMAS DE TELECOMUNICACIONES MASCULINO \n33 SISTEMAS DE TELECOMUNICACIONES MASCULINO \n... ... ... \n15083 COCINA PERUANA FEMENINO \n15084 COCINA PERUANA FEMENINO \n15085 NUTRICION Y DIETETICA FEMENINO \n15090 COCINA PERUANA FEMENINO \n15091 COCINA PERUANA FEMENINO \n15092 PANADERIA - PASTELERIA BASICA FEMENINO \n15093 COCINA PERUANA FEMENINO \n15095 PANADERIA - PASTELERIA BASICA FEMENINO \n15096 COCINA PERUANA FEMENINO \n15097 COCINA PERUANA FEMENINO \n15098 COCINA PERUANA FEMENINO \n15099 COCINA PERUANA FEMENINO \n15104 COCINA PERUANA FEMENINO \n15105 PANADERIA - PASTELERIA BASICA FEMENINO \n15106 PANADERIA - PASTELERIA BASICA FEMENINO \n15107 COCINA PERUANA FEMENINO \n15113 COCINA PERUANA FEMENINO \n15114 COCINA INTERNACIONAL FEMENINO \n15115 PANADERIA - PASTELERIA BASICA FEMENINO \n15132 COCINA PERUANA FEMENINO \n15133 COCINA PERUANA FEMENINO \n15180 ASISTENTE DE COCINA FEMENINO \n15182 GUIAS OFICIALES DE TURISMO FEMENINO \n15183 ADMINISTRACION TURISTICA FEMENINO \n15184 ADMINISTRACION TURISTICA FEMENINO \n15185 PANADERIA FEMENINO \n15186 PANADERIA FEMENINO \n15187 GUIAS OFICIALES DE TURISMO FEMENINO \n15188 ADMINISTRACION TURISTICA FEMENINO \n15189 GUIAS OFICIALES DE TURISMO FEMENINO \n\n[11003 rows x 11 columns]\n" ], [ "becariosp = becariospdbv1.drop_duplicates() #Eliminamos las instancias duplicadas", "_____no_output_____" ], [ "print(becariosp)", " convocatoria region \\\n0 Beca 18 Modalidad Ordinaria 2012 LIMA \n1 Beca 18 Modalidad Ordinaria 2012 LIMA \n2 Beca 18 Modalidad Ordinaria 2012 LIMA \n3 Beca 18 Modalidad Ordinaria 2012 LIMA \n4 Beca 18 Modalidad Ordinaria 2012 LIMA \n5 Beca 18 Modalidad Ordinaria 2012 LIMA \n6 Beca 18 Modalidad Ordinaria 2012 LIMA \n7 Beca 18 Modalidad Ordinaria 2012 LIMA \n9 Beca 18 Modalidad Ordinaria 2012 LIMA \n10 Beca 18 Modalidad Ordinaria 2012 LIMA \n11 Beca 18 Modalidad Ordinaria 2012 LIMA \n13 Beca 18 Modalidad Ordinaria 2012 LIMA \n14 Beca 18 Modalidad Ordinaria 2012 LIMA \n17 Beca 18 Modalidad Ordinaria 2013 LIMA \n18 Beca 18 Modalidad Ordinaria 2013 LIMA \n19 Beca 18 Ordinaria 2015 LIMA \n20 Beca 18 Reparaciones 2012-01 LIMA \n22 Beca 18 Modalidad Ordinaria 2012 LIMA \n23 Beca 18 Modalidad Ordinaria 2012 LIMA \n24 Beca 18 Modalidad Ordinaria 2014 LIMA \n25 Beca 18 VRAEM 2012-01 LIMA \n26 Beca 18 Ordinaria 2015 LIMA \n27 Beca 18 VRAEM 2012-01 LIMA \n28 Beca 18 VRAEM 2012-01 LIMA \n30 Beca 18 VRAEM 2012-01 LIMA \n31 Beca 18 VRAEM 2012-01 LIMA \n32 Beca 18 VRAEM 2012-01 LIMA \n33 Beca 18 Modalidad Ordinaria 2013 LIMA \n34 Beca 18 Modalidad Ordinaria 2013 LIMA \n35 Beca 18 Modalidad Ordinaria 2013 LIMA \n... ... ... \n14982 Beca para Poblaciones Vulnerables y en Situaci... JUNIN \n14985 Beca para Poblaciones Vulnerables y en Situaci... CAJAMARCA \n14987 Beca para Poblaciones Vulnerables y en Situaci... AREQUIPA \n14995 Beca para Poblaciones Vulnerables y en Situaci... AREQUIPA \n15000 Beca para Poblaciones Vulnerables y en Situaci... PIURA \n15001 Beca para Poblaciones Vulnerables y en Situaci... AREQUIPA \n15003 Beca para Poblaciones Vulnerables y en Situaci... JUNIN \n15011 Beca para Poblaciones Vulnerables y en Situaci... JUNIN \n15023 Beca para Poblaciones Vulnerables y en Situaci... JUNIN \n15024 Beca para Poblaciones Vulnerables y en Situaci... JUNIN \n15043 Beca para Poblaciones Vulnerables y en Situaci... CALLAO \n15047 Beca para Poblaciones Vulnerables y en Situaci... CALLAO \n15048 Beca para Poblaciones Vulnerables y en Situaci... CALLAO \n15068 Beca para Poblaciones Vulnerables y en Situaci... CALLAO \n15069 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15078 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15079 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15082 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15084 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15085 Beca 18 Ordinaria 2015 LIMA \n15095 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15096 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15113 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15114 Beca para Poblaciones Vulnerables y en Situaci... LIMA \n15180 Beca para Poblaciones Vulnerables y en Situaci... CAJAMARCA \n15182 Beca 18 Ordinaria 2015 LAMBAYEQUE \n15183 Beca 18 Ordinaria 2015 LAMBAYEQUE \n15185 Beca para Poblaciones Vulnerables y en Situaci... CAJAMARCA \n15186 Beca para Poblaciones Vulnerables y en Situaci... CAJAMARCA \n15188 Beca 18 Ordinaria 2015 LAMBAYEQUE \n\n motivo \\\n0 Becarios que desaprobaron \n1 Becarios que desaprobaron \n2 Becarios que desaprobaron \n3 Becarios que desaprobaron \n4 Becarios que desaprobaron \n5 Becarios que desaprobaron \n6 Becarios que desaprobaron \n7 Becarios que desaprobaron \n9 Becarios que desaprobaron \n10 Becarios que desaprobaron \n11 Becarios que desaprobaron \n13 Becarios que abandonaron los estudios (No reci... \n14 Becarios que desaprobaron \n17 Becarios que desaprobaron \n18 Becarios que desaprobaron \n19 Becarios que desaprobaron \n20 Becarios que desaprobaron \n22 Becarios que desaprobaron \n23 Becarios que desaprobaron \n24 Becarios que desaprobaron \n25 Becarios que desaprobaron \n26 Becarios que desaprobaron \n27 Becarios que desaprobaron \n28 Becarios que desaprobaron \n30 Becarios que abandonaron los estudios (No reci... \n31 Becarios que abandonaron los estudios (No reci... \n32 Becarios que abandonaron los estudios (No reci... \n33 Becarios que desaprobaron \n34 Becarios que desaprobaron \n35 Becarios que desaprobaron \n... ... \n14982 Becarios que desaprobaron \n14985 Becarios que desaprobaron \n14987 Becarios que desaprobaron \n14995 Becarios que desaprobaron \n15000 Becarios que desaprobaron \n15001 Becarios que desaprobaron \n15003 Becarios que desaprobaron \n15011 Becarios que desaprobaron \n15023 Becarios que abandonaron los estudios (No reci... \n15024 Becarios que desaprobaron \n15043 Becarios que desaprobaron \n15047 Becarios que desaprobaron \n15048 Becarios que desaprobaron \n15068 Becarios que abandonaron los estudios (No reci... \n15069 Becarios que abandonaron los estudios (No reci... \n15078 Becarios que abandonaron los estudios (No reci... \n15079 Becarios que abandonaron los estudios (No reci... \n15082 Becarios que desaprobaron \n15084 Becarios que desaprobaron \n15085 Becarios que abandonaron los estudios (No reci... \n15095 Becarios que abandonaron los estudios (No reci... \n15096 Becarios que abandonaron los estudios (No reci... \n15113 Becarios que abandonaron los estudios (No reci... \n15114 Becarios que abandonaron los estudios (No reci... \n15180 Becarios que desaprobaron \n15182 Becarios que abandonaron los estudios (No reci... \n15183 Becarios que desaprobaron \n15185 Becarios que desaprobaron \n15186 Becarios que desaprobaron \n15188 Becarios que abandonaron los estudios (No reci... \n\n resolucion_ret_beca fec_resolucion_ret_beca fec_Postulacion \\\n0 RESOLUCION JEFATURAL 2014-11 2012-04 \n1 RESOLUCION JEFATURAL 2013-11 2012-04 \n2 RESOLUCION JEFATURAL 2013-11 2012-04 \n3 RESOLUCION JEFATURAL 2013-11 2012-04 \n4 RESOLUCION JEFATURAL 2013-12 2012-04 \n5 RESOLUCION JEFATURAL NaN 2012-03 \n6 RESOLUCION JEFATURAL 2013-12 2012-03 \n7 RESOLUCION JEFATURAL 2013-12 2012-03 \n9 RESOLUCION JEFATURAL 2014-01 2012-03 \n10 RESOLUCION JEFATURAL 2013-11 2012-04 \n11 RESOLUCION JEFATURAL 2013-12 2012-04 \n13 RESOLUCION JEFATURAL 2014-02 2012-04 \n14 RESOLUCION JEFATURAL 2013-11 2012-04 \n17 RESOLUCION JEFATURAL 2015-03 2013-01 \n18 RESOLUCION JEFATURAL 2014-11 2013-03 \n19 RESOLUCION JEFATURAL NaN 2015-03 \n20 RESOLUCION JEFATURAL NaN 2012-10 \n22 RESOLUCION JEFATURAL 2013-11 2012-04 \n23 RESOLUCION JEFATURAL 2014-02 2012-04 \n24 RESOLUCION JEFATURAL 2014-12 2014-03 \n25 RESOLUCION JEFATURAL NaN 2012-08 \n26 RESOLUCION JEFATURAL NaN 2015-03 \n27 RESOLUCION JEFATURAL 2014-04 2012-08 \n28 RESOLUCION JEFATURAL NaN 2012-08 \n30 RESOLUCION JEFATURAL 2014-08 2012-08 \n31 RESOLUCION JEFATURAL 2014-10 2012-09 \n32 RESOLUCION JEFATURAL 2014-02 2012-09 \n33 RESOLUCION JEFATURAL 2015-03 2013-03 \n34 RESOLUCION JEFATURAL NaN 2013-03 \n35 RESOLUCION JEFATURAL 2014-05 2013-02 \n... ... ... ... \n14982 RESOLUCION JEFATURAL NaN 2014-10 \n14985 RESOLUCION JEFATURAL NaN 2014-10 \n14987 RESOLUCION JEFATURAL NaN 2014-10 \n14995 RESOLUCION JEFATURAL NaN 2014-10 \n15000 RESOLUCION JEFATURAL NaN 2014-11 \n15001 RESOLUCION JEFATURAL NaN 2014-12 \n15003 RESOLUCION JEFATURAL NaN 2014-11 \n15011 RESOLUCION JEFATURAL NaN 2014-10 \n15023 RESOLUCION JEFATURAL 2015-08 2014-10 \n15024 RESOLUCION JEFATURAL NaN 2014-11 \n15043 RESOLUCION JEFATURAL NaN 2014-11 \n15047 RESOLUCION JEFATURAL NaN 2014-11 \n15048 RESOLUCION JEFATURAL NaN 2014-11 \n15068 RESOLUCION JEFATURAL 2015-08 2014-11 \n15069 RESOLUCION JEFATURAL 2015-08 2014-11 \n15078 RESOLUCION JEFATURAL 2015-08 2014-10 \n15079 RESOLUCION JEFATURAL 2015-08 2014-10 \n15082 RESOLUCION JEFATURAL NaN 2014-10 \n15084 RESOLUCION JEFATURAL NaN 2014-11 \n15085 RESOLUCION JEFATURAL NaN 2015-01 \n15095 RESOLUCION JEFATURAL 2015-08 2014-12 \n15096 RESOLUCION JEFATURAL 2015-08 2014-12 \n15113 RESOLUCION JEFATURAL 2015-08 2014-11 \n15114 RESOLUCION JEFATURAL 2015-08 2014-12 \n15180 RESOLUCION JEFATURAL NaN 2014-12 \n15182 RESOLUCION JEFATURAL NaN 2015-01 \n15183 RESOLUCION JEFATURAL NaN 2015-01 \n15185 RESOLUCION JEFATURAL NaN 2014-11 \n15186 RESOLUCION JEFATURAL NaN 2014-12 \n15188 RESOLUCION JEFATURAL NaN 2015-01 \n\n tipoinstitucion \\\n0 Universidad \n1 Universidad \n2 Universidad \n3 Universidad \n4 Universidad \n5 Universidad \n6 Universidad \n7 Universidad \n9 Universidad \n10 Universidad \n11 Universidad \n13 Universidad \n14 Universidad \n17 Universidad \n18 Universidad \n19 Universidad \n20 Universidad \n22 Universidad \n23 Universidad \n24 Universidad \n25 Instituto de Educación Superior Tecnológico \n26 Universidad \n27 Instituto de Educación Superior Tecnológico \n28 Instituto de Educación Superior Tecnológico \n30 Instituto de Educación Superior Tecnológico \n31 Instituto de Educación Superior Tecnológico \n32 Instituto de Educación Superior Tecnológico \n33 Instituto de Educación Superior Tecnológico \n34 Instituto de Educación Superior Tecnológico \n35 Instituto de Educación Superior Tecnológico \n... ... \n14982 Centro de Educación Técnico-Productiva \n14985 Centro de Educación Técnico-Productiva \n14987 Centro de Educación Técnico-Productiva \n14995 Instituto de Educación Superior Tecnológico \n15000 Instituto de Educación Superior Tecnológico \n15001 Instituto de Educación Superior Tecnológico \n15003 Instituto de Educación Superior Tecnológico \n15011 Instituto de Educación Superior Tecnológico \n15023 Instituto de Educación Superior Tecnológico \n15024 Instituto de Educación Superior Tecnológico \n15043 Centro de Educación Técnico-Productiva \n15047 Centro de Educación Técnico-Productiva \n15048 Centro de Educación Técnico-Productiva \n15068 Centro de Educación Técnico-Productiva \n15069 Centro de Educación Técnico-Productiva \n15078 Centro de Educación Técnico-Productiva \n15079 Centro de Educación Técnico-Productiva \n15082 Centro de Educación Técnico-Productiva \n15084 Centro de Educación Técnico-Productiva \n15085 Universidad \n15095 Centro de Educación Técnico-Productiva \n15096 Centro de Educación Técnico-Productiva \n15113 Centro de Educación Técnico-Productiva \n15114 Centro de Educación Técnico-Productiva \n15180 Instituto de Educación Superior Tecnológico \n15182 Instituto de Educación Superior Tecnológico \n15183 Instituto de Educación Superior Tecnológico \n15185 Instituto de Educación Superior Tecnológico \n15186 Instituto de Educación Superior Tecnológico \n15188 Instituto de Educación Superior Tecnológico \n\n institucioneducativa institucionsede \\\n0 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n1 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n2 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n3 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n4 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n5 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n6 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n7 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n9 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n10 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n11 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n13 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n14 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n17 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n18 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n19 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n20 NACIONAL FEDERICO VILLARREAL SEDE LIMA \n22 NACIONAL FEDERICO VILLARREAL SEDE LIMA \n23 NACIONAL FEDERICO VILLARREAL SEDE LIMA \n24 NACIONAL FEDERICO VILLARREAL SEDE LIMA \n25 IBEROTEC SEDE LINCE \n26 NACIONAL MAYOR DE SAN MARCOS SEDE LIMA \n27 IBEROTEC SEDE LINCE \n28 IBEROTEC SEDE LINCE \n30 IBEROTEC SEDE LINCE \n31 IBEROTEC SEDE LINCE \n32 IBEROTEC SEDE LINCE \n33 IBEROTEC SEDE LINCE \n34 IBEROTEC SEDE LINCE \n35 IBEROTEC SEDE LINCE \n... ... ... \n14982 CETEMIN SEDE SATIPO \n14985 CETEMIN SEDE CAJAMARCA \n14987 CETEMIN SEDE AREQUIPA \n14995 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE AREQUIPA \n15000 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE PIURA \n15001 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE AREQUIPA \n15003 DE COMERCIO EXTERIOR SEDE MAZAMARI \n15011 DE COMERCIO EXTERIOR SEDE MAZAMARI \n15023 DE COMERCIO EXTERIOR SEDE MAZAMARI \n15024 DE COMERCIO EXTERIOR SEDE MAZAMARI \n15043 ALCIDES SALOMON ZORRILLA SEDE CALLAO \n15047 ALCIDES SALOMON ZORRILLA SEDE CALLAO \n15048 ALCIDES SALOMON ZORRILLA SEDE CALLAO \n15068 ALCIDES SALOMON ZORRILLA SEDE CALLAO \n15069 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15078 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15079 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15082 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15084 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15085 FEMENINA DEL SAGRADO CORAZON SEDE LA MOLINA \n15095 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15096 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15113 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15114 PADRE JOSE LUIS IDIGORAS GOYA SEDE LIMA \n15180 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CAJAMARCA \n15182 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CHICLAYO \n15183 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CHICLAYO \n15185 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CAJAMARCA \n15186 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CAJAMARCA \n15188 CENFOTUR-CENTRO DE FORMACION EN TURISMO SEDE CHICLAYO \n\n carreradescripcion genero \n0 INGENIERIA GEOLOGICA MASCULINO \n1 INGENIERIA GEOGRAFICA MASCULINO \n2 QUIMICA MASCULINO \n3 INGENIERIA DE SISTEMAS MASCULINO \n4 INGENIERIA CIVIL MASCULINO \n5 INGENIERIA MECANICA DE FLUIDOS MASCULINO \n6 INGENIERIA CIVIL MASCULINO \n7 INGENIERIA ELECTRONICA MASCULINO \n9 INGENIERIA ELECTRONICA MASCULINO \n10 ESTADISTICA MASCULINO \n11 INGENIERIA ELECTRICA MASCULINO \n13 COMPUTACION CIENTIFICA MASCULINO \n14 INGENIERIA DE SOFTWARE MASCULINO \n17 INGENIERIA INDUSTRIAL MASCULINO \n18 INGENIERIA INDUSTRIAL MASCULINO \n19 INGENIERIA ELECTRONICA MASCULINO \n20 INGENIERIA CIVIL MASCULINO \n22 INGENIERIA CIVIL MASCULINO \n23 INGENIERIA AGROINDUSTRIAL MASCULINO \n24 INGENIERIA CIVIL MASCULINO \n25 TELEMATICA MASCULINO \n26 COMPUTACION CIENTIFICA MASCULINO \n27 SISTEMAS DE TELECOMUNICACIONES MASCULINO \n28 SISTEMAS DE TELECOMUNICACIONES MASCULINO \n30 SISTEMAS DE TELECOMUNICACIONES MASCULINO \n31 TELEMATICA MASCULINO \n32 SISTEMAS DE TELECOMUNICACIONES MASCULINO \n33 SISTEMAS DE TELECOMUNICACIONES MASCULINO \n34 SISTEMAS DE TELECOMUNICACIONES MASCULINO \n35 SISTEMAS DE TELECOMUNICACIONES MASCULINO \n... ... ... \n14982 RETROEXCAVADORA + VOLQUETE FEMENINO \n14985 CARGADOR FRONTAL + VOLQUETE FEMENINO \n14987 EXCAVADORA + VOLQUETE FEMENINO \n14995 ORFEBRERIA -JOYERO BASICO FEMENINO \n15000 ORFEBRERIA -JOYERO BASICO FEMENINO \n15001 ORFEBRERIA -JOYERO BASICO FEMENINO \n15003 AUXILIAR EN ADMINISTRACION DE COOPERATIVAS FEMENINO \n15011 GESTION DE COOPERATIVAS FEMENINO \n15023 GESTION DE COOPERATIVAS FEMENINO \n15024 GESTION DE COOPERATIVAS FEMENINO \n15043 ELABORACION DE PRODUCTOS DE PASTELERIA, PANADE... FEMENINO \n15047 ATENCION DE CABINAS DE INTERNET FEMENINO \n15048 TECNICAS DE HIDROPONIA FEMENINO \n15068 LABORES DE JARDINERIA FEMENINO \n15069 PANADERIA - PASTELERIA BASICA FEMENINO \n15078 COCINA PERUANA FEMENINO \n15079 PANADERIA - PASTELERIA BASICA FEMENINO \n15082 COCINA PERUANA FEMENINO \n15084 COCINA PERUANA FEMENINO \n15085 NUTRICION Y DIETETICA FEMENINO \n15095 PANADERIA - PASTELERIA BASICA FEMENINO \n15096 COCINA PERUANA FEMENINO \n15113 COCINA PERUANA FEMENINO \n15114 COCINA INTERNACIONAL FEMENINO \n15180 ASISTENTE DE COCINA FEMENINO \n15182 GUIAS OFICIALES DE TURISMO FEMENINO \n15183 ADMINISTRACION TURISTICA FEMENINO \n15185 PANADERIA FEMENINO \n15186 PANADERIA FEMENINO \n15188 ADMINISTRACION TURISTICA FEMENINO \n\n[6441 rows x 11 columns]\n" ], [ "# tabla de frecuencia de motivo de perdida de beca o conteo por motivo de perdida de beca\npd.value_counts(becariosp['motivo'])", "_____no_output_____" ], [ "# Revisar instancias region,tipoinstitucion y genero\npd.value_counts(becariosp['region'])", "_____no_output_____" ], [ "becariosp['region'].replace(\"ESPAÑA\",\"ESPAÑA\",inplace=True)\n\nbecariosp['tipoinstitucion'].replace(\"Instituto de Educación Superior Tecnológico\",\"Instituto de Educación Superior Tecnológico\",inplace=True)\nbecariosp['tipoinstitucion'].replace(\"Centro de Educación Técnico-Productiva\",\"Centro de Educación técnico-Productiva\",inplace=True)\nbecariosp['tipoinstitucion'].replace(\"Instituto de Educación Superior Pedagógico\",\"Instituto de Educación Superior Pedagógico\",inplace=True)\nbecariosp['tipoinstitucion'].replace(\"Instituto de Educación Superior\",\"Instituto de Educación Superior\",inplace=True)\n\n\nbecariosp['motivo'].replace(\"Becarios que desaprobaron\",\"1\",inplace=True)\nbecariosp['motivo'].replace(\"Becarios que abandonaron los estudios (No recibieron subvencion)\",\"0\",inplace=True)\n\n\n\n\n#becariosp.loc({'tipoinstitucion': {\"Instituto de Educación Superior Tecnológico\":\"Instituto de Educación Superior Tecnológico\"}})\n#\"Centro de Educación Técnico-Productiva\": \"Centro de Educación técnico-Productiva\",\n#\"Instituto de Educación Superior\": \"Instituto de Educación Superior\" Instituto de Educación Superior Pedagógico", "/home/eder/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py:3924: 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/indexing.html#indexing-view-versus-copy\n self._update_inplace(new_data)\n" ], [ "# Verificamos\npd.value_counts(becariosp['motivo'])", "_____no_output_____" ], [ "#Observamos algunos cambios viendo graficas\n# tabla de contingencia en porcentajes relativos total motivo/tipoinstitucion\npd.crosstab(index=becariosp['motivo'], columns=becariosp['tipoinstitucion'],margins=True).apply(lambda r: r/len(becariosp) *100,axis=1)", "_____no_output_____" ], [ "# Gráfico de barras de motivo/tipoinstitucion \npd.crosstab(index=becariosp['motivo'], columns=becariosp['tipoinstitucion']).apply(lambda r: r/r.sum() *100,axis=1).plot(kind='barh',legend=True, figsize=(25, 25))", "_____no_output_____" ], [ "becariosp.describe()", "_____no_output_____" ], [ "#Exportamos nuestro data set casi preprocesado\nbecariosp.to_csv('datapronabeclimpio.csv')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a53a66a23698eeda6e6254979d63e1455065d85
106,673
ipynb
Jupyter Notebook
results_ipynb/single_neuron_exploration/cnn_initial_exploration.ipynb
leelabcnbc/tang_jcompneuro_revision
58e9dbcbef7ca3f0c3976b24a4e4aa9c5efcdd3a
[ "Apache-2.0" ]
3
2018-06-19T15:45:02.000Z
2020-12-25T03:10:30.000Z
results_ipynb/single_neuron_exploration/cnn_initial_exploration.ipynb
leelabcnbc/tang_jcompneuro_revision
58e9dbcbef7ca3f0c3976b24a4e4aa9c5efcdd3a
[ "Apache-2.0" ]
null
null
null
results_ipynb/single_neuron_exploration/cnn_initial_exploration.ipynb
leelabcnbc/tang_jcompneuro_revision
58e9dbcbef7ca3f0c3976b24a4e4aa9c5efcdd3a
[ "Apache-2.0" ]
null
null
null
134.011307
34,444
0.843541
[ [ [ "this notebook first collect all stats obtained in intial exploration.\n\nit will be a big table, indexed by subset, neuron, structure, optimization.\n\n# result:\n\nI will use k9cX + k6s2 + vanilla as my basis.", "_____no_output_____" ] ], [ [ "import h5py\nimport numpy as np\nimport os.path\nfrom functools import partial\nfrom collections import OrderedDict\n\nimport pandas as pd\npd.options.display.max_rows = 100\npd.options.display.max_columns = 100\nfrom scipy.stats import pearsonr", "_____no_output_____" ], [ "# get number of parameters.", "_____no_output_____" ], [ "from tang_jcompneuro import dir_dictionary\nfrom tang_jcompneuro.cnn_exploration_pytorch import get_num_params", "_____no_output_____" ], [ "num_param_dict = get_num_params()", "_____no_output_____" ], [ "def print_relevant_models():\n for x, y in num_param_dict.items():\n if x.startswith('k9c') and 'k6s2max' in x and x.endswith('vanilla'):\n print(x, y)\n \nprint_relevant_models()", "k9c3_nobn_k6s2max_vanilla 295\nk9c6_nobn_k6s2max_vanilla 589\nk9c9_nobn_k6s2max_vanilla 883\nk9c12_nobn_k6s2max_vanilla 1177\nk9c15_nobn_k6s2max_vanilla 1471\n" ], [ "def generic_call_back(name, obj, env):\n if isinstance(obj, h5py.Dataset):\n arch, dataset, subset, neuron_idx, opt = name.split('/')\n assert dataset == 'MkA_Shape'\n neuron_idx = int(neuron_idx)\n corr_this = obj.attrs['corr']\n if corr_this.dtype != np.float32:\n # this will get hit by my code.\n assert corr_this == 0.0\n env['result'].append(\n {\n 'subset': subset,\n 'neuron': neuron_idx,\n 'arch': arch,\n 'opt': opt,\n 'corr': corr_this,\n 'time': obj.attrs['time'],\n# 'num_param': num_param_dict[arch],\n }\n )\n \n\ndef collect_all_data():\n cnn_explore_dir = os.path.join(dir_dictionary['models'], 'cnn_exploration')\n env = {'result': []}\n count = 0\n for root, dirs, files in os.walk(cnn_explore_dir):\n for f in files:\n if f.lower().endswith('.hdf5'):\n count += 1\n if count % 100 == 0:\n print(count)\n f_check = os.path.join(root, f)\n with h5py.File(f_check, 'r') as f_metric:\n f_metric.visititems(partial(generic_call_back, env=env))\n \n result = pd.DataFrame(env['result'], columns=['subset', 'neuron', 'arch', 'opt', 'corr', 'time'])\n result = result.set_index(['subset', 'neuron', 'arch', 'opt'], verify_integrity=True)\n print(count)\n return result", "_____no_output_____" ], [ "all_data = collect_all_data()", "100\n200\n300\n400\n500\n600\n700\n800\n900\n1000\n1100\n1200\n1300\n1400\n1500\n1600\n1700\n1800\n1848\n" ], [ "# 66 (arch) x 35 (opt) x 2 (subsets) x 14 (neurons per subset)\nassert all_data.shape == (64680, 2)", "_____no_output_____" ], [ "%matplotlib inline\nimport matplotlib.pyplot as plt\ndef check_run_time():\n# check time. as long as it's fast, it's fine.\n time_all = all_data['time'].values\n plt.close('all')\n plt.hist(time_all, bins=100)\n plt.show()\n print(time_all.min(), time_all.max(),\n np.median(time_all), np.mean(time_all))\n print(np.sort(time_all)[::-1][:50])\ncheck_run_time()", "_____no_output_____" ], [ "# seems that it's good to check those with more than 100 sec.\ndef check_long_ones():\n long_runs = all_data[all_data['time']>=100]\n return long_runs\n\n# typically, long cases are from adam.\n# I'm not sure whether these numbers are accruate. but maybe let's ignore them for now.\ncheck_long_ones()", "_____no_output_____" ], [ "# I think it's easier to analyze per data set.\ndef study_one_subset(df_this_only_corr):\n # this df_this_only_corr should be a series.\n # with (neuron, arch, opt) as the (multi) index.\n \n # first, I want to know how good my opt approximation is.\n # \n # I will show two ways.\n # first, use my opt approximation to replace the best\n # one for every combination of neuron and arch.\n # show scatter plot, pearsonr, as well as how much performance is lost.\n #\n # second, I want to see, if for each neuron I choose the best architecture,\n # how much performance is lost.\n #\n # there are actually two ways to choose best architecture.\n # a) one is, best one is chosen based on the exact version of loss.\n # b) another one is, best one is chosen separately.\n # \n # by the last plot in _examine_opt (second, b)), you can see that,\n # given enough architectures to choose from, these optimization methods can achieve neear optimal.\n \n a = _examine_opt(df_this_only_corr)\n \n # ok. then, I'd like to check archtectures.\n # here, I will use these arch's performance on the approx version.\n \n _examine_arch(a)\n", "_____no_output_____" ], [ "def _examine_arch(df_neuron_by_arch):\n # mark input as tmp_sutff.\n # then you can run things like\n # tmp_stuff.T.mean(axis=1).sort_values()\n # or tmp_stuff.T.median(axis=1).sort_values()\n \n # my finding is that k9cX_nobn_k6s2max_vanilla\n # where X is number of channels often perform best.\n \n # essentially, I can remove those k13 stuff.\n # also, dropout and factored works poorly.\n # so remove them as well.\n # k6s2 stuff may not be that evident.\n # so I will examine that next.\n print(df_neuron_by_arch.T.mean(axis=1).sort_values(ascending=False).iloc[:10])\n print(df_neuron_by_arch.T.median(axis=1).sort_values(ascending=False).iloc[:10])\n \n \n columns = df_neuron_by_arch.columns\n columsn_to_preserve = [x for x in columns if x.startswith('k9c') and x.endswith('vanilla')]\n df_neuron_by_arch = df_neuron_by_arch[columsn_to_preserve]\n \n print(df_neuron_by_arch.T.mean(axis=1).sort_values(ascending=False))\n print(df_neuron_by_arch.T.median(axis=1).sort_values(ascending=False))\n \n # just search 'k6s2max' in the output, and see that most of them are on top.\n ", "_____no_output_____" ], [ "def show_stuff(x1, x2, figsize=(10, 10), title='',\n xlabel=None, ylabel=None):\n plt.close('all')\n plt.figure(figsize=figsize)\n plt.scatter(x1, x2, s=5)\n plt.xlim(0,1)\n plt.ylim(0,1)\n if xlabel is not None:\n plt.xlabel(xlabel)\n if ylabel is not None:\n plt.ylabel(ylabel)\n plt.plot([0,1], [0,1], linestyle='--', color='r')\n plt.title(title + 'corr {:.2f}'.format(pearsonr(x1,x2)[0]))\n plt.axis('equal')\n plt.show()\n \n", "_____no_output_____" ], [ "def _extract_max_value_from_neuron_by_arch_stuff(neuron_by_arch_stuff: np.ndarray, max_idx=None):\n assert isinstance(neuron_by_arch_stuff, np.ndarray)\n n_neuron, n_arch = neuron_by_arch_stuff.shape\n if max_idx is None:\n max_idx = np.argmax(neuron_by_arch_stuff, axis=1)\n assert max_idx.shape == (n_neuron,)\n \n best_perf_per_neuron = neuron_by_arch_stuff[np.arange(n_neuron), max_idx]\n assert best_perf_per_neuron.shape == (n_neuron, )\n # OCD, sanity check.\n for neuron_idx in range(n_neuron):\n assert best_perf_per_neuron[neuron_idx] == neuron_by_arch_stuff[neuron_idx, max_idx[neuron_idx]]\n \n return neuron_by_arch_stuff[np.arange(n_neuron), max_idx], max_idx", "_____no_output_____" ], [ "def _examine_opt(df_this_only_corr):\n # seems that best opt can be approximated by max(1e-3L2_1e-3L2_adam002_mse, 1e-4L2_1e-3L2_adam002_mse,\n # '1e-3L2_1e-3L2_sgd_mse', '1e-4L2_1e-3L2_sgd_mse')\n # let's see how well that goes.\n # this is by running code like\n # opt_var = all_data['corr'].xs('OT', level='subset').unstack('arch').unstack('neuron').median(axis=1).sort_values()\n # where you can replace OT with all,\n # median with mean.\n # and check by eye.\n # notice that mean and median may give pretty different results.\n\n\n opt_approxer = (\n '1e-3L2_1e-3L2_adam002_mse', '1e-4L2_1e-3L2_adam002_mse',\n '1e-3L2_1e-3L2_sgd_mse', '1e-4L2_1e-3L2_sgd_mse'\n )\n \n opt_in_columns = df_this_only_corr.unstack('opt')\n \n opt_best = opt_in_columns.max(axis=1).values\n assert np.all(opt_best > 0)\n opt_best_approx = np.asarray([df_this_only_corr.unstack('opt')[x].values for x in opt_approxer]).max(axis=0)\n assert opt_best.shape == opt_best_approx.shape\n # compute how much is lost.\n preserved_performance = opt_best_approx.mean()/opt_best.mean()\n print('preserved performance', preserved_performance)\n show_stuff(opt_best, opt_best_approx, (8, 8), 'approx vs. exact, all arch, all neurons, ',\n 'exact', 'approx')\n \n \n both_exact_and_opt = pd.DataFrame(OrderedDict([('exact', opt_best), ('approx', opt_best_approx)]),\n index = opt_in_columns.index.copy())\n both_exact_and_opt.columns.name = 'opt_type'\n \n \n \n best_arch_performance_exact, max_idx = _extract_max_value_from_neuron_by_arch_stuff(both_exact_and_opt['exact'].unstack('arch').values)\n best_arch_performance_approx, _ = _extract_max_value_from_neuron_by_arch_stuff(both_exact_and_opt['approx'].unstack('arch').values, max_idx)\n \n best_arch_performance_own_idx, _ = _extract_max_value_from_neuron_by_arch_stuff(both_exact_and_opt['approx'].unstack('arch').values)\n \n assert best_arch_performance_exact.shape == best_arch_performance_approx.shape\n #return best_arch_performance_exact, best_arch_performance_approx\n\n show_stuff(best_arch_performance_exact, best_arch_performance_approx, (6, 6),\n 'approx vs. exact, best arch (determined by exact), all neurons, ',\n 'exact', 'approx')\n \n show_stuff(best_arch_performance_exact, best_arch_performance_own_idx, (6, 6),\n 'approx vs. exact, best arch (determined by each), all neurons, ',\n 'exact', 'approx')\n \n return both_exact_and_opt['approx'].unstack('arch')", "_____no_output_____" ], [ "tmp_stuff = study_one_subset(all_data['corr'].xs('OT', level='subset'))", "preserved performance 0.961820467602\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a53adaa453797cfabbdc910587265559042e5df
20,460
ipynb
Jupyter Notebook
examples/prescient_tutorial.ipynb
bknueven/Prescient
6289c06a5ea06c137cf1321603a15e0c96ddfb85
[ "BSD-3-Clause" ]
1
2021-10-14T20:39:50.000Z
2021-10-14T20:39:50.000Z
examples/prescient_tutorial.ipynb
shrivats-pu/Prescient
3d4238e98ddd767e2b81adc4091bb723dbf563d3
[ "BSD-3-Clause" ]
1
2021-08-04T16:38:39.000Z
2021-08-04T16:38:39.000Z
examples/prescient_tutorial.ipynb
shrivats-pu/Prescient
3d4238e98ddd767e2b81adc4091bb723dbf563d3
[ "BSD-3-Clause" ]
null
null
null
37.749077
441
0.649169
[ [ [ "# Prescient Tutorial", "_____no_output_____" ], [ "## Getting Started\nThis is a tutorial to demonstration the basic functionality of Prescient. Please follow the installation instructions in the [README](https://github.com/grid-parity-exchange/Prescient/blob/master/README.md) before proceeding. This tutorial will assume we are using the CBC MIP solver, however, we will point out where one could use a different solver (CPLEX, Gurobi, Xpress).", "_____no_output_____" ], [ "## RTS-GMLC\nWe will use the RTS-GMLC test system as a demonstration. Prescient comes included with a translator for the RTS-GMLC system data, which is publically available [here](https://github.com/GridMod/RTS-GMLC). To find out more about the RTS-GMLC system, or if you use the RTS-GMLC system in published research, please see or cite the [RTS-GMLC paper](https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8753693&isnumber=4374138&tag=1).", "_____no_output_____" ], [ "## IMPORTANT NOTE\nIn the near future, the dev-team will allow more-direct reading of data in the \"RTS-GMLC\" format directly into the simulator. In the past, we have created one-off scripts for each data set to put then in the format required by the populator.", "_____no_output_____" ], [ "### Downloading the RTS-GMLC data", "_____no_output_____" ] ], [ [ "# first, we'll use the built-in function to download the RTS-GMLC system to Prescicent/downloads/rts_gmlc\nimport prescient.downloaders.rts_gmlc as rts_downloader\n\n# the download function has the path Prescient/downloads/rts_gmlc hard-coded.\n# All it does is a 'git clone' of the RTS-GMLC repo\nrts_downloader.download()", "_____no_output_____" ], [ "# we should be able to see the RTS-GMLC data now\nimport os\nrts_gmlc_dir = rts_downloader.rts_download_path+os.sep+'RTS-GMLC'\nprint(rts_gmlc_dir)\nos.listdir(rts_gmlc_dir)", "_____no_output_____" ] ], [ [ "### Converting RTS-GMLC data into the format for the \"populator\"", "_____no_output_____" ] ], [ [ "# first thing we'll do is to create a *.dat file template for the \"static\" data, e.g.,\n# branches, buses, generators, to Prescicent/downloads/rts_gmlc/templates/rts_with_network_template_hotstart.dat\nfrom prescient.downloaders.rts_gmlc_prescient.rtsgmlc_to_dat import write_template\nwrite_template(rts_gmlc_dir=rts_gmlc_dir,\n file_name=rts_downloader.rts_download_path+os.sep+'templates'+os.sep+'rts_with_network_template_hotstart.dat')", "_____no_output_____" ], [ "# next, we'll convert the included time-series data into input for the populator\n# (this step can take a while because we set up an entire year's worth of data)\nfrom prescient.downloaders.rts_gmlc_prescient.process_RTS_GMLC_data import create_timeseries\ncreate_timeseries(rts_downloader.rts_download_path)", "_____no_output_____" ], [ "# Lastly, Prescient comes with some pre-made scripts and templates to help get up-and-running with RTS-GMLC.\n# This function just puts those in rts_downloader.rts_download_path from \n# Prescient/prescient/downloaders/rts_gmlc_prescient/runners\nrts_downloader.copy_templates()\nos.listdir(rts_downloader.rts_download_path)", "_____no_output_____" ] ], [ [ "NOTE: the above steps are completely automated in the `__main__` function of Prescient/prescient/downloaders/rts_gmlc.py", "_____no_output_____" ], [ "### Running the populator\nBelow we'll show how the populator is set-up by the scripts above an subsequently run.", "_____no_output_____" ] ], [ [ "# we'll work in the directory we've set up now for\n# running the populator and simulator\n\n# If prescient is properly installed, this could be\n# a directory anywhere on your system\nos.chdir(rts_downloader.rts_download_path)\nos.getcwd()", "_____no_output_____" ], [ "# helper for displaying *.txt files in jupyter\ndef print_file(file_n):\n '''prints file contents to the screen'''\n with open(file_n, 'r') as f:\n for l in f:\n print(l.strip())", "_____no_output_____" ] ], [ [ "Generally, one would call `runner.py populate_with_network_deterministic.txt` to set-up the data for the simulator. We'll give a brief overview below as to how that is orchestrated.", "_____no_output_____" ] ], [ [ "print_file('populate_with_network_deterministic.txt')", "_____no_output_____" ] ], [ [ "First, notice the `command/exec` line, which tells `runner.py` which command to execute. These `*.txt` files could be replaced with bash scripts, or run from the command line directly. In this case,\n\n`populator.py --start-date 2020-07-10 --end-date 2020-07-16 --source-file sources_with_network.txt --output-directory deterministic_with_network_scenarios --scenario-creator-options-file deterministic_scenario_creator_with_network.txt \n--traceback`\n\nwould give the same result. The use of the `*.txt` files enables saving these complex commands in a cross-platform compatable manner.\n\nThe `--start-date` and `--end-date` specify the date range for which we'll generate simulator input. The `--ouput-directory` gives the path (relative in this case) where the simulator input (the output of this script) should go. The `--sources-file` and `--scenario-creator-options-file` point to other `*.txt` files.", "_____no_output_____" ], [ "#### --scenario-creator-options-file", "_____no_output_____" ] ], [ [ "print_file('deterministic_scenario_creator_with_network.txt')", "_____no_output_____" ] ], [ [ "This file points the `scenario_creator` to the templates created/copied above, which store the \"static\" prescient data, e.g., `--sceneario-template-file` points to the bus/branch/generator data. The `--tree-template-file` is depreciated at this point, pending re-introdcution of stochastic unit commitment capabilities.\n", "_____no_output_____" ] ], [ [ "# This prints out the files entire contents, just to look at.\n# See if you can find the set \"NondispatchableGenerators\"\nprint_file('templates/rts_with_network_template_hotstart.dat')", "_____no_output_____" ] ], [ [ "#### --sources-file", "_____no_output_____" ] ], [ [ "print_file('sources_with_network.txt')", "_____no_output_____" ] ], [ [ "This file connects each \"Source\" (e.g., `122_HYDRO_1`) in the file `templates/rts_with_network_template_hotstart.dat` to the `*.csv` files generated above for both load and renewable generation. Other things controlled here are whether a renewable resource is dispatchable at all.", "_____no_output_____" ] ], [ [ "# You could also run 'runner.py populate_with_network_deterministic.txt' from the command line\nimport prescient.scripts.runner as runner\nrunner.run('populate_with_network_deterministic.txt')", "_____no_output_____" ] ], [ [ "This creates the \"input deck\" for July 10, 2020 -- July 16, 2020 for the simulator in the ouput directory `determinstic_with_network_scenarios`.", "_____no_output_____" ] ], [ [ "sorted(os.listdir('deterministic_with_network_scenarios'+os.sep+'pyspdir_twostage'))", "_____no_output_____" ] ], [ [ "Inside each of these directories are the `*.dat` files specifying the simulation for each day.", "_____no_output_____" ] ], [ [ "sorted(os.listdir('deterministic_with_network_scenarios'+os.sep+'pyspdir_twostage'+os.sep+'2020-07-10'))", "_____no_output_____" ] ], [ [ "`Scenario_actuals.dat` contains the \"actuals\" for the day, which is used for the SCED problems, and `Scenario_forecast.dat` contains the \"forecasts\" for the day. The other `*.dat` files are hold-overs from stochastic mode.\n\n`scenarios.csv` has forecast and actuals data for every uncertain generator in an easy-to-process format.", "_____no_output_____" ], [ "### Running the simulator\nBelow we show how to set-up and run the simulator.", "_____no_output_____" ], [ "Below is the contents of the included `simulate_with_network_deterministic.txt`:", "_____no_output_____" ] ], [ [ "print_file('simulate_with_network_deterministic.txt')", "_____no_output_____" ] ], [ [ "Description of the options included are as follows:\n - `--data-directory`: Where the source data is (same as outputs for the populator).\n - `--simulate-out-of-sample`: This option directs the simulator to use different forecasts from actuals. Without it, the simulation is run with forecasts equal to actuals\n - `--run-sced-with-persistent-forecast-errors`: This option directs the simulator to use forecasts (adjusted by the current forecast error) for sced look-ahead periods, instead of using the actuals for sced look-ahead periods.\n - `--output-directory`: Where to write the output data.\n - `--run-deterministic-ruc`: Directs the simualtor to run a deterministic (as opposed to stochastic) unit commitment problem. Required for now as stochastic unit commitment is currently deprecated.\n - `--start-date`: Day to start the simulation on. Must be in the data-directory.\n - `--num-days`: Number of days to simulate, including the start date. All days must be included in the data-directory.\n - `--sced-horizon`: Number of look-ahead periods (in hours) for the real-time economic dispatch problem.\n - `--traceback`: If enabled, the simulator will print a trace if it failed.\n - `--random-seed`: Unused currently.\n - `--output-sced-initial-conditions`: Prints the initial conditions for the economic dispatch problem to the screen.\n - `--output-sced-demands`: Prints the demands for the economic dispatch problem to the screen.\n - `--output-sced-solutions`: Prints the solution for the economic dispatch problem to the screen.\n - `--output-ruc-initial-conditions`: Prints the initial conditions for the unit commitment problem to the screen.\n - `--output-ruc-solutions`: Prints the commitment solution for the unit commitment problem to the screen.\n - `--output-ruc-dispatches`: Prints the dispatch solution for the unit commitment problem to the screen.\n - `--output-solver-logs`: Prints the logs from the optimization solver (CBC, CPLEX, Gurobi, Xpress) to the screen.\n - `--ruc-mipgap`: Optimality gap to use for the unit commitment problem. Default is 1% used here -- can often be tighted for commerical solvers.\n - `--symbolic-solver-labels`: If set, `symbolic_solver_labels` is used when writing optimization models from Pyomo to the solver. Only useful for low-level debugging.\n - `--reserve-factor`: If set, overwrites any basic reserve factor included in the test data.\n - `--deterministic-ruc-solver`: The optimization solver ('cbc', 'cplex', 'gurobi', 'xpress') used for the unit commitment problem.\n - `--sced-solver`: The optimization solver ('cbc', 'cplex', 'gurobi', 'xpress') used for the economic dispatch problem.\n\nOther options not included in this file, which may be useful:\n - `--compute-market-settlements`: (True/False) If enabled, solves a day-ahead pricing problem (in addition to the real-time pricing problem) and computes generator revenue based on day-ahead and real-time prices.\n - `--day-ahead-pricing`: ('LMP', 'ELMP', 'aCHP') Specifies the type of day-ahead price to use. Default is 'aCHP'.\n - `--price-threashold`: The maximum value for the energy price ($/MWh). Useful for when market settlements are computed to avoid very large LMP values when load shedding occurs.\n - `--reserve-price-threashold`: The maximum value for the reserve price (\\$/MW). Useful for when market settlements are computed to avoid very large LMP values when reserve shortfall occurs.\n - `--deterministic-ruc-solver-options`: Options to pass into the unit commitment solver (specific to the solver used) for every unit commitment solve.\n - `--sced-solver-options`: Options to pass into the economic dispatch solve (specific to the solver used) for every economic dispatch solve.\n - `--plugin`: Path to a Python module to modify Prescient behavior.", "_____no_output_____" ] ], [ [ "# You could also run 'runner.py simulate_with_network_deterministic.txt' from the command line\n# This runs a week of RTS-GMLC, which with the open-source cbc solver will take several (~12) minutes\nimport prescient.scripts.runner as runner\nrunner.run('simulate_with_network_deterministic.txt')", "_____no_output_____" ] ], [ [ "### Analyzing results\nSummary and detailed `*.csv` files are written to the specified output directory (in this case, `deterministic_with_network_simulation_output`).", "_____no_output_____" ] ], [ [ "sorted(os.listdir('deterministic_with_network_simulation_output/'))", "_____no_output_____" ] ], [ [ "Below we give a breif description of the contents of each file.\n- `bus_detail.csv`: Detailed results (demand, LMP, etc.) by bus.\n- `daily_summary.csv`: Summary results by day. Demand, renewables data, costs, load shedding/over generation, etc.\n- `hourly_gen_summary.csv`: Gives total thermal headroom and data on reserves (shortfall, price) by hour.\n- `hourly_summary.csv`: Summary results by hour. Similar to `daily_summary.csv`.\n- `line_detail.csv`: Detailed results (flow in MW) by bus.\n- `overall_simulation_output.csv`: Summary results for the entire simulation run. Similar to `daily_summary.csv`.\n- `plots`: Directory containing stackgraphs for every day of the simulation.\n- `renewables_detail.csv`: Detailed results (output, curtailment) by renewable generator.\n- `runtimes.csv`: Runtimes for each economic dispatch problem.\n- `thermal_detail.csv`: Detailed results (dispatch, commitment, costs) per thermal generator.", "_____no_output_____" ], [ "Generally, the first think to look at, as a sanity check is the stackgraphs:", "_____no_output_____" ] ], [ [ "dates = [f'2020-07-1{i}' for i in range(0,7)]\nfrom IPython.display import Image\nfor date in dates:\n display(Image('deterministic_with_network_simulation_output'+os.sep+'plots'+os.sep+'stackgraph_'+date+'.png',\n width=500))", "_____no_output_____" ] ], [ [ "Due to the non-deterministic nature of most MIP solvers, your results may be slightly different than mine. For my simulation, two things stand out:\n1. The load-shedding at the end of the day (hour 23) on July 12th.\n2. The renewables curtailed the evening of July 15th into the morning of July 16th.\n\nFor this tutorial, let's hypothesize about the cause of (2). Often renewables are curtailed either because of a binding transmission constraint, or because some or all of the thermal generators are operating at minimum power. Let's investigate the first possibility.", "_____no_output_____" ], [ "#### Examining Loaded Transmission Lines", "_____no_output_____" ] ], [ [ "import pandas as pd\n# load in the output data for the lines\nline_flows = pd.read_csv('deterministic_with_network_simulation_output'+os.sep+'line_detail.csv', index_col=[0,1,2,3])\n\n# load in the source data for the lines\nline_attributes = pd.read_csv('RTS-GMLC'+os.sep+'RTS_Data'+os.sep+'SourceData'+os.sep+'branch.csv', index_col=0)\n\n# get the line limits\nline_limits = line_attributes['Cont Rating']\n\n# get a series of flows\nline_flows = line_flows['Flow']", "_____no_output_____" ], [ "line_flows", "_____no_output_____" ], [ "# rename the line_limits to match the\n# index of line_flows\nline_limits.index.name = \"Line\"\nline_limits", "_____no_output_____" ], [ "lines_relative_flow = line_flows/line_limits", "_____no_output_____" ], [ "lines_near_limits_time = lines_relative_flow[ (lines_relative_flow > 0.99) | (lines_relative_flow < -0.99) ]", "_____no_output_____" ], [ "lines_near_limits_time", "_____no_output_____" ] ], [ [ "As we can see, near the end of the day on July 15th and the beginning of the day July 16th, several transmission constraints are binding, which correspond exactly to the periods of renewables curtailment in the stackgraphs above.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
4a53ca27e37704628e669c28db4cef02f70b9ea0
7,267
ipynb
Jupyter Notebook
210107-SingleReview-Prediction.ipynb
MartinTschendel/NLP
4b32a202426c9520d42aba25e84e3d7d4fdb9483
[ "MIT" ]
null
null
null
210107-SingleReview-Prediction.ipynb
MartinTschendel/NLP
4b32a202426c9520d42aba25e84e3d7d4fdb9483
[ "MIT" ]
null
null
null
210107-SingleReview-Prediction.ipynb
MartinTschendel/NLP
4b32a202426c9520d42aba25e84e3d7d4fdb9483
[ "MIT" ]
null
null
null
29.302419
102
0.572451
[ [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd", "_____no_output_____" ], [ "#delimiter = \"\\t\" means tab\n#quoting = 3 means we are ignoring the double quotes in the dataset\ndataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter='\\t', quoting = 3)", "_____no_output_____" ], [ "#use vpn so that stopwords can be downloaded\n\n#importing text cleaning libraries\nimport re \n#nltk helps to remove all useless words (stopwords) such as a, the. and ...\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\n#stemming only concentrates on the roots of the word (loved --> love)\nfrom nltk.stem.porter import PorterStemmer", "[nltk_data] Downloading package stopwords to\n[nltk_data] C:\\Users\\Martin\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n" ], [ "#the list corpus will contain all text cleaned reviews\ncorpus = []\n#iterate through dataset\nfor i in range(0, 1000):\n #removing all punctuations\n #meaning of [^a-zA-Z]: anything except...\n #meaning of ' ': replacement by space\n #meaning of dataset['Review'][i]: place where the cleaning step should happen \n review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i])\n #transform capital letters to lower case by updating the 'review' variable\n review = review.lower()\n #split each review in different words, so that we can apply stemming\n review = review.split()\n #apply stemming (reduce the words to their roots)\n #with 'ps' we created an object to apply stemming\n ps = PorterStemmer()\n #actually stopwords also includes the word 'not'\n #but we have to keep it because it is a clearly negative indicator\n all_stopwords = stopwords.words('english')\n all_stopwords.remove('not')\n #update 'review' by creating a list with the stemmed words\n #this can be done with a single line for loop\n #by applying ps.stem() to the iterator 'word'\n #here we get also rid of the stopwords\n review = [ps.stem(word) for word in review if not word in set(all_stopwords)]\n #join the splitted words together in one review\n #' ' means to separate the words with a space\n review = ' '.join(review)\n #putting each cleaned 'review' into the 'corpus' list \n corpus.append(review)", "_____no_output_____" ], [ "#create bag of words model\n#rows of sparse matrix: different reviews\n#columns of sparse matrix: cleaned words \n#cells of sparse matrix: 1 (word is in review) or 0 (word is not in review)\n#the above described matrix creation is done with tokenization\nfrom sklearn.feature_extraction.text import CountVectorizer\n#create an instance of the class 'CountVectorizer'\n#in () we have to enter the maximum number of words\n#we set this number after we know what is the number of the most frequent words\ncv = CountVectorizer(max_features=1500)\n#'X' stands for our sparse matrix\n#'toarray()' transforms it to a 2D array\nX = cv.fit_transform(corpus).toarray()\n#create dependent vector y\ny = dataset.iloc[:, -1].values\n", "_____no_output_____" ], [ "#split dataset in training and test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)", "_____no_output_____" ], [ "#train random forest model\nfrom sklearn.ensemble import RandomForestClassifier\nclass_rf = RandomForestClassifier(n_estimators = 30, criterion = 'entropy', random_state = 0)\nclass_rf.fit(X_train, y_train)", "_____no_output_____" ], [ "y_pred = class_rf.predict(X_test)\nfrom sklearn.metrics import confusion_matrix, accuracy_score\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\naccuracy_score(y_test, y_pred)", "[[90 7]\n [40 63]]\n" ], [ "def check_review(new_review):\n new_review = re.sub('[^a-zA-Z]', ' ', new_review)\n new_review = new_review.lower()\n new_review = new_review.split()\n ps = PorterStemmer()\n all_stopwords = stopwords.words('english')\n all_stopwords.remove('not')\n new_review = [ps.stem(word) for word in new_review if not word in set(all_stopwords)]\n new_review = ' '.join(new_review)\n new_corpus = [new_review]\n new_X_test = cv.transform(new_corpus).toarray()\n new_y_pred = class_rf.predict(new_X_test)\n return print(new_y_pred)", "_____no_output_____" ], [ "check_review('We loved it')", "[1]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a53ce107393419c0ab19a21c3a04f49f1887be8
51,665
ipynb
Jupyter Notebook
solutions/4 Deep Learning Intro Exercises Solution.ipynb
joelrivas/Keras
f8a8bd3de43ca5db0c5b13f5b2ff0bfb352b0830
[ "MIT" ]
null
null
null
solutions/4 Deep Learning Intro Exercises Solution.ipynb
joelrivas/Keras
f8a8bd3de43ca5db0c5b13f5b2ff0bfb352b0830
[ "MIT" ]
null
null
null
solutions/4 Deep Learning Intro Exercises Solution.ipynb
joelrivas/Keras
f8a8bd3de43ca5db0c5b13f5b2ff0bfb352b0830
[ "MIT" ]
null
null
null
94.279197
36,768
0.835827
[ [ [ "# Deep Learning Intro", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np", "_____no_output_____" ] ], [ [ "## Exercise 1", "_____no_output_____" ], [ "The [Pima Indians dataset](https://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes) is a very famous dataset distributed by UCI and originally collected from the National Institute of Diabetes and Digestive and Kidney Diseases. It contains data from clinical exams for women age 21 and above of Pima indian origins. The objective is to predict based on diagnostic measurements whether a patient has diabetes.\n\nIt has the following features:\n\n- Pregnancies: Number of times pregnant\n- Glucose: Plasma glucose concentration a 2 hours in an oral glucose tolerance test\n- BloodPressure: Diastolic blood pressure (mm Hg)\n- SkinThickness: Triceps skin fold thickness (mm)\n- Insulin: 2-Hour serum insulin (mu U/ml)\n- BMI: Body mass index (weight in kg/(height in m)^2)\n- DiabetesPedigreeFunction: Diabetes pedigree function\n- Age: Age (years)\n\nThe last colum is the outcome, and it is a binary variable.\n\nIn this first exercise we will explore it through the following steps:\n\n1. Load the ..data/diabetes.csv dataset, use pandas to explore the range of each feature\n- For each feature draw a histogram. Bonus points if you draw all the histograms in the same figure.\n- Explore correlations of features with the outcome column. You can do this in several ways, for example using the `sns.pairplot` we used above or drawing a heatmap of the correlations.\n- Do features need standardization? If so what stardardization technique will you use? MinMax? Standard?\n- Prepare your final `X` and `y` variables to be used by a ML model. Make sure you define your target variable well. Will you need dummy columns?", "_____no_output_____" ] ], [ [ "df = pd.read_csv('../data/diabetes.csv')\ndf.head()", "_____no_output_____" ], [ "_ = df.hist(figsize=(12, 10))", "_____no_output_____" ], [ "import seaborn as sns", "_____no_output_____" ], [ "sns.pairplot(df, hue='Outcome')", "_____no_output_____" ], [ "sns.heatmap(df.corr(), annot = True)", "_____no_output_____" ], [ "df.info()", "_____no_output_____" ], [ "df.describe()", "_____no_output_____" ], [ "from sklearn.preprocessing import StandardScaler", "_____no_output_____" ], [ "from keras.utils import to_categorical", "_____no_output_____" ], [ "sc = StandardScaler()\nX = sc.fit_transform(df.drop('Outcome', axis=1))\ny = df['Outcome'].values\ny_cat = to_categorical(y)", "_____no_output_____" ], [ "X.shape", "_____no_output_____" ], [ "y_cat.shape", "_____no_output_____" ] ], [ [ "## Exercise 2", "_____no_output_____" ], [ "Build a fully connected NN model that predicts diabetes. Follow these steps:\n\n1. Split your data in a train/test with a test size of 20% and a `random_state = 22`\n- define a sequential model with at least one inner layer. You will have to make choices for the following things:\n - what is the size of the input?\n - how many nodes will you use in each layer?\n - what is the size of the output?\n - what activation functions will you use in the inner layers?\n - what activation function will you use at output?\n - what loss function will you use?\n - what optimizer will you use?\n- fit your model on the training set, using a validation_split of 0.1\n- test your trained model on the test data from the train/test split\n- check the accuracy score, the confusion matrix and the classification report", "_____no_output_____" ] ], [ [ "X.shape", "_____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_cat,\n random_state=22,\n test_size=0.2)", "_____no_output_____" ], [ "from keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam", "_____no_output_____" ], [ "model = Sequential()\nmodel.add(Dense(32, input_shape=(8,), activation='relu'))\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dense(2, activation='softmax'))\nmodel.compile(Adam(lr=0.05),\n loss='categorical_crossentropy',\n metrics=['accuracy'])", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ], [ "32*8 + 32", "_____no_output_____" ], [ "model.fit(X_train, y_train, epochs=20, verbose=2, validation_split=0.1)", "_____no_output_____" ], [ "y_pred = model.predict(X_test)", "_____no_output_____" ], [ "y_test_class = np.argmax(y_test, axis=1)\ny_pred_class = np.argmax(y_pred, axis=1)", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix", "_____no_output_____" ], [ "pd.Series(y_test_class).value_counts() / len(y_test_class)", "_____no_output_____" ], [ "accuracy_score(y_test_class, y_pred_class)", "_____no_output_____" ], [ "print(classification_report(y_test_class, y_pred_class))", "_____no_output_____" ], [ "confusion_matrix(y_test_class, y_pred_class)", "_____no_output_____" ] ], [ [ "## Exercise 3\nCompare your work with the results presented in [this notebook](https://www.kaggle.com/futurist/d/uciml/pima-indians-diabetes-database/pima-data-visualisation-and-machine-learning). Are your Neural Network results better or worse than the results obtained by traditional Machine Learning techniques?\n\n- Try training a Support Vector Machine or a Random Forest model on the exact same train/test split. Is the performance better or worse?\n- Try restricting your features to only 4 features like in the suggested notebook. How does model performance change?", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.naive_bayes import GaussianNB\n\nfor mod in [RandomForestClassifier(), SVC(), GaussianNB()]:\n mod.fit(X_train, y_train[:, 1])\n y_pred = mod.predict(X_test)\n print(\"=\"*80)\n print(mod)\n print(\"-\"*80)\n print(\"Accuracy score: {:0.3}\".format(accuracy_score(y_test_class,\n y_pred)))\n print(\"Confusion Matrix:\")\n print(confusion_matrix(y_test_class, y_pred))\n print()", "_____no_output_____" ] ], [ [ "## Exercise 4\n\n[Tensorflow playground](http://playground.tensorflow.org/) is a web based neural network demo. It is really useful to develop an intuition about what happens when you change architecture, activation function or other parameters. Try playing with it for a few minutes. You don't nee do understand the meaning of every knob and button in the page, just get a sense for what happens if you change something. In the next chapter we'll explore these things in more detail.\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a53e1d7431c521719d9802100fb0d7e62e9b9f2
3,510
ipynb
Jupyter Notebook
AIDungeon_2.ipynb
gho0sts/AIDungeon
d7b77553d21a171268d4d59e822b2c1635875d26
[ "MIT" ]
null
null
null
AIDungeon_2.ipynb
gho0sts/AIDungeon
d7b77553d21a171268d4d59e822b2c1635875d26
[ "MIT" ]
null
null
null
AIDungeon_2.ipynb
gho0sts/AIDungeon
d7b77553d21a171268d4d59e822b2c1635875d26
[ "MIT" ]
1
2019-12-13T04:47:34.000Z
2019-12-13T04:47:34.000Z
42.289157
344
0.582051
[ [ [ "![BYU PCCL](https://pcc4318.files.wordpress.com/2018/02/asset-1.png?w=150)\n\nSponsored by the BYU PCCL Lab.\n\n> AI Dungeon 2 is a completely AI generated text adventure built with OpenAI's largest GPT-2 model. It's a first of it's kind game that allows you to enter and will react to any action you can imagine.\n\n# Main mirrors of AI Dungeon 2 are currently down due to high download costs.\nWe are using bittorrent as a temporary solution to host game files and keep this game alive. It's not fast, but it's the best we've got right now.\n\nIf you want to help, best thing you can do is to **[download this torrent file with game files](https://github.com/nickwalton/AIDungeon/files/3935881/model_v5.torrent.zip)** and **seed it** indefinitely to the best of your ability. This will help new players download this game faster, and discover the vast worlds of AIDungeon2!\n\n- <a href=\"https://twitter.com/nickwalton00?ref_src=twsrc%5Etfw\" class=\"twitter-follow-button\" data-show-count=\"false\">Follow @nickwalton00</a> on twitter for updates on when it will be available again.\n- **[Support AI Dungeon 2 on Patreon to help get it back up!](https://www.patreon.com/posts/update-32193930)**\n\n## How to play\n1. Click \"Tools\"-> \"Settings...\" -> \"Theme\" -> \"Dark\" (optional but recommended)\n2. Click \"Runtime\" -> \"Run all\"\n3. Wait until all files are downloaded (only has to be one once, and it will take some time)\n4. It will then take a couple minutes to boot up as the model is downloaded loaded onto the GPU. \n\n## About\n* While you wait you can [read adventures others have had](https://aidungeon.io/)\n* [Read more](https://pcc.cs.byu.edu/2019/11/21/ai-dungeon-2-creating-infinitely-generated-text-adventures-with-deep-learning-language-models/) about how AI Dungeon 2 is made.\n\n* Please [support AI Dungeon 2](https://www.patreon.com/join/AIDungeon/) to help get it back up.", "_____no_output_____" ] ], [ [ "!git clone --depth 1 --branch master https://github.com/AIDungeon/AIDungeon/\n%cd AIDungeon\n!./install.sh\nfrom IPython.display import clear_output \nclear_output()\nprint(\"Download Complete!\")", "_____no_output_____" ], [ "from IPython.display import Javascript\ndisplay(Javascript('''google.colab.output.setIframeHeight(0, true, {maxHeight: 5000})'''))\n!python play.py", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ] ]
4a53eba46f07fee03f3c89292660e4f21002fd1c
82,181
ipynb
Jupyter Notebook
book/_build/.jupyter_cache/executed/57fdb57fa84056f97749e9079b8b198f/base.ipynb
hossainlab/HealthDataReports
fdc6c5e6b8e012a02a89ef736ac8e8c6f359e45c
[ "MIT" ]
null
null
null
book/_build/.jupyter_cache/executed/57fdb57fa84056f97749e9079b8b198f/base.ipynb
hossainlab/HealthDataReports
fdc6c5e6b8e012a02a89ef736ac8e8c6f359e45c
[ "MIT" ]
null
null
null
book/_build/.jupyter_cache/executed/57fdb57fa84056f97749e9079b8b198f/base.ipynb
hossainlab/HealthDataReports
fdc6c5e6b8e012a02a89ef736ac8e8c6f359e45c
[ "MIT" ]
null
null
null
38.564524
28,632
0.460982
[ [ [ "import pandas as pd \nimport numpy as np \nimport cufflinks as cf \nimport chart_studio.plotly as py\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot ", "_____no_output_____" ], [ "cf.set_config_file(theme='ggplot',sharing='public',offline=True)", "_____no_output_____" ], [ " init_notebook_mode(connected=True)", "_____no_output_____" ], [ "cf.datagen.lines().iplot(kind='scatter',xTitle='Dates',yTitle='Returns',title='Cufflinks - Line Chart')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
4a5411a127f051bdb889e8adf3fe218e24e56c48
665
ipynb
Jupyter Notebook
supervised/regression/decision_tree/DecisionTreeClassifier.ipynb
adityakamble49/ml-algorithms
1c29efacaf97d7dca5fac24ff5227ba7872b38a5
[ "Apache-2.0" ]
1
2020-03-21T00:38:42.000Z
2020-03-21T00:38:42.000Z
supervised/regression/decision_tree/DecisionTreeClassifier.ipynb
adityakamble49/ml-algorithms
1c29efacaf97d7dca5fac24ff5227ba7872b38a5
[ "Apache-2.0" ]
null
null
null
supervised/regression/decision_tree/DecisionTreeClassifier.ipynb
adityakamble49/ml-algorithms
1c29efacaf97d7dca5fac24ff5227ba7872b38a5
[ "Apache-2.0" ]
null
null
null
16.625
34
0.518797
[ [ [ "## Decision Tree Classifier", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
4a541759271367004111411959637ffd177ce79e
14,185
ipynb
Jupyter Notebook
14_linear_algebra/14_String_Problem-Students-1.ipynb
nachrisman/PHY494
bac0dd5a7fe6f59f9e2ccaee56ebafcb7d97e2e7
[ "CC-BY-4.0" ]
null
null
null
14_linear_algebra/14_String_Problem-Students-1.ipynb
nachrisman/PHY494
bac0dd5a7fe6f59f9e2ccaee56ebafcb7d97e2e7
[ "CC-BY-4.0" ]
null
null
null
14_linear_algebra/14_String_Problem-Students-1.ipynb
nachrisman/PHY494
bac0dd5a7fe6f59f9e2ccaee56ebafcb7d97e2e7
[ "CC-BY-4.0" ]
null
null
null
25.837887
577
0.497991
[ [ [ "# 14 Linear Algebra: String Problem – Students (1)\n## Motivating problem: Two masses on three strings\nTwo masses $M_1$ and $M_2$ are hung from a horizontal rod with length $L$ in such a way that a rope of length $L_1$ connects the left end of the rod to $M_1$, a rope of length $L_2$ connects $M_1$ and $M_2$, and a rope of length $L_3$ connects $M_2$ to the right end of the rod. The system is at rest (in equilibrium under gravity).\n\n![Schematic of the 1 rod/2 masses/3 strings problem.](1rod2masses3strings.svg)\n\nFind the angles that the ropes make with the rod and the tension forces in the ropes.", "_____no_output_____" ], [ "## Theoretical background\nTreat $\\sin\\theta_i$ and $\\cos\\theta_i$ together with $T_i$, $1\\leq i \\leq 3$, as unknowns that have to simultaneously fulfill the nine equations\n\\begin{align}\n-T_1 \\cos\\theta_1 + T_2\\cos\\theta_2 &= 0\\\\\n T_1 \\sin\\theta_1 - T_2\\sin\\theta_2 - W_1 &= 0\\\\\n -T_2\\cos\\theta_2 + T_3\\cos\\theta_3 &= 0\\\\\n T_2\\sin\\theta_2 + T_3\\sin\\theta_3 - W_2 &= 0\\\\\n L_1\\cos\\theta_1 + L_2\\cos\\theta_2 + L_3\\cos\\theta_3 - L &= 0\\\\\n-L_1\\sin\\theta_1 - L_2\\sin\\theta_2 + L_3\\sin\\theta_3 &= 0\\\\\n\\sin^2\\theta_1 + \\cos^2\\theta_1 - 1 &= 0\\\\\n\\sin^2\\theta_2 + \\cos^2\\theta_2 - 1 &= 0\\\\\n\\sin^2\\theta_3 + \\cos^2\\theta_3 - 1 &= 0\n\\end{align}\n\nConsider the nine equations a vector function $\\mathbf{f}$ that takes a 9-vector $\\mathbf{x}$ of the unknowns as argument:\n\\begin{align}\n\\mathbf{f}(\\mathbf{x}) &= 0\\\\\n\\mathbf{x} &= \\left(\\begin{array}{c}\nx_0 \\\\ x_1 \\\\ x_2 \\\\ \nx_3 \\\\ x_4 \\\\ x_5 \\\\ \nx_6 \\\\ x_7 \\\\ x_8\n\\end{array}\\right) \n =\n\\left(\\begin{array}{c}\n\\sin\\theta_1 \\\\ \\sin\\theta_2 \\\\ \\sin\\theta_3 \\\\\n\\cos\\theta_1 \\\\ \\cos\\theta_2 \\\\ \\cos\\theta_3 \\\\\nT_1 \\\\ T_2 \\\\ T_3\n\\end{array}\\right) \\\\\n\\mathbf{L} &= \\left(\\begin{array}{c}\nL \\\\ L_1 \\\\ L_2 \\\\ L_3\n\\end{array}\\right), \\quad\n\\mathbf{W} = \\left(\\begin{array}{c}\nW_1 \\\\ W_2\n\\end{array}\\right)\n\\end{align}", "_____no_output_____" ], [ "Solve with generalized Newton-Raphson:\n$$\n\\mathsf{J}(\\mathbf{x}) \\Delta\\mathbf{x} = -\\mathbf{f}(\\mathbf{x})\n$$\nand \n$$\n\\mathbf{x} \\leftarrow \\mathbf{x} + \\Delta\\mathbf{x}.\n$$", "_____no_output_____" ], [ "## Problem setup\nSet the problem parameters and the objective function $\\mathbf{f}(\\mathbf{x})$", "_____no_output_____" ] ], [ [ "import numpy as np\n\n# problem parameters\nW = np.array([10, 20])\nL = np.array([8, 3, 4, 4])\n\ndef f_2masses(x, L, W):\n return np.array([\n -x[6]*x[3] + x[7]*x[4],\n x[6]*x[0] - x[7]*x[1] - W[0],\n # Eq 3\n # Eq 4\n # Eq 5\n # Eq 6\n x[0]**2 + x[3]**2 - 1,\n # Eq 8\n # Eq 9\n ])\n\ndef fLW(x):\n return f_2masses(x, L, W)", "_____no_output_____" ] ], [ [ "### Initial values\nGuess some initial values (they don't have to fullfil the equations!):", "_____no_output_____" ] ], [ [ "# initial parameters x0\n# ...\nx0 = ", "_____no_output_____" ] ], [ [ "Check that we can calculate $\\mathbf{f}(\\mathbf{x}_0)$:", "_____no_output_____" ] ], [ [ "f_2masses(x0, L, W)", "_____no_output_____" ] ], [ [ "### Visualization\nPlot the positions of the 2 masses and the 3 strings for any solution vector $\\mathbf{x}$:", "_____no_output_____" ] ], [ [ "import matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "def plot_2masses(x, L, W):\n r0 = np.array([0, 0])\n r1 = r0 + np.array([L[0], 0])\n rod = np.transpose([r0, r1])\n \n L1 = r0 + np.array([L[1]*x[3], -L[1]*x[0]])\n L2 = L1 + np.array([L[2]*x[4], -L[2]*x[1]])\n L3 = L2 + np.array([L[3]*x[5], L[3]*x[2]])\n strings = np.transpose([r0, L1, L2, L3])\n \n ax = plt.subplot(111)\n ax.plot(rod[0], rod[1], color=\"black\", marker=\"d\", linewidth=4)\n ax.plot(strings[0], strings[1], marker=\"o\", linestyle=\"-\", linewidth=1)\n ax.set_aspect(1)\n return ax", "_____no_output_____" ] ], [ [ "What does the initial guess look like?", "_____no_output_____" ] ], [ [ "plot_2masses(x0, L, W)", "_____no_output_____" ] ], [ [ "## Jacobian \nWrite a function `Jacobian(f, x, h=1e-5)` that computes the Jacobian matrix numerically (use the central difference algorithm).", "_____no_output_____" ] ], [ [ "def Jacobian(f, x, h=1e-5):\n \"\"\"df_i/dx_j with central difference (f(x+h/2)-f(x-h/2))/h\"\"\"\n J = np.zeros((len(f(x)), len(x)), dtype=np.float64)\n \n raise NotImplementedError\n \n return J", "_____no_output_____" ] ], [ [ "Test Jacobian on \n$$\n\\mathbf{f}(\\mathbf{x}) = \\left( \\begin{array}{c}\n x_0^2 - x_1 \\\\ x_0\n \\end{array}\\right)\n$$\nwith analytical result (compute it analytically!)\n$$\n\\mathsf{J} = \\frac{\\partial f_i}{\\partial x_j} = \\ ?\n$$", "_____no_output_____" ] ], [ [ "def ftest(x):\n return np.array([\n # Eq Test 1\n # Eq Test 2\n ])\nx0test = # choose a simple test vector\n# run function and print result\n# compare to analytical result", "_____no_output_____" ] ], [ [ "Just testing that it also works for our starting vector:", "_____no_output_____" ] ], [ [ "Jacobian(fLW, x0)", "_____no_output_____" ] ], [ [ "## n-D Newton-Raphson Root Finding \nWrite a function `newton_raphson(f, x, Nmax=100, tol=1e-8, h=1e-5)` to find a root for a vector function `f(x)=0`. (See also [13 Root-finding by trial-and-error](http://asu-compmethodsphysics-phy494.github.io/ASU-PHY494//2017/03/16/13_Root_finding/) and the _1D Newton-Raphson algorithm_ in [13-Root-finding.ipynb](https://github.com/ASU-CompMethodsPhysics-PHY494/PHY494-resources/blob/master/13_root_finding/13-Root-finding.ipynb).) As a convergence criterion we demand that the length of the vector `f(x)` (the norm --- see `np.linalg.norm`) be less than the tolerance.", "_____no_output_____" ] ], [ [ "def newton_raphson(f, x, Nmax=100, tol=1e-8, h=1e-5):\n \"\"\"n-D Newton-Raphson: solves f(x) = 0.\n \n Iterate until |f(x)| < tol or nmax steps.\n \"\"\"\n x = x.copy()\n\n raise NotImplementedError\n \n else:\n print(\"Newton-Raphson: no root found after {0} iterations (eps={1}); \"\n \"best guess is {2} with error {3}\".format(Nmax, tol, x, fx))\n return x", "_____no_output_____" ] ], [ [ "### Solve 2 masses/3 strings problem ", "_____no_output_____" ], [ "#### Solution ", "_____no_output_____" ] ], [ [ "# solve the string problem\nx = ", "_____no_output_____" ] ], [ [ "Plot the starting configuration and the solution:", "_____no_output_____" ] ], [ [ "plot_2masses(x0, L, W)\nplot_2masses(x, L, W)", "_____no_output_____" ] ], [ [ "Pretty-print the solution (angles in degrees):", "_____no_output_____" ] ], [ [ "def pretty_print(x):\n theta = np.rad2deg(np.arcsin(x[0:3]))\n tensions = x[6:]\n print(\"theta1 = {0[0]:.1f} \\t theta2 = {0[1]:.1f} \\t theta3 = {0[2]:.1f}\".format(theta))\n print(\"T1 = {0[0]:.1f} \\t T2 = {0[1]:.1f} \\t T3 = {0[2]:.1f}\".format(tensions))", "_____no_output_____" ], [ "print(\"Starting values\")\npretty_print(x0)\nprint()\nprint(\"Solution\")\npretty_print(x)", "_____no_output_____" ] ], [ [ "#### Show intermediate steps\nCreate a new function `newton_raphson_intermediates()` based on `newtopn_raphson()` that returns *all* trial `x` values including the last one.", "_____no_output_____" ] ], [ [ "def newton_raphson_intermediates(f, x, Nmax=100, tol=1e-8, h=1e-5):\n \"\"\"n-D Newton-Raphson: solves f(x) = 0.\n \n Iterate until |f(x)| < tol or nmax steps.\n \n Returns all intermediates.\n \"\"\"\n intermediates = []\n x = x.copy()\n\n raise NotImplementedError\n \n else:\n print(\"Newton-Raphson: no root found after {0} iterations (eps={1}); \"\n \"best guess is {2} with error {3}\".format(Nmax, tol, x, fx))\n return np.array(intermediates)", "_____no_output_____" ] ], [ [ "Visualize the intermediate configurations:", "_____no_output_____" ] ], [ [ "x_series = newton_raphson_intermediates(fLW, x0)", "_____no_output_____" ], [ "ax = plt.subplot(111)\nax.set_prop_cycle(\"color\", [plt.cm.viridis_r(i) for i in np.linspace(0, 1, len(x_series))])\nfor x in x_series:\n plot_2masses(x, L, W)", "_____no_output_____" ] ], [ [ "It's convenient to turn the above plotting code into a function that we can reuse:", "_____no_output_____" ] ], [ [ "def plot_series(x_series, L, W):\n \"\"\"Plot all N masses/strings solution vectors in x_series (N, 9) array\"\"\"\n ax = plt.subplot(111)\n ax.set_prop_cycle(\"color\", [plt.cm.viridis_r(i) for i in np.linspace(0, 1, len(x_series))])\n for x in x_series:\n plot_2masses(x, L, W)\n return ax", "_____no_output_____" ] ], [ [ "## Additional work\nTry different masses, e.g. M1 = M2 = 10, or M1= 0 , M2 = 10.", "_____no_output_____" ], [ "### M1 = M2 = 10 ", "_____no_output_____" ], [ "### M1 = 0, M2 = 10 ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
4a54193191d48a9e4c9b2a8ae004aac3c97da6af
67,704
ipynb
Jupyter Notebook
notebook/modelisation_rf.ipynb
Orlogskapten/dvf_ensae_sbra
d43a8d051075b40046041f6b9f50786a191f4b22
[ "MIT" ]
1
2021-07-16T15:49:48.000Z
2021-07-16T15:49:48.000Z
notebook/modelisation_rf.ipynb
Orlogskapten/dvf_ensae_sbra
d43a8d051075b40046041f6b9f50786a191f4b22
[ "MIT" ]
1
2020-12-18T07:51:09.000Z
2020-12-18T08:00:29.000Z
notebook/modelisation_rf.ipynb
Orlogskapten/dvf_ensae_sbra
d43a8d051075b40046041f6b9f50786a191f4b22
[ "MIT" ]
2
2020-12-16T14:02:08.000Z
2020-12-18T11:21:03.000Z
135.679359
52,358
0.86571
[ [ [ "# Prédiction à l'aide de forêts aléatoires", "_____no_output_____" ], [ "Les forêts aléatoires sont des modèles de bagging ne nécessitant pas beaucoup de *fine tuning* pour obtenir des performances correctes. De plus, ces méthodes sont plus résitances au surapprentissage par rapport à d'autres méthodes.", "_____no_output_____" ] ], [ [ "from google.colab import drive\ndrive.mount('/content/drive')", "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n" ], [ "dossier_donnees = \"/content/drive/My Drive/projet_info_Ensae\"", "_____no_output_____" ], [ "import pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn import metrics\nfrom sklearn.model_selection import GridSearchCV\nimport numpy as np\nfrom matplotlib import pyplot as plt\n", "_____no_output_____" ] ], [ [ "## Lecture des données de train et validation", "_____no_output_____" ] ], [ [ "donnees = pd.read_csv(dossier_donnees + \"/donnees_model/donnees_train.csv\", index_col = 1)", "_____no_output_____" ], [ "donnees_validation = pd.read_csv(dossier_donnees + \"/donnees_model/donnees_validation.csv\", index_col = 1)", "_____no_output_____" ], [ "donnees.drop(columns= \"Unnamed: 0\", inplace = True)", "_____no_output_____" ], [ "donnees_validation.drop(columns= \"Unnamed: 0\", inplace = True)", "_____no_output_____" ] ], [ [ "On va faire quelques petites modifications sur les donnees : \n- Les variables `arrondissement`, `pp`, `mois` vont être considérées comme variable catégorielle\n- Les variables `datemut` vont être supprimées\n- La variable `sbati_squa` est retirée en suivant les recommandations de Maître Wenceslas Sanchez.", "_____no_output_____" ] ], [ [ "donnees[\"arrondissement\"] = donnees[\"arrondissement\"].astype(\"object\")\n\ndonnees[\"pp\"] = donnees[\"pp\"].astype(\"object\")\n\ndonnees[\"mois\"] = donnees[\"datemut\"].str[5:7].astype(\"object\")\n\ndonnees_train = donnees.drop(columns = [\"nblot\", \"nbpar\", \"nblocmut\", \"nblocdep\",\"datemut\",\"sbati_squa\"])\n", "_____no_output_____" ], [ "donnees_validation[\"arrondissement\"] = donnees_validation[\"arrondissement\"].astype(\"object\")\n\ndonnees_validation[\"pp\"] = donnees_validation[\"pp\"].astype(\"object\")\n\ndonnees_validation[\"mois\"] = donnees_validation[\"datemut\"].str[5:7].astype(\"object\")\n\ndonnees_validation.drop(columns = [\"nblot\", \"nbpar\", \"nblocmut\", \"nblocdep\",\"datemut\",\"sbati_squa\"], inplace = True)", "_____no_output_____" ], [ "donnees_train.rename(columns = {\"valfoncact2\" : \"valfoncact\"}, inplace = True)\r\ndonnees_validation.rename(columns = {\"valfoncact2\" : \"valfoncact\"}, inplace = True)", "_____no_output_____" ], [ "def preparation(table):\r\n #Restriction à certains biens\r\n table = table[(table[\"valfoncact\"] > 1e5) & (table[\"valfoncact\"] < 3*(1e6))]\r\n #Ajout données brut\r\n men_brut = table.loc[:, \"Men\":\"Men_mais\"].apply(lambda x : x*table[\"Men\"], axis = 0).add_suffix(\"_brut\")\r\n ind_brut = table.loc[:, \"Ind_0_3\":\"Ind_80p\"].apply(lambda x : x*table[\"Ind\"], axis = 0).add_suffix(\"_brut\")\r\n table = pd.concat([table, men_brut, ind_brut],axis = 1)\r\n table_X = table.drop(columns = [\"valfoncact\"]).to_numpy()\r\n table_Y = table[\"valfoncact\"].to_numpy()\r\n nom = table.drop(columns = [\"valfoncact\"]).columns\r\n return(table_X,table_Y,nom)", "_____no_output_____" ], [ "donnees_validation_prep_X,donnees_validation_prep_Y,nom = preparation(donnees_validation)\r\ndonnees_train_prep_X,donnees_train_prep_Y,nom = preparation(donnees_train)", "_____no_output_____" ] ], [ [ "## Modélisation\n", "_____no_output_____" ] ], [ [ "rf = RandomForestRegressor(random_state=42,n_jobs = -1)", "_____no_output_____" ] ], [ [ "Pour le choix du nombre de variables testés à chaque split, Breiman [2000] recommande qu'utiliser dans les problèmes de régression $\\sqrt{p}$ comme valeur où p désigne le nombre de covariables. Ici $p$ vaut 67. On prendra donc $p = 8$ ainsi que $6$ et $16$.\r\n\r\nLe nombre d'arbres (`n_estimators`) n'est *a priori* pas le critère le plus déterminant dans la performance des forêts aléatoires au delà d'un certain seuil. Nous essayons ici des valeurs *conventionnelles*.\r\n\r\nPour contrôler la profondeur des feuilles de chaque arbre CART, nous utilisons le nombre d'individus minimums dans chaque feuille de l'arbre. Plus il est grand, plus l'arbre sera petit. Notons que les arbres ne sont pas élagués ici.", "_____no_output_____" ] ], [ [ "param_grid = { \n 'n_estimators': [100,200,500,1000],\n 'max_features': [6,8,16],\n 'min_samples_leaf' : [1,2,5,10]\n}", "_____no_output_____" ], [ "rf_grid_search = GridSearchCV(estimator = rf, param_grid = param_grid,cv = 3, verbose=2, n_jobs = -1)", "_____no_output_____" ], [ "rf_grid_search.fit(donnees_train_prep_X, donnees_train_prep_Y)\r\nprint(rf_grid_search.best_params_)", "Fitting 3 folds for each of 48 candidates, totalling 144 fits\n" ], [ "rf2 = RandomForestRegressor(random_state=42,n_jobs = -1, max_features = 16, min_samples_leaf= 2, n_estimators= 1000)", "_____no_output_____" ], [ "rf2.fit(donnees_train_prep_X,donnees_train_prep_Y)", "_____no_output_____" ], [ "pred = rf2.predict(donnees_validation_prep_X)", "_____no_output_____" ], [ "np.sqrt(metrics.mean_squared_error(donnees_validation_prep_Y,pred))", "_____no_output_____" ] ], [ [ "## Visualisation de l'importance des variables", "_____no_output_____" ], [ "Afin de savoir quelles sont les variables les plus importantes dans la prédiction, nous allons utiliser l'importance des variables. Il s'agit ici d'une importance basée sur la diminution de l'indice de Gini.", "_____no_output_____" ] ], [ [ "sorted_idx = rf2.feature_importances_.argsort()\r\nplt.figure(figsize=(10,15))\r\nplt.barh(nom[sorted_idx], rf2.feature_importances_[sorted_idx])\r\nplt.xlabel(\"Random Forest Feature Importance\")", "_____no_output_____" ] ], [ [ "On note que les variables les plus importantes pour la prédiction sont : \r\n- sbati : la surface du bien\r\n- pp : le nombre de pièces\r\n- nv_par_hab : le niveau de vie par habitant du carreaux de 200 mètres dans lequel le bien se situe\r\n- Men_mai : Part de ménages en maison\r\n- arrondissement : Arrondissement dans lequel se situe le bien\r\n- Men_prop : Part de ménages propriétaires\r\n- Ind_80p : Part de plus de 80 ans\r\n- Ind_65_79 : Part d'individus âgés entre 65 et 79 ans\r\n- Men_mai_brut : Nombre bruts de ménages en maison", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
4a541b9b6274c1ee9f83faafe7ad71c287ad8202
238,619
ipynb
Jupyter Notebook
peqw.ipynb
madjabal/GHZ_Quant_Paper_Research
89e4529dfda1348a14c7d1a86ec876b6173dcb3c
[ "MIT" ]
null
null
null
peqw.ipynb
madjabal/GHZ_Quant_Paper_Research
89e4529dfda1348a14c7d1a86ec876b6173dcb3c
[ "MIT" ]
null
null
null
peqw.ipynb
madjabal/GHZ_Quant_Paper_Research
89e4529dfda1348a14c7d1a86ec876b6173dcb3c
[ "MIT" ]
null
null
null
99.383174
47,364
0.827256
[ [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\nimport torch\nimport torchvision\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nfrom torchvision.utils import save_image\nfrom torchvision.datasets import MNIST\n\nfrom sklearn import preprocessing\n\nimport os\nimport gc\nimport sys", "_____no_output_____" ], [ "def getdef(key, acc):\n return key['Definition of the characteristic-based anomaly variable'][acc]", "_____no_output_____" ], [ "def ispos(value):\n if value > 0:\n return 1\n return 0", "_____no_output_____" ], [ "key = pd.read_csv('var_key.csv')\nkey.set_index('Acronym', inplace=True)", "_____no_output_____" ], [ "d = pd.read_csv('peqw.csv')", "_____no_output_____" ], [ "d.rename(index=str, columns = {'Unnamed: 0':'time'}, inplace=True)", "_____no_output_____" ], [ "d.head()", "_____no_output_____" ], [ "d['mom1m'].head()", "_____no_output_____" ], [ "mom1mcorr = d.corr()['mom1m']", "_____no_output_____" ], [ "key.head()", "_____no_output_____" ], [ "mom1mcorr.sort_values()", "_____no_output_____" ], [ "getdef(key, 'mom6m')", "_____no_output_____" ], [ "getdef(key, 'chmom')", "_____no_output_____" ], [ "sns.scatterplot(x=d['mom1m'], y=d['mom6m'])\nplt.axvline(0,0,1)\nplt.axhline(0,0,1)", "_____no_output_____" ], [ "sns.scatterplot(x=d['mom1m'], y=d['mom12m'])\nplt.axvline(0,0,1)\nplt.axhline(0,0,1)", "_____no_output_____" ], [ "sns.scatterplot(x=d['mom1m'], y=d['chmom'])\nplt.axvline(0,0,1)\nplt.axhline(0,0,1)", "_____no_output_____" ], [ "# Chmom prediction\nchmom_pred = []\nfor i in range(len(d['chmom'])):\n chmom_pred.append(d['chmom'].iloc[i] * d['mom1m'].iloc[i])\n\nprint('right', sum([1 for i in chmom_pred if i > 0]))\nprint('wrong', sum([1 for i in chmom_pred if i < 0]))", "right 295\nwrong 125\n" ], [ "# mom6m prediction\nmom6m_pred = []\nfor i in range(len(d['mom6m'])):\n mom6m_pred.append(d['mom6m'].iloc[i] * d['mom1m'].iloc[i])\n\nprint('right', sum([1 for i in mom6m_pred if i > 0]))\nprint('wrong', sum([1 for i in mom6m_pred if i < 0]))", "right 238\nwrong 182\n" ], [ "# mom12m prediction\nmom12m_pred = []\nfor i in range(len(d['mom12m'])):\n mom12m_pred.append(d['mom12m'].iloc[i] * d['mom1m'].iloc[i])\n\nprint('right', sum([1 for i in mom12m_pred if i > 0]))\nprint('wrong', sum([1 for i in mom12m_pred if i < 0]))", "right 228\nwrong 192\n" ], [ "m = d[['time', 'year', 'month', 'mom1m', 'mom6m', 'mom12m', 'chmom']]", "_____no_output_____" ], [ "m126 = []\nfor i in range(len(m['time'])):\n m126.append(m['mom6m'].iloc[i] - m['chmom'].iloc[i])\nm['mom126m'] = m126", "/anaconda3/lib/python3.6/site-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: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n after removing the cwd from sys.path.\n" ], [ "m.head()", "_____no_output_____" ], [ "# mom126m prediction\nmom126m_pred = []\nfor i in range(len(m['mom126m'])):\n mom126m_pred.append(m['mom126m'].iloc[i] * m['mom1m'].iloc[i])\n\nprint('right', sum([1 for i in mom126m_pred if i > 0]))\nprint('wrong', sum([1 for i in mom126m_pred if i < 0]))", "right 187\nwrong 233\n" ], [ "m['mom126m'].head()", "_____no_output_____" ], [ "# bm1 = []\n# for i in range(len(m['time'])):\n# bm1.append(ispos(m['mom1m'].iloc[i]))\n# m['bmom1m'] = bm1", "_____no_output_____" ], [ "# bm6 = []\n# for i in range(len(m['time'])):\n# bm6.append(ispos(m['mom6m'].iloc[i]))\n# m['bmom6m'] = bm6", "_____no_output_____" ], [ "# bm12 = []\n# for i in range(len(m['time'])):\n# bm12.append(ispos(m['mom12m'].iloc[i]))\n# m['bmom12m'] = bm12", "_____no_output_____" ], [ "d.info()", "<class 'pandas.core.frame.DataFrame'>\nIndex: 420 entries, 0 to 419\nColumns: 105 entries, time to month\ndtypes: float64(102), int64(3)\nmemory usage: 367.8+ KB\n" ], [ "sns.lineplot(y=d['mom1m'], x=d['time'])", "_____no_output_____" ], [ "sns.heatmap(data=m.corr())", "_____no_output_____" ], [ "m.corr()['mom1m']", "_____no_output_____" ], [ "sns.boxplot(x=m['month'],y=m['mom1m'])", "_____no_output_____" ], [ "sm = m.copy()", "_____no_output_____" ], [ "bmom1m = [0 if i > 0 else 1 for i in list(sm['mom1m'])]\n# for i in range(len(sm)):\n# bmom1m.append(sm['mom1m'].iloc[i])\nsm['bmom1m'] = bmom1m", "_____no_output_____" ], [ "sm.drop('mom1m', axis=1, inplace=True)", "_____no_output_____" ], [ "from sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nscaler.fit(sm.drop('bmom1m', axis=1))", "/anaconda3/lib/python3.6/site-packages/sklearn/preprocessing/data.py:645: DataConversionWarning: Data with input dtype int64, float64 were all converted to float64 by StandardScaler.\n return self.partial_fit(X, y)\n" ], [ "scaled_features = scaler.transform(sm.drop('bmom1m', axis=1))", "/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:1: DataConversionWarning: Data with input dtype int64, float64 were all converted to float64 by StandardScaler.\n \"\"\"Entry point for launching an IPython kernel.\n" ], [ "sm_feat = pd.DataFrame(scaled_features, columns=sm.columns[:-1])\nsm_feat.head()", "_____no_output_____" ], [ "from sklearn.model_selection import train_test_split\nKX_train, KX_test, ky_train, ky_test = train_test_split(scaled_features, \n sm['bmom1m'],\n test_size=.30)", "_____no_output_____" ], [ "from sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier(n_neighbors=1)\nknn.fit(KX_train, ky_train)", "_____no_output_____" ], [ "pred = knn.predict(X_test)", "_____no_output_____" ], [ "from sklearn.metrics import classification_report,confusion_matrix", "_____no_output_____" ], [ "print(confusion_matrix(ky_test, pred))", "[[44 0]\n [81 1]]\n" ], [ "print(classification_report(ky_test, pred))\nKX_test.shape", " precision recall f1-score support\n\n 0 0.67 0.50 0.57 44\n 1 0.76 0.87 0.81 82\n\n micro avg 0.74 0.74 0.74 126\n macro avg 0.72 0.68 0.69 126\nweighted avg 0.73 0.74 0.73 126\n\n" ], [ "error_rate = []\n\n# Will take some time\nfor i in range(1,100):\n \n knn = KNeighborsClassifier(n_neighbors=i)\n knn.fit(KX_train,ky_train)\n pred_i = knn.predict(KX_test)\n error_rate.append(np.mean(pred_i != ky_test))", "_____no_output_____" ], [ "plt.figure(figsize=(10,6))\nplt.plot(range(1,100),error_rate,color='blue', \n linestyle='dashed', marker='o',\n markerfacecolor='red', markersize=10)\nplt.title('Error Rate vs. K Value')\nplt.xlabel('K')\nplt.ylabel('Error Rate')", "[0.2857142857142857, 0.31746031746031744, 0.2619047619047619, 0.2698412698412698, 0.30158730158730157, 0.2857142857142857, 0.2777777777777778, 0.2857142857142857, 0.2857142857142857, 0.2698412698412698, 0.29365079365079366, 0.2857142857142857, 0.2777777777777778, 0.2857142857142857, 0.2857142857142857, 0.2857142857142857, 0.3333333333333333, 0.3253968253968254, 0.30952380952380953, 0.30952380952380953, 0.29365079365079366, 0.29365079365079366, 0.30158730158730157, 0.29365079365079366, 0.2857142857142857, 0.2857142857142857, 0.29365079365079366, 0.30158730158730157, 0.29365079365079366, 0.30158730158730157, 0.30158730158730157, 0.2857142857142857, 0.30158730158730157, 0.30952380952380953, 0.30158730158730157, 0.30952380952380953, 0.30158730158730157, 0.30952380952380953, 0.30952380952380953, 0.31746031746031744, 0.3253968253968254, 0.31746031746031744, 0.3253968253968254, 0.30158730158730157, 0.3253968253968254, 0.30158730158730157, 0.30158730158730157, 0.30158730158730157, 0.31746031746031744, 0.2857142857142857, 0.31746031746031744, 0.30158730158730157, 0.31746031746031744, 0.29365079365079366, 0.30952380952380953, 0.30952380952380953, 0.30952380952380953, 0.30158730158730157, 0.30158730158730157, 0.30158730158730157, 0.31746031746031744, 0.31746031746031744, 0.30952380952380953, 0.30952380952380953, 0.31746031746031744, 0.30952380952380953, 0.30952380952380953, 0.30158730158730157, 0.30952380952380953, 0.30158730158730157, 0.3253968253968254, 0.31746031746031744, 0.31746031746031744, 0.29365079365079366, 0.30952380952380953, 0.30158730158730157, 0.31746031746031744, 0.30158730158730157, 0.31746031746031744, 0.30952380952380953, 0.30952380952380953, 0.30952380952380953, 0.30158730158730157, 0.30158730158730157, 0.30158730158730157, 0.30952380952380953, 0.30952380952380953, 0.30952380952380953, 0.31746031746031744, 0.31746031746031744, 0.31746031746031744, 0.31746031746031744, 0.31746031746031744, 0.31746031746031744, 0.31746031746031744, 0.31746031746031744, 0.30952380952380953, 0.30952380952380953, 0.31746031746031744]\n" ], [ "knn = KNeighborsClassifier(n_neighbors=3)\n\nknn.fit(KX_train, ky_train)\npred = knn.predict(KX_test)\n\nprint(confusion_matrix(ky_test,pred))\nprint(classification_report(ky_test,pred))", "[[22 22]\n [11 71]]\n precision recall f1-score support\n\n 0 0.67 0.50 0.57 44\n 1 0.76 0.87 0.81 82\n\n micro avg 0.74 0.74 0.74 126\n macro avg 0.72 0.68 0.69 126\nweighted avg 0.73 0.74 0.73 126\n\n" ], [ "X = m.drop(['mom1m'], axis=1)\ny = m['mom1m']", "_____no_output_____" ], [ "from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, \n test_size=.30, \n random_state=101)", "_____no_output_____" ], [ "from sklearn.linear_model import LinearRegression", "_____no_output_____" ], [ "lm = LinearRegression()\nlm.fit(X_train, y_train)", "_____no_output_____" ], [ "lm.intercept_", "_____no_output_____" ], [ "coeff_df = pd.DataFrame(lm.coef_, X.columns)\ncoeff_df", "_____no_output_____" ], [ "predictions = lm.predict(X_test)", "_____no_output_____" ], [ "sns.scatterplot(y_test,predictions)", "_____no_output_____" ], [ "sns.distplot((y_test-predictions));", "_____no_output_____" ], [ "from sklearn import metrics", "_____no_output_____" ], [ "print('MAE:', metrics.mean_absolute_error(y_test, predictions))\nprint('MSE:', metrics.mean_squared_error(y_test, predictions))\nprint('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, predictions)))", "MAE: 0.020159518076388893\nMSE: 0.0010841011809668592\nRMSE: 0.03292569180695919\n" ], [ "pm = m.copy()", "_____no_output_____" ], [ "pmom1m = []\npmom6m = []\npmom12m = []\npchmom = []\npmom126m = []\n\ncount = 0\n\nfor i in range(len(pm)):\n count += 1\n pmom1m.append(pm['mom1m'].iloc[i] * 100)\n pmom6m.append(pm['mom6m'].iloc[i] * 100)\n pmom12m.append(pm['mom12m'].iloc[i] * 100)\n pchmom.append(pm['chmom'].iloc[i] * 100)\n pmom126m.append(pm['mom126m'].iloc[i] * 100)\n\npm['pmom1m'] = pmom1m\npm['pmom6m'] = pmom6m\npm['pmom12m'] = pmom12m\npm['pchmom'] = pchmom\npm['pmom126m'] = pmom126m", "_____no_output_____" ], [ "pm.head()", "_____no_output_____" ], [ "pm.drop(['mom1m', 'mom6m', 'mom12m', 'chmom', 'mom126m'], axis=1, inplace=True)", "_____no_output_____" ], [ "# features = d.columns\n# x = d[features]\n# y = d['mom1m']\n# x = StandardScaler().fit_transform(x)", "_____no_output_____" ], [ "# from sklearn.decomposition import PCA\n# pca = PCA(n_components=2)\n# principalComponents = pca.fit_transform(x)\n# principalDf = pd.DataFrame(data = principalComponents, \n# columns = ['principal component 1', \n# 'principal component 2'])", "_____no_output_____" ], [ "# finalDf = pd.concat([principalDf, d[['mom1m']]], axis = 1)", "_____no_output_____" ], [ "# sns.scatterplot(x=principalDf['principal component 1'], \n# y=principalDf['principal component 2'])", "_____no_output_____" ], [ "sm.to_csv()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a5434ae786ec22634a53a046ace60ca18de287b
26,148
ipynb
Jupyter Notebook
CERN - Practical Introduction To Quantum Computing/Lecture 4 Resources/8.-Deutsch-Jozsa And Grover With Aqua[Run In IBM Quantum Experience].ipynb
bobsub218/exercise-qubit
32e1b851f65b98dcdf90ceaca1bd52ac6553e63a
[ "MIT" ]
229
2020-11-13T07:11:20.000Z
2022-03-06T02:27:45.000Z
CERN - Practical Introduction To Quantum Computing/Lecture 4 Resources/8.-Deutsch-Jozsa And Grover With Aqua[Run In IBM Quantum Experience].ipynb
Parv-01/Quantum-Computing-Collection-Of-Resources
42546e04d3dfce1ff3bb060dea5cd4462e2e0243
[ "MIT" ]
6
2020-12-25T17:25:14.000Z
2021-04-26T07:56:06.000Z
CERN - Practical Introduction To Quantum Computing/Lecture 4 Resources/8.-Deutsch-Jozsa And Grover With Aqua[Run In IBM Quantum Experience].ipynb
Parv-01/Quantum-Computing-Collection-Of-Resources
42546e04d3dfce1ff3bb060dea5cd4462e2e0243
[ "MIT" ]
50
2020-11-13T08:55:28.000Z
2022-03-14T21:16:07.000Z
88.938776
12,380
0.844921
[ [ [ "# Deutsch-Jozsa and Grover with Aqua", "_____no_output_____" ], [ "The Aqua library in Qiskit implements some common algorithms so that they can be used without needing to program the circuits for each case. In this notebook, we will show how we can use the Deutsch-Jozsa and Grover algorithms.", "_____no_output_____" ], [ "## Detusch-Jozsa", "_____no_output_____" ], [ "To use the Deutsch-Jozsa algorithm, we need to import some extra packages in addition to the ones we have been using.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nfrom qiskit import *\nfrom qiskit.visualization import *\nfrom qiskit.tools.monitor import *\nfrom qiskit.aqua import *\nfrom qiskit.aqua.components.oracles import *\nfrom qiskit.aqua.algorithms import *", "_____no_output_____" ] ], [ [ "To specify the elements of the Deutsch-Jozsa algorithm, we must use an oracle (the function that we need to test to see if it is constant or balanced). Aqua offers the possibility of defining this oracle at a high level, without giving the actual quantum gates, with *TruthTableOracle*.\n\n*TruthTableOracle* receives a string of zeroes and ones of length $2^n$ that sets what are the values of the oracle for the $2^n$ binary strings in lexicographical order. For example, with the string 0101 we will have a boolean function that is 0 on 00 and 10 but 1 on 01 and 11 (and, thus, it is balanced).", "_____no_output_____" ] ], [ [ "oracle = TruthTableOracle(\"0101\")\noracle.construct_circuit().draw(output='mpl')", "_____no_output_____" ] ], [ [ "Once we have defined the oracle, we can easily create an instance of the Deutsch-Jozsa algorithm and draw the circuit.", "_____no_output_____" ] ], [ [ "dj = DeutschJozsa(oracle)\ndj.construct_circuit(measurement=True).draw(output='mpl')", "_____no_output_____" ] ], [ [ "Obviously, we could execute this circuit on any backend. However, Aqua specifies some extra elements in addition to the circuit, as for instance how the results are to be interpreted.\n\nTo execute a quantum algorithm in Aqua, we need to pass it a *QuantumInstance* (which includes the backend and possibly other settings) and the algorithm will use it as many times as need. The result will include information about the execution and, in the case of Deutsch-Jozsa, the final veredict.", "_____no_output_____" ] ], [ [ "backend = Aer.get_backend('qasm_simulator')\nquantum_instance = QuantumInstance(backend)\nresult = dj.run(quantum_instance)\nprint(result)", "{'measurement': {'01': 1024}, 'result': 'balanced'}\n" ] ], [ [ "Let us check that it also works with constant functions.", "_____no_output_____" ] ], [ [ "oracle2 = TruthTableOracle('00000000')\ndj2 = DeutschJozsa(oracle2)\nresult = dj2.run(quantum_instance)\nprint(\"The function is\",result['result'])", "The function is constant\n" ] ], [ [ "# Grover", "_____no_output_____" ], [ "As in the case of Deutsch-Jozsa, for the Aqua implementation of Grover's algorithm we need to provide an oracle. We can also specify the number of iterations.", "_____no_output_____" ] ], [ [ "backend = Aer.get_backend('qasm_simulator')\noracle3 = TruthTableOracle('0001')\ng = Grover(oracle3, iterations=1)", "_____no_output_____" ] ], [ [ "The execution is also similar to the one of Deutsch-Jozsa", "_____no_output_____" ] ], [ [ "result = g.run(quantum_instance)\nprint(result)", "{'measurement': {'11': 1024}, 'top_measurement': '11', 'circuit': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x7f24168f9210>, 'assignment': [1, 2], 'oracle_evaluation': True}\n" ] ], [ [ "It can also be interesting to use oracles that we construct from logical expressions", "_____no_output_____" ] ], [ [ "expression = '(x | y) & (~y | z) & (~x | ~z | w) & (~x | y | z | ~w)'\noracle4 = LogicalExpressionOracle(expression)\ng2 = Grover(oracle4, iterations = 3)\nresult = g2.run(quantum_instance)\nprint(result)", "{'measurement': {'0000': 28, '0001': 23, '0010': 157, '0011': 26, '0100': 22, '0101': 25, '0110': 22, '0111': 22, '1000': 30, '1001': 24, '1010': 20, '1011': 137, '1100': 161, '1101': 157, '1110': 29, '1111': 141}, 'top_measurement': '1100', 'circuit': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x7f2417469e90>, 'assignment': [-1, -2, 3, 4], 'oracle_evaluation': True}\n" ] ], [ [ "If we do not know the number of solutions or if we do not want to specify the number of iterations, we can use the incremenal mode, that allows us to find a solution in time $O(\\sqrt{N})$.", "_____no_output_____" ] ], [ [ "backend = Aer.get_backend('qasm_simulator')\nexpression2 = '(x & y & z & w) | (~x & ~y & ~z & ~w)'\n#expression2 = '(x & y) | (~x & ~y)'\noracle5 = LogicalExpressionOracle(expression2, optimization = True)\ng3 = Grover(oracle5, incremental = True)\nresult = g3.run(quantum_instance)\nprint(result)", "{'measurement': {'0000': 387, '0001': 17, '0010': 15, '0011': 17, '0100': 13, '0101': 9, '0110': 15, '0111': 11, '1000': 14, '1001': 20, '1010': 11, '1011': 16, '1100': 24, '1101': 16, '1110': 15, '1111': 424}, 'top_measurement': '1111', 'circuit': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x7f2438677410>, 'assignment': [1, 2, 3, 4], 'oracle_evaluation': True}\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a54366dbdc974f784ec861fc75c0a7cb42f4cf8
57,895
ipynb
Jupyter Notebook
Creating random dataframes and indexing.ipynb
tanishkasinghal/python
6a349d8363bad96b8e72af98f97239dae25677fe
[ "Apache-2.0" ]
null
null
null
Creating random dataframes and indexing.ipynb
tanishkasinghal/python
6a349d8363bad96b8e72af98f97239dae25677fe
[ "Apache-2.0" ]
null
null
null
Creating random dataframes and indexing.ipynb
tanishkasinghal/python
6a349d8363bad96b8e72af98f97239dae25677fe
[ "Apache-2.0" ]
null
null
null
26.327876
757
0.354538
[ [ [ "import numpy as np\nimport pandas as pd", "_____no_output_____" ], [ "from numpy.random import randn", "_____no_output_____" ], [ "np.random.seed(101)", "_____no_output_____" ], [ "df=pd.DataFrame(randn(5,4),['A','B','C','D','E'],['W','X','Y','Z'])", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df['W']['A']", "_____no_output_____" ], [ "type(df)", "_____no_output_____" ], [ "type(df['W'])", "_____no_output_____" ], [ "df.W", "_____no_output_____" ], [ "df[['W','Z']]", "_____no_output_____" ], [ "df['new']=df['W'] + df['X']", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df.drop('new',axis=1) #axis =0 row", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df.drop('new',axis=1,inplace=True) #allow changes to occur", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df.drop('E',axis=0)", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ] ], [ [ "### why axis=0 is for row and axis=1 for column", "_____no_output_____" ], [ "###### beacuse df.shape -- 5 at index 0 is for row and --4 is for column at index 1 (due to numpy)", "_____no_output_____" ] ], [ [ "# accesss rows --two ways", "_____no_output_____" ], [ "#first by index name", "_____no_output_____" ], [ "df.loc['A'] \n#not only columns rows are also series", "_____no_output_____" ], [ "#By index no", "_____no_output_____" ], [ "df.iloc[0]", "_____no_output_____" ], [ "# selecting subsets of rows and columns", "_____no_output_____" ], [ "df.loc['B','Y']", "_____no_output_____" ], [ "df.loc[['A','B'],['W','Y']]", "_____no_output_____" ] ], [ [ "## Conditional Selection", "_____no_output_____" ] ], [ [ "df>0", "_____no_output_____" ], [ "df[df>0]", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df['W']>0", "_____no_output_____" ], [ "df[df['W']>0] #return oly thoe values which are True", "_____no_output_____" ], [ "df[df['Z']<0]", "_____no_output_____" ], [ "df[df['W']>0][['X','Y']]", "_____no_output_____" ], [ "df[(df['W']>0) and (df['X']>0)] #boolean values cant", "_____no_output_____" ] ], [ [ "##### python and cannot take series of boolean values only single values so we use &", "_____no_output_____" ] ], [ [ "df[(df['W']>0) & (df['X']>0)] ", "_____no_output_____" ], [ "# to reset index to default", "_____no_output_____" ], [ "df.reset_index()", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "#To occur actully we use inplace", "_____no_output_____" ], [ "newind = 'CA NY WY OR CO'.split()", "_____no_output_____" ], [ "newind", "_____no_output_____" ], [ "df['States']=newind", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df.set_index('States')", "_____no_output_____" ], [ "df", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a543c73dd64f75dad39931ee91f7287c9f68812
895,702
ipynb
Jupyter Notebook
1. Load and Visualize Data.ipynb
margaretmz/CVND-Facial-Keypoint-Detection
19999b4a977ac07721ee737d0d4afb687e6cdc95
[ "MIT" ]
2
2019-10-03T01:57:23.000Z
2020-12-05T16:33:57.000Z
1. Load and Visualize Data.ipynb
margaretmz/CVND-Facial-Keypoint-Detection
19999b4a977ac07721ee737d0d4afb687e6cdc95
[ "MIT" ]
5
2021-03-19T02:33:52.000Z
2022-03-11T23:55:47.000Z
1. Load and Visualize Data.ipynb
margaretmz/CVND-Facial-Keypoint-Detection
19999b4a977ac07721ee737d0d4afb687e6cdc95
[ "MIT" ]
null
null
null
134.006882
176,208
0.831721
[ [ [ "# Facial Keypoint Detection\n \nThis project will be all about defining and training a convolutional neural network to perform facial keypoint detection, and using computer vision techniques to transform images of faces. The first step in any challenge like this will be to load and visualize the data you'll be working with. \n\nLet's take a look at some examples of images and corresponding facial keypoints.\n\n<img src='images/key_pts_example.png' width=50% height=50%/>\n\nFacial keypoints (also called facial landmarks) are the small magenta dots shown on each of the faces in the image above. In each training and test image, there is a single face and **68 keypoints, with coordinates (x, y), for that face**. These keypoints mark important areas of the face: the eyes, corners of the mouth, the nose, etc. These keypoints are relevant for a variety of tasks, such as face filters, emotion recognition, pose recognition, and so on. Here they are, numbered, and you can see that specific ranges of points match different portions of the face.\n\n<img src='images/landmarks_numbered.jpg' width=30% height=30%/>\n\n---", "_____no_output_____" ], [ "## Load and Visualize Data\n\nThe first step in working with any dataset is to become familiar with your data; you'll need to load in the images of faces and their keypoints and visualize them! This set of image data has been extracted from the [YouTube Faces Dataset](https://www.cs.tau.ac.il/~wolf/ytfaces/), which includes videos of people in YouTube videos. These videos have been fed through some processing steps and turned into sets of image frames containing one face and the associated keypoints.\n\n#### Training and Testing Data\n\nThis facial keypoints dataset consists of 5770 color images. All of these images are separated into either a training or a test set of data.\n\n* 3462 of these images are training images, for you to use as you create a model to predict keypoints.\n* 2308 are test images, which will be used to test the accuracy of your model.\n\nThe information about the images and keypoints in this dataset are summarized in CSV files, which we can read in using `pandas`. Let's read the training CSV and get the annotations in an (N, 2) array where N is the number of keypoints and 2 is the dimension of the keypoint coordinates (x, y).\n\n---", "_____no_output_____" ], [ "First, before we do anything, we have to load in our image data. This data is stored in a zip file and in the below cell, we access it by it's URL and unzip the data in a `/data/` directory that is separate from the workspace home directory.", "_____no_output_____" ] ], [ [ "# -- DO NOT CHANGE THIS CELL -- #\n!mkdir /data\n!wget -P /data/ https://s3.amazonaws.com/video.udacity-data.com/topher/2018/May/5aea1b91_train-test-data/train-test-data.zip\n!unzip -n /data/train-test-data.zip -d /data", "--2019-06-04 23:47:43-- https://s3.amazonaws.com/video.udacity-data.com/topher/2018/May/5aea1b91_train-test-data/train-test-data.zip\nResolving s3.amazonaws.com (s3.amazonaws.com)... 52.216.128.141\nConnecting to s3.amazonaws.com (s3.amazonaws.com)|52.216.128.141|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 338613624 (323M) [application/zip]\nSaving to: ‘/data/train-test-data.zip’\n\ntrain-test-data.zip 100%[===================>] 322.93M 57.3MB/s in 5.5s \n\n2019-06-04 23:47:49 (59.0 MB/s) - ‘/data/train-test-data.zip’ saved [338613624/338613624]\n\nArchive: /data/train-test-data.zip\n creating: /data/test/\n inflating: /data/test/Abdel_Aziz_Al-Hakim_00.jpg \n inflating: /data/test/Abdel_Aziz_Al-Hakim_01.jpg \n inflating: /data/test/Abdel_Aziz_Al-Hakim_10.jpg \n inflating: /data/test/Abdel_Aziz_Al-Hakim_11.jpg \n inflating: /data/test/Abdel_Aziz_Al-Hakim_40.jpg \n inflating: /data/test/Abdel_Aziz_Al-Hakim_41.jpg \n inflating: /data/test/Abdullah_Gul_10.jpg \n inflating: /data/test/Abdullah_Gul_11.jpg \n inflating: /data/test/Abdullah_Gul_30.jpg \n inflating: /data/test/Abdullah_Gul_31.jpg \n inflating: /data/test/Abdullah_Gul_50.jpg \n inflating: /data/test/Abdullah_Gul_51.jpg \n inflating: /data/test/Adam_Sandler_00.jpg \n inflating: /data/test/Adam_Sandler_01.jpg \n inflating: /data/test/Adam_Sandler_10.jpg \n inflating: /data/test/Adam_Sandler_11.jpg \n inflating: /data/test/Adam_Sandler_40.jpg \n inflating: /data/test/Adam_Sandler_41.jpg \n inflating: /data/test/Adrian_Nastase_10.jpg \n inflating: /data/test/Adrian_Nastase_11.jpg \n inflating: /data/test/Adrian_Nastase_40.jpg \n inflating: /data/test/Adrian_Nastase_41.jpg \n inflating: /data/test/Adrian_Nastase_50.jpg \n inflating: /data/test/Adrian_Nastase_51.jpg \n inflating: /data/test/Agbani_Darego_00.jpg \n inflating: /data/test/Agbani_Darego_01.jpg \n inflating: /data/test/Agbani_Darego_20.jpg \n inflating: /data/test/Agbani_Darego_21.jpg \n inflating: /data/test/Agbani_Darego_40.jpg \n inflating: /data/test/Agbani_Darego_41.jpg \n inflating: /data/test/Agbani_Darego_50.jpg \n inflating: /data/test/Agbani_Darego_51.jpg \n inflating: /data/test/Agnes_Bruckner_00.jpg \n inflating: /data/test/Agnes_Bruckner_01.jpg \n inflating: /data/test/Agnes_Bruckner_10.jpg \n inflating: /data/test/Agnes_Bruckner_11.jpg \n inflating: /data/test/Agnes_Bruckner_20.jpg \n inflating: /data/test/Agnes_Bruckner_21.jpg \n inflating: /data/test/Agnes_Bruckner_40.jpg \n inflating: /data/test/Agnes_Bruckner_41.jpg \n inflating: /data/test/Ahmad_Masood_00.jpg \n inflating: /data/test/Ahmad_Masood_01.jpg \n inflating: /data/test/Ahmad_Masood_30.jpg \n inflating: /data/test/Ahmad_Masood_31.jpg \n inflating: /data/test/Ahmad_Masood_40.jpg \n inflating: /data/test/Ahmad_Masood_41.jpg \n inflating: /data/test/Ahmed_Ahmed_00.jpg \n inflating: /data/test/Ahmed_Ahmed_01.jpg \n inflating: /data/test/Ahmed_Ahmed_10.jpg \n inflating: /data/test/Ahmed_Ahmed_11.jpg \n inflating: /data/test/Ahmed_Ahmed_40.jpg \n inflating: /data/test/Ahmed_Ahmed_41.jpg \n inflating: /data/test/Ahmed_Ahmed_50.jpg \n inflating: /data/test/Ahmed_Ahmed_51.jpg \n inflating: /data/test/Aidan_Quinn_00.jpg \n inflating: /data/test/Aidan_Quinn_01.jpg \n inflating: /data/test/Aidan_Quinn_10.jpg \n inflating: /data/test/Aidan_Quinn_11.jpg \n inflating: /data/test/Aidan_Quinn_20.jpg \n inflating: /data/test/Aidan_Quinn_21.jpg \n inflating: /data/test/Aidan_Quinn_30.jpg \n inflating: /data/test/Aidan_Quinn_31.jpg \n inflating: /data/test/Aishwarya_Rai_00.jpg \n inflating: /data/test/Aishwarya_Rai_01.jpg \n inflating: /data/test/Aishwarya_Rai_10.jpg \n inflating: /data/test/Aishwarya_Rai_11.jpg \n inflating: /data/test/Aishwarya_Rai_40.jpg \n inflating: /data/test/Aishwarya_Rai_41.jpg \n inflating: /data/test/Aishwarya_Rai_50.jpg \n inflating: /data/test/Aishwarya_Rai_51.jpg \n inflating: /data/test/Albert_Brooks_00.jpg \n inflating: /data/test/Albert_Brooks_01.jpg \n inflating: /data/test/Albert_Brooks_10.jpg \n inflating: /data/test/Albert_Brooks_11.jpg \n inflating: /data/test/Albert_Brooks_30.jpg \n inflating: /data/test/Albert_Brooks_31.jpg \n inflating: /data/test/Alejandro_Toledo_10.jpg \n inflating: /data/test/Alejandro_Toledo_11.jpg \n inflating: /data/test/Alejandro_Toledo_30.jpg \n inflating: /data/test/Alejandro_Toledo_31.jpg \n inflating: /data/test/Alejandro_Toledo_50.jpg \n inflating: /data/test/Alejandro_Toledo_51.jpg \n inflating: /data/test/Aleksander_Kwasniewski_00.jpg \n inflating: /data/test/Aleksander_Kwasniewski_01.jpg \n inflating: /data/test/Aleksander_Kwasniewski_10.jpg \n inflating: /data/test/Aleksander_Kwasniewski_11.jpg \n inflating: /data/test/Aleksander_Kwasniewski_20.jpg \n inflating: /data/test/Aleksander_Kwasniewski_21.jpg \n inflating: /data/test/Aleksander_Kwasniewski_30.jpg \n inflating: /data/test/Aleksander_Kwasniewski_31.jpg \n inflating: /data/test/Alex_Ferguson_00.jpg \n inflating: /data/test/Alex_Ferguson_01.jpg \n inflating: /data/test/Alex_Ferguson_10.jpg \n inflating: /data/test/Alex_Ferguson_11.jpg \n inflating: /data/test/Alex_Ferguson_50.jpg \n inflating: /data/test/Alex_Ferguson_51.jpg \n inflating: /data/test/Alexandra_Pelosi_00.jpg \n inflating: /data/test/Alexandra_Pelosi_01.jpg \n inflating: /data/test/Alexandra_Pelosi_10.jpg \n inflating: /data/test/Alexandra_Pelosi_11.jpg \n inflating: /data/test/Alexandra_Pelosi_30.jpg \n inflating: /data/test/Alexandra_Pelosi_31.jpg \n inflating: /data/test/Alfredo_di_Stefano_00.jpg \n inflating: /data/test/Alfredo_di_Stefano_01.jpg \n inflating: /data/test/Alfredo_di_Stefano_20.jpg \n inflating: /data/test/Alfredo_di_Stefano_21.jpg \n inflating: /data/test/Alfredo_di_Stefano_50.jpg \n inflating: /data/test/Alfredo_di_Stefano_51.jpg \n inflating: /data/test/Ali_Abbas_20.jpg \n inflating: /data/test/Ali_Abbas_21.jpg \n inflating: /data/test/Ali_Abbas_30.jpg \n inflating: /data/test/Ali_Abbas_31.jpg \n inflating: /data/test/Ali_Abbas_40.jpg \n inflating: /data/test/Ali_Abbas_41.jpg \n inflating: /data/test/Ali_Abbas_50.jpg \n inflating: /data/test/Ali_Abbas_51.jpg \n inflating: /data/test/Alicia_Silverstone_00.jpg \n inflating: /data/test/Alicia_Silverstone_01.jpg \n inflating: /data/test/Alicia_Silverstone_10.jpg \n inflating: /data/test/Alicia_Silverstone_11.jpg \n inflating: /data/test/Alicia_Silverstone_20.jpg \n inflating: /data/test/Alicia_Silverstone_21.jpg \n inflating: /data/test/Alicia_Silverstone_50.jpg \n inflating: /data/test/Alicia_Silverstone_51.jpg \n inflating: /data/test/Alma_Powell_00.jpg \n inflating: /data/test/Alma_Powell_01.jpg \n inflating: /data/test/Alma_Powell_10.jpg \n inflating: /data/test/Alma_Powell_11.jpg \n inflating: /data/test/Alma_Powell_40.jpg \n inflating: /data/test/Alma_Powell_41.jpg \n inflating: /data/test/Alma_Powell_50.jpg \n inflating: /data/test/Alma_Powell_51.jpg \n inflating: /data/test/Alvaro_Silva_Calderon_00.jpg \n inflating: /data/test/Alvaro_Silva_Calderon_01.jpg \n inflating: /data/test/Alvaro_Silva_Calderon_10.jpg \n inflating: /data/test/Alvaro_Silva_Calderon_11.jpg \n inflating: /data/test/Alvaro_Silva_Calderon_20.jpg \n inflating: /data/test/Alvaro_Silva_Calderon_21.jpg \n inflating: /data/test/Alvaro_Silva_Calderon_30.jpg \n inflating: /data/test/Alvaro_Silva_Calderon_31.jpg \n inflating: /data/test/Amelia_Vega_10.jpg \n inflating: /data/test/Amelia_Vega_11.jpg \n inflating: /data/test/Amelia_Vega_20.jpg \n inflating: /data/test/Amelia_Vega_21.jpg \n inflating: /data/test/Amelia_Vega_30.jpg \n inflating: /data/test/Amelia_Vega_31.jpg \n inflating: /data/test/Amelia_Vega_40.jpg \n inflating: /data/test/Amelia_Vega_41.jpg \n inflating: /data/test/Amy_Brenneman_10.jpg \n inflating: /data/test/Amy_Brenneman_11.jpg \n inflating: /data/test/Amy_Brenneman_30.jpg \n inflating: /data/test/Amy_Brenneman_31.jpg \n inflating: /data/test/Amy_Brenneman_50.jpg \n inflating: /data/test/Amy_Brenneman_51.jpg \n inflating: /data/test/Andrea_Bocelli_10.jpg \n inflating: /data/test/Andrea_Bocelli_11.jpg \n inflating: /data/test/Andrea_Bocelli_20.jpg \n inflating: /data/test/Andrea_Bocelli_21.jpg \n inflating: /data/test/Andrea_Bocelli_30.jpg \n inflating: /data/test/Andrea_Bocelli_31.jpg \n inflating: /data/test/Andy_Roddick_20.jpg \n inflating: /data/test/Andy_Roddick_21.jpg \n inflating: /data/test/Andy_Roddick_40.jpg \n inflating: /data/test/Andy_Roddick_41.jpg \n inflating: /data/test/Andy_Roddick_50.jpg \n inflating: /data/test/Andy_Roddick_51.jpg \n inflating: /data/test/Andy_Rooney_10.jpg \n inflating: /data/test/Andy_Rooney_11.jpg \n inflating: /data/test/Andy_Rooney_20.jpg \n inflating: /data/test/Andy_Rooney_21.jpg \n inflating: /data/test/Andy_Rooney_50.jpg \n inflating: /data/test/Andy_Rooney_51.jpg \n inflating: /data/test/Angel_Lockward_30.jpg \n inflating: /data/test/Angel_Lockward_31.jpg \n inflating: /data/test/Angel_Lockward_40.jpg \n inflating: /data/test/Angel_Lockward_41.jpg \n inflating: /data/test/Angel_Lockward_50.jpg \n inflating: /data/test/Angel_Lockward_51.jpg \n inflating: /data/test/Angela_Bassett_20.jpg \n inflating: /data/test/Angela_Bassett_21.jpg \n inflating: /data/test/Angela_Bassett_30.jpg \n inflating: /data/test/Angela_Bassett_31.jpg \n inflating: /data/test/Angela_Bassett_40.jpg \n inflating: /data/test/Angela_Bassett_41.jpg \n inflating: /data/test/Angelo_Reyes_20.jpg \n inflating: /data/test/Angelo_Reyes_21.jpg \n inflating: /data/test/Angelo_Reyes_30.jpg \n inflating: /data/test/Angelo_Reyes_31.jpg \n inflating: /data/test/Angelo_Reyes_50.jpg \n inflating: /data/test/Angelo_Reyes_51.jpg \n inflating: /data/test/Baburam_Bhattari_00.jpg \n inflating: /data/test/Baburam_Bhattari_01.jpg \n inflating: /data/test/Baburam_Bhattari_20.jpg \n inflating: /data/test/Baburam_Bhattari_21.jpg \n inflating: /data/test/Baburam_Bhattari_30.jpg \n inflating: /data/test/Baburam_Bhattari_31.jpg \n inflating: /data/test/Barbara_Bodine_00.jpg \n inflating: /data/test/Barbara_Bodine_01.jpg \n inflating: /data/test/Barbara_Bodine_20.jpg \n inflating: /data/test/Barbara_Bodine_21.jpg \n inflating: /data/test/Barbara_Bodine_40.jpg \n inflating: /data/test/Barbara_Bodine_41.jpg \n inflating: /data/test/Barbara_Bodine_50.jpg \n" ], [ "# import the required libraries\nimport glob\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimport cv2", "_____no_output_____" ] ], [ [ "Then, let's load in our training data and display some stats about that data to make sure it's been loaded in correctly!", "_____no_output_____" ] ], [ [ "key_pts_frame = pd.read_csv('/data/training_frames_keypoints.csv')\n\nn = 0\nimage_name = key_pts_frame.iloc[n, 0]\nkey_pts = key_pts_frame.iloc[n, 1:].as_matrix()\nkey_pts = key_pts.astype('float').reshape(-1, 2)\n\nprint('Image name: ', image_name)\nprint('Landmarks shape: ', key_pts.shape)\nprint('First 4 key pts: {}'.format(key_pts[:4]))", "Image name: Luis_Fonsi_21.jpg\nLandmarks shape: (68, 2)\nFirst 4 key pts: [[ 45. 98.]\n [ 47. 106.]\n [ 49. 110.]\n [ 53. 119.]]\n" ], [ "# print out some stats about the training data\nprint('Number of images: ', key_pts_frame.shape[0])", "Number of images: 3462\n" ] ], [ [ "## Look at some images\n\nBelow, is a function `show_keypoints` that takes in an image and keypoints and displays them. As you look at this data, **note that these images are not all of the same size**, and neither are the faces! To eventually train a neural network on these images, we'll need to standardize their shape.", "_____no_output_____" ] ], [ [ "def show_keypoints(image, key_pts):\n \"\"\"Show image with keypoints\"\"\"\n plt.imshow(image)\n plt.scatter(key_pts[:, 0], key_pts[:, 1], s=20, marker='.', c='m')\n", "_____no_output_____" ], [ "# Display a few different types of images by changing the index n\n\n# select an image by index in our data frame\nn = 0\nimage_name = key_pts_frame.iloc[n, 0]\nkey_pts = key_pts_frame.iloc[n, 1:].as_matrix()\nkey_pts = key_pts.astype('float').reshape(-1, 2)\n\nplt.figure(figsize=(5, 5))\nshow_keypoints(mpimg.imread(os.path.join('/data/training/', image_name)), key_pts)\nplt.show()", "/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:6: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.\n \n" ] ], [ [ "## Dataset class and Transformations\n\nTo prepare our data for training, we'll be using PyTorch's Dataset class. Much of this this code is a modified version of what can be found in the [PyTorch data loading tutorial](http://pytorch.org/tutorials/beginner/data_loading_tutorial.html).\n\n#### Dataset class\n\n``torch.utils.data.Dataset`` is an abstract class representing a\ndataset. This class will allow us to load batches of image/keypoint data, and uniformly apply transformations to our data, such as rescaling and normalizing images for training a neural network.\n\n\nYour custom dataset should inherit ``Dataset`` and override the following\nmethods:\n\n- ``__len__`` so that ``len(dataset)`` returns the size of the dataset.\n- ``__getitem__`` to support the indexing such that ``dataset[i]`` can\n be used to get the i-th sample of image/keypoint data.\n\nLet's create a dataset class for our face keypoints dataset. We will\nread the CSV file in ``__init__`` but leave the reading of images to\n``__getitem__``. This is memory efficient because all the images are not\nstored in the memory at once but read as required.\n\nA sample of our dataset will be a dictionary\n``{'image': image, 'keypoints': key_pts}``. Our dataset will take an\noptional argument ``transform`` so that any required processing can be\napplied on the sample. We will see the usefulness of ``transform`` in the\nnext section.\n", "_____no_output_____" ] ], [ [ "from torch.utils.data import Dataset, DataLoader\n\nclass FacialKeypointsDataset(Dataset):\n \"\"\"Face Landmarks dataset.\"\"\"\n\n def __init__(self, csv_file, root_dir, transform=None):\n \"\"\"\n Args:\n csv_file (string): Path to the csv file with annotations.\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.key_pts_frame = pd.read_csv(csv_file)\n self.root_dir = root_dir\n self.transform = transform\n\n def __len__(self):\n return len(self.key_pts_frame)\n\n def __getitem__(self, idx):\n image_name = os.path.join(self.root_dir,\n self.key_pts_frame.iloc[idx, 0])\n \n image = mpimg.imread(image_name)\n \n # if image has an alpha color channel, get rid of it\n if(image.shape[2] == 4):\n image = image[:,:,0:3]\n \n key_pts = self.key_pts_frame.iloc[idx, 1:].as_matrix()\n key_pts = key_pts.astype('float').reshape(-1, 2)\n sample = {'image': image, 'keypoints': key_pts}\n\n if self.transform:\n sample = self.transform(sample)\n\n return sample", "_____no_output_____" ] ], [ [ "Now that we've defined this class, let's instantiate the dataset and display some images.", "_____no_output_____" ] ], [ [ "# Construct the dataset\nface_dataset = FacialKeypointsDataset(csv_file='/data/training_frames_keypoints.csv',\n root_dir='/data/training/')\n\n# print some stats about the dataset\nprint('Length of dataset: ', len(face_dataset))", "Length of dataset: 3462\n" ], [ "# Display a few of the images from the dataset\nnum_to_display = 3\n\nfor i in range(num_to_display):\n \n # define the size of images\n fig = plt.figure(figsize=(20,10))\n \n # randomly select a sample\n rand_i = np.random.randint(0, len(face_dataset))\n sample = face_dataset[rand_i]\n\n # print the shape of the image and keypoints\n print(i, sample['image'].shape, sample['keypoints'].shape)\n\n ax = plt.subplot(1, num_to_display, i + 1)\n ax.set_title('Sample #{}'.format(i))\n \n # Using the same display function, defined earlier\n show_keypoints(sample['image'], sample['keypoints'])\n", "0 (174, 144, 3) (68, 2)\n1 (219, 197, 3) (68, 2)\n2 (332, 414, 3) (68, 2)\n" ] ], [ [ "## Transforms\n\nNow, the images above are not of the same size, and neural networks often expect images that are standardized; a fixed size, with a normalized range for color ranges and coordinates, and (for PyTorch) converted from numpy lists and arrays to Tensors.\n\nTherefore, we will need to write some pre-processing code.\nLet's create four transforms:\n\n- ``Normalize``: to convert a color image to grayscale values with a range of [0,1] and normalize the keypoints to be in a range of about [-1, 1]\n- ``Rescale``: to rescale an image to a desired size.\n- ``RandomCrop``: to crop an image randomly.\n- ``ToTensor``: to convert numpy images to torch images.\n\n\nWe will write them as callable classes instead of simple functions so\nthat parameters of the transform need not be passed everytime it's\ncalled. For this, we just need to implement ``__call__`` method and \n(if we require parameters to be passed in), the ``__init__`` method. \nWe can then use a transform like this:\n\n tx = Transform(params)\n transformed_sample = tx(sample)\n\nObserve below how these transforms are generally applied to both the image and its keypoints.\n\n", "_____no_output_____" ] ], [ [ "import torch\nfrom torchvision import transforms, utils\n# tranforms\n\nclass Normalize(object):\n \"\"\"Convert a color image to grayscale and normalize the color range to [0,1].\"\"\" \n\n def __call__(self, sample):\n image, key_pts = sample['image'], sample['keypoints']\n \n image_copy = np.copy(image)\n key_pts_copy = np.copy(key_pts)\n\n # convert image to grayscale\n image_copy = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n \n # scale color range from [0, 255] to [0, 1]\n image_copy= image_copy/255.0\n \n # scale keypoints to be centered around 0 with a range of [-1, 1]\n # mean = 100, sqrt = 50, so, pts should be (pts - 100)/50\n key_pts_copy = (key_pts_copy - 100)/50.0\n\n\n return {'image': image_copy, 'keypoints': key_pts_copy}\n\n\nclass Rescale(object):\n \"\"\"Rescale the image in a sample to a given size.\n\n Args:\n output_size (tuple or int): Desired output size. If tuple, output is\n matched to output_size. If int, smaller of image edges is matched\n to output_size keeping aspect ratio the same.\n \"\"\"\n\n def __init__(self, output_size):\n assert isinstance(output_size, (int, tuple))\n self.output_size = output_size\n\n def __call__(self, sample):\n image, key_pts = sample['image'], sample['keypoints']\n\n h, w = image.shape[:2]\n if isinstance(self.output_size, int):\n if h > w:\n new_h, new_w = self.output_size * h / w, self.output_size\n else:\n new_h, new_w = self.output_size, self.output_size * w / h\n else:\n new_h, new_w = self.output_size\n\n new_h, new_w = int(new_h), int(new_w)\n\n img = cv2.resize(image, (new_w, new_h))\n \n # scale the pts, too\n key_pts = key_pts * [new_w / w, new_h / h]\n\n return {'image': img, 'keypoints': key_pts}\n\n\nclass RandomCrop(object):\n \"\"\"Crop randomly the image in a sample.\n\n Args:\n output_size (tuple or int): Desired output size. If int, square crop\n is made.\n \"\"\"\n\n def __init__(self, output_size):\n assert isinstance(output_size, (int, tuple))\n if isinstance(output_size, int):\n self.output_size = (output_size, output_size)\n else:\n assert len(output_size) == 2\n self.output_size = output_size\n\n def __call__(self, sample):\n image, key_pts = sample['image'], sample['keypoints']\n\n h, w = image.shape[:2]\n new_h, new_w = self.output_size\n\n top = np.random.randint(0, h - new_h)\n left = np.random.randint(0, w - new_w)\n\n image = image[top: top + new_h,\n left: left + new_w]\n\n key_pts = key_pts - [left, top]\n\n return {'image': image, 'keypoints': key_pts}\n\n\nclass ToTensor(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n image, key_pts = sample['image'], sample['keypoints']\n \n # if image has no grayscale color channel, add one\n if(len(image.shape) == 2):\n # add that third color dim\n image = image.reshape(image.shape[0], image.shape[1], 1)\n \n # swap color axis because\n # numpy image: H x W x C\n # torch image: C X H X W\n image = image.transpose((2, 0, 1))\n \n return {'image': torch.from_numpy(image),\n 'keypoints': torch.from_numpy(key_pts)}", "_____no_output_____" ] ], [ [ "## Test out the transforms\n\nLet's test these transforms out to make sure they behave as expected. As you look at each transform, note that, in this case, **order does matter**. For example, you cannot crop a image using a value smaller than the original image (and the orginal images vary in size!), but, if you first rescale the original image, you can then crop it to any size smaller than the rescaled size.", "_____no_output_____" ] ], [ [ "# test out some of these transforms\nrescale = Rescale(100)\ncrop = RandomCrop(50)\ncomposed = transforms.Compose([Rescale(250),\n RandomCrop(224)])\n\n# apply the transforms to a sample image\ntest_num = 500\nsample = face_dataset[test_num]\n\nfig = plt.figure()\nfor i, tx in enumerate([rescale, crop, composed]):\n transformed_sample = tx(sample)\n\n ax = plt.subplot(1, 3, i + 1)\n plt.tight_layout()\n ax.set_title(type(tx).__name__)\n show_keypoints(transformed_sample['image'], transformed_sample['keypoints'])\n\nplt.show()", "/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:31: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.\n" ] ], [ [ "## Create the transformed dataset\n\nApply the transforms in order to get grayscale images of the same shape. Verify that your transform works by printing out the shape of the resulting data (printing out a few examples should show you a consistent tensor size).", "_____no_output_____" ] ], [ [ "# define the data tranform\n# order matters! i.e. rescaling should come before a smaller crop\ndata_transform = transforms.Compose([Rescale(250),\n RandomCrop(224),\n Normalize(),\n ToTensor()])\n\n# create the transformed dataset\ntransformed_dataset = FacialKeypointsDataset(csv_file='/data/training_frames_keypoints.csv',\n root_dir='/data/training/',\n transform=data_transform)\n", "_____no_output_____" ], [ "# print some stats about the transformed data\nprint('Number of images: ', len(transformed_dataset))\n\n# make sure the sample tensors are the expected size\nfor i in range(5):\n sample = transformed_dataset[i]\n print(i, sample['image'].size(), sample['keypoints'].size())\n", "Number of images: 3462\n0 torch.Size([1, 224, 224]) torch.Size([68, 2])\n1 torch.Size([1, 224, 224]) torch.Size([68, 2])\n2 torch.Size([1, 224, 224]) torch.Size([68, 2])\n3 torch.Size([1, 224, 224]) torch.Size([68, 2])\n4 torch.Size([1, 224, 224]) torch.Size([68, 2])\n" ] ], [ [ "## Data Iteration and Batching\n\nRight now, we are iterating over this data using a ``for`` loop, but we are missing out on a lot of PyTorch's dataset capabilities, specifically the abilities to:\n\n- Batch the data\n- Shuffle the data\n- Load the data in parallel using ``multiprocessing`` workers.\n\n``torch.utils.data.DataLoader`` is an iterator which provides all these\nfeatures, and we'll see this in use in the *next* notebook, Notebook 2, when we load data in batches to train a neural network!\n\n---\n\n", "_____no_output_____" ], [ "## Ready to Train!\n\nNow that you've seen how to load and transform our data, you're ready to build a neural network to train on this data.\n\nIn the next notebook, you'll be tasked with creating a CNN for facial keypoint detection.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ] ]
4a543f4fd2e6ea0581a5ca109721693ff65b39b6
121,059
ipynb
Jupyter Notebook
notebook.ipynb
loftiskg/runaway
9577b7981299f647cbf9c477eb7b1a3898619ece
[ "MIT" ]
null
null
null
notebook.ipynb
loftiskg/runaway
9577b7981299f647cbf9c477eb7b1a3898619ece
[ "MIT" ]
null
null
null
notebook.ipynb
loftiskg/runaway
9577b7981299f647cbf9c477eb7b1a3898619ece
[ "MIT" ]
null
null
null
756.61875
92,769
0.765288
[ [ [ "%load_ext autoreload\n%autoreload 2\n\nfrom src.game import Game\nfrom src.agent import Random_Agent, QAgent\nfrom matplotlib import pyplot as plt\nimport numpy as np", "_____no_output_____" ] ], [ [ "# Training Notebook", "_____no_output_____" ], [ "## Train the agent using q-learning\n", "_____no_output_____" ] ], [ [ "env = Game(randomize_start_pos=False)\nagent = QAgent()\nagent.train(env, episodes=5000, epsilon=1, min_epsilon=0.001, print_every=500,epsilon_decay=.995)", "0 | 114.0\n500 | 139.41\n1000 | 154.66\n1500 | 346.75\n2000 | 653.35\n2500 | 628.95\n3000 | 666.19\n3500 | 1322.79\n4000 | 1294.81\n4500 | 1275.49\n" ] ], [ [ "Plot the rewards obtained over the course of training.", "_____no_output_____" ] ], [ [ "agent.plot_train_stats(path=None)\nplt.hlines(1250,xmin=0,xmax=5000, colors='gold')\nplt.annotate('Convergence',(0,1300))", "_____no_output_____" ] ], [ [ "The agent started to converge around 3000 episodes for this example. The time of convergence may vary when you run this multiple times, but convergence typically occurs around 2000-4000 episodes in most cases.", "_____no_output_____" ], [ "## Compare the performance of the Q agent versus a Random baseline", "_____no_output_____" ] ], [ [ "## Performance of Q agent\nq_agent_rewards = agent.performance(env)\nrandom_agent_rewards = np.mean([Random_Agent(5,4).performance(env) for i in range(100)])\n\nprint(f\"Average rewards for random agent: {random_agent_rewards}\\nRewards obtained by Q-agent: {q_agent_rewards}\")", "Average rewards for random agent: 129.9\nRewards obtained by Q-agent: 1999\n" ] ], [ [ "Our agent recieved the maximum score and beat just a randomly walking agent!", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
4a543f6e04a2775aaa4aab489d91e82c12753a61
21,880
ipynb
Jupyter Notebook
Chapter05/Exercise_5_12.ipynb
enakai00/rl_book_solutions
350ccd3fdb161853a2ef69a05632abe080fdd423
[ "Apache-2.0" ]
13
2019-05-06T13:36:32.000Z
2021-03-25T17:40:11.000Z
Chapter05/Exercise_5_12.ipynb
enakai00/rl_book_solutions
350ccd3fdb161853a2ef69a05632abe080fdd423
[ "Apache-2.0" ]
null
null
null
Chapter05/Exercise_5_12.ipynb
enakai00/rl_book_solutions
350ccd3fdb161853a2ef69a05632abe080fdd423
[ "Apache-2.0" ]
10
2019-08-22T06:19:14.000Z
2021-01-11T12:46:22.000Z
34.730159
248
0.206536
[ [ [ "<a href=\"https://colab.research.google.com/github/enakai00/rl_book_solutions/blob/master/Chapter05/Exercise_5_12.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# Exercise 5.12 : Solution", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom numpy import random\nimport copy", "_____no_output_____" ], [ "track_img1 = '''\n ##############\n # G\n # G\n # G\n # G\n# G\n# G\n# #######\n# #\n# #\n# #\n# #\n# #\n# #\n # #\n # #\n # #\n # #\n # #\n # #\n # #\n # #\n # # \n # #\n # #\n # #\n # #\n # #\n # #\n # #\n # #\n #SSSSSS#\n'''", "_____no_output_____" ], [ "track_img2 = '''\n #################\n ### G\n # G \n # G \n # G \n # G \n # G \n # G \n # G\n # ##\n # ###\n # #\n # ##\n # #\n # #\n # #\n # #\n # #\n # #\n # #\n # #\n # # \n # #\n # #\n # #\n # #\n # #\n # #\n# #\n# #\n#SSSSSSSSSSSSSSSSSSSSSSS#\n'''", "_____no_output_____" ], [ "def get_track(track_img):\n x_max = max(map(len, track_img.split('\\n')))\n track = []\n for line in track_img.split('\\n'):\n if line == '':\n continue \n line += ' ' * x_max\n track.append(list(line)[:x_max])\n\n return np.array(track)", "_____no_output_____" ], [ "class Car:\n def __init__(self, track):\n self.path = []\n self.track = track\n self._restart()\n\n def _restart(self):\n self.vx, self.vy = 0, 0\n self.y = len(self.track) - 1\n while True:\n self.x = random.randint(len(self.track[self.y]))\n if self.track[self.y][self.x] == 'S':\n break\n\n def get_state(self):\n return self.x, self.y, self.vx, self.vy\n\n def get_result(self):\n result = np.copy(self.track)\n for (x, y, vx, vy, ax, ay) in self.path:\n result[y][x] = '+'\n return result \n\n def _action(self, ax, ay):\n _vx = self.vx + ax\n _vy = self.vy + ay\n if _vx in range(5):\n self.vx = _vx\n if _vy in range(5):\n self.vy = _vy\n\n def move(self, ax, ay, noise):\n self.path.append((self.x, self.y, self.vx, self.vy, ax, ay))\n if noise and random.random() < 0.1:\n self._action(0, 0)\n else:\n self._action(ax, ay)\n\n for _ in range(self.vy):\n self.y -= 1\n if self.track[self.y][self.x] == 'G':\n return True\n if self.track[self.y][self.x] == '#':\n self._restart()\n\n for _ in range(self.vx):\n self.x += 1\n if self.track[self.y][self.x] == 'G':\n return True\n if self.track[self.y][self.x] == '#':\n self._restart()\n\n return False", "_____no_output_____" ], [ "def trial(car, policy, epsilon = 0.1, noise=True):\n for _ in range(10000):\n x, y, vx, vy = car.get_state()\n state = \"{:02},{:02}:{:02},{:02}\".format(x, y, vx, vy)\n if state not in policy.keys():\n policy[state] = (0, 0)\n\n ax, ay = policy[state]\n if random.random() < epsilon:\n ax, ay = random.randint(-1, 2, 2)\n \n finished = car.move(ax, ay, noise)\n if finished:\n break", "_____no_output_____" ], [ "def optimal_action(q, x, y, vx, vy):\n optimal = (0, 0)\n q_max = 0\n initial = True\n for ay in range(-1, 2):\n for ax in range(-1, 2):\n sa = \"{:02},{:02}:{:02},{:02}:{:02},{:02}\".format(x, y, vx, vy, ax, ay)\n if sa not in q.keys():\n q[sa] = -10**10\n if initial or q[sa] > q_max:\n q_max = q[sa]\n optimal = (ax, ay)\n initial = False\n return optimal\n \ndef run_sampling(track, num=100000):\n policy_t = {}\n policy_b = {}\n q = {}\n c = {}\n epsilon = 0.1\n\n for i in range(num):\n if i % 2000 == 0:\n print ('.', end='')\n car = Car(track)\n trial(car, policy_b, epsilon, noise=True)\n g = 0\n w = 1\n path = car.path\n path.reverse()\n for x, y, vx, vy, ax, ay in path:\n state = \"{:02},{:02}:{:02},{:02}\".format(x, y, vx, vy)\n sa = \"{:02},{:02}:{:02},{:02}:{:02},{:02}\".format(x, y, vx, vy, ax, ay)\n action = (ax, ay)\n\n g += -1 # Reward = -1 for each step\n if sa not in c.keys():\n c[sa] = 0\n c[sa] += w\n if sa not in q.keys():\n q[sa] = 0\n q[sa] += w*(g-q[sa])/c[sa]\n policy_t[state] = optimal_action(q, x, y, vx, vy)\n\n if policy_t[state] != action:\n break\n w = w / (1 - epsilon + epsilon/9)\n # b(a|s) = (1 - epsilon) + epsilon / 9\n # 1 - epsilon : chosen with the greedy policy\n # epsilon / 9 : chosen with the random policy\n \n policy_b = copy.copy(policy_t) # Update the behaivor policy\n\n return policy_t", "_____no_output_____" ], [ "track = get_track(track_img1)\npolicy_t = run_sampling(track, 200000)", "...................................................................................................." ], [ "for _ in range(3):\n car = Car(track)\n trial(car, policy_t, 0, noise=False)\n result = car.get_result()\n for line in result:\n print (''.join(line))\n print ()", " ##############\n # G\n # G\n # G\n # + G\n# G\n# + G\n# #######\n# +# \n# # \n# + # \n# # \n# # \n# + # \n # # \n # # \n # # \n # + # \n # # \n # # \n # # \n # + # \n # # \n # # \n # # \n # + # \n # # \n # # \n # + # \n # # \n # + # \n #SSS+SS# \n\n ##############\n # G\n # G\n # G\n # + G\n# G\n# + G\n# #######\n# +# \n# # \n# + # \n# # \n# # \n# + # \n # # \n # # \n # # \n # + # \n # # \n # # \n # # \n # + # \n # # \n # # \n # # \n # + # \n # # \n # # \n # + # \n # # \n # + # \n #SSSS+S# \n\n ##############\n # G\n # G\n # G\n # G\n# + G\n# G\n# +#######\n# # \n# # \n# + # \n# # \n# # \n# + # \n # # \n # # \n # # \n # + # \n # # \n # # \n # # \n # + # \n # # \n # # \n # # \n # + # \n # # \n # # \n # + # \n # # \n # + # \n #++SSSS# \n\n" ], [ "track = get_track(track_img2)\npolicy_t = run_sampling(track, 200000)", "...................................................................................................." ], [ "for _ in range(3):\n car = Car(track)\n trial(car, policy_t, 0, noise=False)\n result = car.get_result()\n for line in result:\n print (''.join(line))\n print ()", " ################# \n ### G \n # G \n # G \n # G \n # G \n # G \n # G \n # G \n # + ## \n # ### \n # # \n # +## \n # # \n # # \n # + # \n # # \n # # \n # # \n # + # \n # # \n # # \n # # \n # + # \n # # \n # # \n # + # \n # # \n# + # \n# + # \n#SSS++SSSSSSSSSSSSSSSSSS# \n\n ################# \n ### G \n # G \n # G \n # G \n # G \n # G \n # G \n # + G \n # ## \n # + ### \n # # \n # ## \n # +# \n # # \n # # \n # +# \n # # \n # # \n # # \n # +# \n # # \n # # \n # # \n # +# \n # # \n # # \n # +# \n# # \n# +# \n#SSSSSSSSSSSSSSSSSSSSSS+# \n\n ################# \n ### G \n # G \n # G \n # G \n # G \n # G \n # G \n # G \n # + ## \n # ### \n # # \n # +## \n # # \n # # \n # # \n # + # \n # # \n # # \n # # \n # + # \n # # \n # # \n # # \n # + # \n # # \n # # \n # + # \n# # \n# + # \n#SSSSSSSSSSSSSS+SSSSSSSS# \n\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]