repo_name
stringlengths
6
77
path
stringlengths
8
215
license
stringclasses
15 values
cells
list
types
list
GoogleCloudPlatform/bigquery-notebooks
notebooks/official/template_notebooks/visualizing_bigquery_public_data.ipynb
apache-2.0
[ "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# test", "Vizualizing BigQuery data in a Jupyter notebook\nBigQuery is a petabyte-scale analytics data warehouse that you can use to run SQL queries over vast amounts of data in near realtime.\nData visualization tools can help you make sense of your BigQuery data and help you analyze the data interactively. You can use visualization tools to help you identify trends, respond to them, and make predictions using your data. In this tutorial, you use the BigQuery Python client library and pandas in a Jupyter notebook to visualize data in the BigQuery natality sample table.\nUsing Jupyter magics to query BigQuery data\nThe BigQuery Python client library provides a magic command that allows you to run queries with minimal code.\nThe BigQuery client library provides a cell magic, %%bigquery. The %%bigquery magic runs a SQL query and returns the results as a pandas DataFrame. The following cell executes a query of the BigQuery natality public dataset and returns the total births by year.", "%%bigquery\nSELECT\n source_year AS year,\n COUNT(is_male) AS birth_count\nFROM `bigquery-public-data.samples.natality`\nGROUP BY year\nORDER BY year DESC\nLIMIT 15", "The following command to runs the same query, but this time the results are saved to a variable. The variable name, total_births, is given as an argument to the %%bigquery. The results can then be used for further analysis and visualization.", "%%bigquery total_births\nSELECT\n source_year AS year,\n COUNT(is_male) AS birth_count\nFROM `bigquery-public-data.samples.natality`\nGROUP BY year\nORDER BY year DESC\nLIMIT 15", "The next cell uses the pandas DataFrame.plot method to visualize the query results as a bar chart. See the pandas documentation to learn more about data visualization with pandas.", "total_births.plot(kind=\"bar\", x=\"year\", y=\"birth_count\");", "Run the following query to retrieve the number of births by weekday. Because the wday (weekday) field allows null values, the query excludes records where wday is null.", "%%bigquery births_by_weekday\nSELECT\n wday,\n SUM(CASE WHEN is_male THEN 1 ELSE 0 END) AS male_births,\n SUM(CASE WHEN is_male THEN 0 ELSE 1 END) AS female_births\nFROM `bigquery-public-data.samples.natality`\nWHERE wday IS NOT NULL\nGROUP BY wday\nORDER BY wday ASC", "Visualize the query results using a line chart.", "births_by_weekday.plot(x=\"wday\");", "Using Python to query BigQuery data\nMagic commands allow you to use minimal syntax to interact with BigQuery. Behind the scenes, %%bigquery uses the BigQuery Python client library to run the given query, convert the results to a pandas Dataframe, optionally save the results to a variable, and finally display the results. Using the BigQuery Python client library directly instead of through magic commands gives you more control over your queries and allows for more complex configurations. The library's integrations with pandas enable you to combine the power of declarative SQL with imperative code (Python) to perform interesting data analysis, visualization, and transformation tasks.\nTo use the BigQuery Python client library, start by importing the library and initializing a client. The BigQuery client is used to send and receive messages from the BigQuery API.", "from google.cloud import bigquery\n\nclient = bigquery.Client()", "Use the Client.query method to run a query. Execute the following cell to run a query to retrieve the annual count of plural births by plurality (2 for twins, 3 for triplets, etc.).", "sql = \"\"\"\nSELECT\n plurality,\n COUNT(1) AS count,\n year\nFROM\n `bigquery-public-data.samples.natality`\nWHERE\n NOT IS_NAN(plurality) AND plurality > 1\nGROUP BY\n plurality, year\nORDER BY\n count DESC\n\"\"\"\ndf = client.query(sql).to_dataframe()\ndf.head()", "To chart the query results in your DataFrame, run the following cell to pivot the data and create a stacked bar chart of the count of plural births over time.", "pivot_table = df.pivot(index=\"year\", columns=\"plurality\", values=\"count\")\npivot_table.plot(kind=\"bar\", stacked=True, figsize=(15, 7));", "Run the following query to retrieve the count of births by the number of gestation weeks.", "sql = \"\"\"\nSELECT\n gestation_weeks,\n COUNT(1) AS count\nFROM\n `bigquery-public-data.samples.natality`\nWHERE\n NOT IS_NAN(gestation_weeks) AND gestation_weeks <> 99\nGROUP BY\n gestation_weeks\nORDER BY\n gestation_weeks\n\"\"\"\ndf = client.query(sql).to_dataframe()", "Finally, chart the query results in your DataFrame.", "ax = df.plot(kind=\"bar\", x=\"gestation_weeks\", y=\"count\", figsize=(15, 7))\nax.set_title(\"Count of Births by Gestation Weeks\")\nax.set_xlabel(\"Gestation Weeks\")\nax.set_ylabel(\"Count\");", "What's Next\n\n\nLearn more about writing queries for BigQuery — Querying Data in the BigQuery documentation explains how to run queries, create user-defined functions (UDFs), and more.\n\n\nExplore BigQuery syntax — The preferred dialect for SQL queries in BigQuery is standard SQL. Standard SQL syntax is described in the SQL Reference. BigQuery's legacy SQL-like syntax is described in the Query Reference (legacy SQL)." ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
josealber84/deep-learning
weight-initialization/weight_initialization.ipynb
mit
[ "Weight Initialization\nIn this lesson, you'll learn how to find good initial weights for a neural network. Having good initial weights can place the neural network close to the optimal solution. This allows the neural network to come to the best solution quicker. \nTesting Weights\nDataset\nTo see how different weights perform, we'll test on the same dataset and neural network. Let's go over the dataset and neural network.\nWe'll be using the MNIST dataset to demonstrate the different initial weights. As a reminder, the MNIST dataset contains images of handwritten numbers, 0-9, with normalized input (0.0 - 1.0). Run the cell below to download and load the MNIST dataset.", "%matplotlib inline\n\nimport tensorflow as tf\nimport helper\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nprint('Getting MNIST Dataset...')\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\nprint('Data Extracted.')", "Neural Network\n<img style=\"float: left\" src=\"images/neural_network.png\"/>\nFor the neural network, we'll test on a 3 layer neural network with ReLU activations and an Adam optimizer. The lessons you learn apply to other neural networks, including different activations and optimizers.", "# Save the shapes of weights for each layer\nlayer_1_weight_shape = (mnist.train.images.shape[1], 256)\nlayer_2_weight_shape = (256, 128)\nlayer_3_weight_shape = (128, mnist.train.labels.shape[1])", "Initialize Weights\nLet's start looking at some initial weights.\nAll Zeros or Ones\nIf you follow the principle of Occam's razor, you might think setting all the weights to 0 or 1 would be the best solution. This is not the case.\nWith every weight the same, all the neurons at each layer are producing the same output. This makes it hard to decide which weights to adjust.\nLet's compare the loss with all ones and all zero weights using helper.compare_init_weights. This function will run two different initial weights on the neural network above for 2 epochs. It will plot the loss for the first 100 batches and print out stats after the 2 epochs (~860 batches). We plot the first 100 batches to better judge which weights performed better at the start.\nRun the cell below to see the difference between weights of all zeros against all ones.", "all_zero_weights = [\n tf.Variable(tf.zeros(layer_1_weight_shape)),\n tf.Variable(tf.zeros(layer_2_weight_shape)),\n tf.Variable(tf.zeros(layer_3_weight_shape))\n]\n\nall_one_weights = [\n tf.Variable(tf.ones(layer_1_weight_shape)),\n tf.Variable(tf.ones(layer_2_weight_shape)),\n tf.Variable(tf.ones(layer_3_weight_shape))\n]\n\nhelper.compare_init_weights(\n mnist,\n 'All Zeros vs All Ones',\n [\n (all_zero_weights, 'All Zeros'),\n (all_one_weights, 'All Ones')])", "As you can see the accuracy is close to guessing for both zeros and ones, around 10%.\nThe neural network is having a hard time determining which weights need to be changed, since the neurons have the same output for each layer. To avoid neurons with the same output, let's use unique weights. We can also randomly select these weights to avoid being stuck in a local minimum for each run.\nA good solution for getting these random weights is to sample from a uniform distribution.\nUniform Distribution\nA [uniform distribution](https://en.wikipedia.org/wiki/Uniform_distribution_(continuous%29) has the equal probability of picking any number from a set of numbers. We'll be picking from a continous distribution, so the chance of picking the same number is low. We'll use TensorFlow's tf.random_uniform function to pick random numbers from a uniform distribution.\n\ntf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None)\nOutputs random values from a uniform distribution.\nThe generated values follow a uniform distribution in the range [minval, maxval). The lower bound minval is included in the range, while the upper bound maxval is excluded.\n\nshape: A 1-D integer Tensor or Python array. The shape of the output tensor.\nminval: A 0-D Tensor or Python value of type dtype. The lower bound on the range of random values to generate. Defaults to 0.\nmaxval: A 0-D Tensor or Python value of type dtype. The upper bound on the range of random values to generate. Defaults to 1 if dtype is floating point.\ndtype: The type of the output: float32, float64, int32, or int64.\nseed: A Python integer. Used to create a random seed for the distribution. See tf.set_random_seed for behavior.\nname: A name for the operation (optional).\n\n\nWe can visualize the uniform distribution by using a histogram. Let's map the values from tf.random_uniform([1000], -3, 3) to a histogram using the helper.hist_dist function. This will be 1000 random float values from -3 to 3, excluding the value 3.", "helper.hist_dist('Random Uniform (minval=-3, maxval=3)', tf.random_uniform([1000], -3, 3))", "The histogram used 500 buckets for the 1000 values. Since the chance for any single bucket is the same, there should be around 2 values for each bucket. That's exactly what we see with the histogram. Some buckets have more and some have less, but they trend around 2.\nNow that you understand the tf.random_uniform function, let's apply it to some initial weights.\nBaseline\nLet's see how well the neural network trains using the default values for tf.random_uniform, where minval=0.0 and maxval=1.0.", "# Default for tf.random_uniform is minval=0 and maxval=1\nbasline_weights = [\n tf.Variable(tf.random_uniform(layer_1_weight_shape)),\n tf.Variable(tf.random_uniform(layer_2_weight_shape)),\n tf.Variable(tf.random_uniform(layer_3_weight_shape))\n]\n\nhelper.compare_init_weights(\n mnist,\n 'Baseline',\n [(basline_weights, 'tf.random_uniform [0, 1)')])", "The loss graph is showing the neural network is learning, which it didn't with all zeros or all ones. We're headed in the right direction.\nGeneral rule for setting weights\nThe general rule for setting the weights in a neural network is to be close to zero without being too small. A good pracitce is to start your weights in the range of $[-y, y]$ where\n$y=1/\\sqrt{n}$ ($n$ is the number of inputs to a given neuron).\nLet's see if this holds true, let's first center our range over zero. This will give us the range [-1, 1).", "uniform_neg1to1_weights = [\n tf.Variable(tf.random_uniform(layer_1_weight_shape, -1, 1)),\n tf.Variable(tf.random_uniform(layer_2_weight_shape, -1, 1)),\n tf.Variable(tf.random_uniform(layer_3_weight_shape, -1, 1))\n]\n\nhelper.compare_init_weights(\n mnist,\n '[0, 1) vs [-1, 1)',\n [\n (basline_weights, 'tf.random_uniform [0, 1)'),\n (uniform_neg1to1_weights, 'tf.random_uniform [-1, 1)')])", "We're going in the right direction, the accuracy and loss is better with [-1, 1). We still want smaller weights. How far can we go before it's too small?\nToo small\nLet's compare [-0.1, 0.1), [-0.01, 0.01), and [-0.001, 0.001) to see how small is too small. We'll also set plot_n_batches=None to show all the batches in the plot.", "uniform_neg01to01_weights = [\n tf.Variable(tf.random_uniform(layer_1_weight_shape, -0.1, 0.1)),\n tf.Variable(tf.random_uniform(layer_2_weight_shape, -0.1, 0.1)),\n tf.Variable(tf.random_uniform(layer_3_weight_shape, -0.1, 0.1))\n]\n\nuniform_neg001to001_weights = [\n tf.Variable(tf.random_uniform(layer_1_weight_shape, -0.01, 0.01)),\n tf.Variable(tf.random_uniform(layer_2_weight_shape, -0.01, 0.01)),\n tf.Variable(tf.random_uniform(layer_3_weight_shape, -0.01, 0.01))\n]\n\nuniform_neg0001to0001_weights = [\n tf.Variable(tf.random_uniform(layer_1_weight_shape, -0.001, 0.001)),\n tf.Variable(tf.random_uniform(layer_2_weight_shape, -0.001, 0.001)),\n tf.Variable(tf.random_uniform(layer_3_weight_shape, -0.001, 0.001))\n]\n\nhelper.compare_init_weights(\n mnist,\n '[-1, 1) vs [-0.1, 0.1) vs [-0.01, 0.01) vs [-0.001, 0.001)',\n [\n (uniform_neg1to1_weights, '[-1, 1)'),\n (uniform_neg01to01_weights, '[-0.1, 0.1)'),\n (uniform_neg001to001_weights, '[-0.01, 0.01)'),\n (uniform_neg0001to0001_weights, '[-0.001, 0.001)')],\n plot_n_batches=None)", "Looks like anything [-0.01, 0.01) or smaller is too small. Let's compare this to our typical rule of using the range $y=1/\\sqrt{n}$.", "import numpy as np\n\ngeneral_rule_weights = [\n tf.Variable(tf.random_uniform(layer_1_weight_shape, -1/np.sqrt(layer_1_weight_shape[0]), 1/np.sqrt(layer_1_weight_shape[0]))),\n tf.Variable(tf.random_uniform(layer_2_weight_shape, -1/np.sqrt(layer_2_weight_shape[0]), 1/np.sqrt(layer_2_weight_shape[0]))),\n tf.Variable(tf.random_uniform(layer_3_weight_shape, -1/np.sqrt(layer_3_weight_shape[0]), 1/np.sqrt(layer_3_weight_shape[0])))\n]\n\nhelper.compare_init_weights(\n mnist,\n '[-0.1, 0.1) vs General Rule',\n [\n (uniform_neg01to01_weights, '[-0.1, 0.1)'),\n (general_rule_weights, 'General Rule')],\n plot_n_batches=None)", "The range we found and $y=1/\\sqrt{n}$ are really close.\nSince the uniform distribution has the same chance to pick anything in the range, what if we used a distribution that had a higher chance of picking numbers closer to 0. Let's look at the normal distribution.\nNormal Distribution\nUnlike the uniform distribution, the normal distribution has a higher likelihood of picking number close to it's mean. To visualize it, let's plot values from TensorFlow's tf.random_normal function to a histogram.\n\ntf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)\nOutputs random values from a normal distribution.\n\nshape: A 1-D integer Tensor or Python array. The shape of the output tensor.\nmean: A 0-D Tensor or Python value of type dtype. The mean of the normal distribution.\nstddev: A 0-D Tensor or Python value of type dtype. The standard deviation of the normal distribution.\ndtype: The type of the output.\nseed: A Python integer. Used to create a random seed for the distribution. See tf.set_random_seed for behavior.\nname: A name for the operation (optional).", "helper.hist_dist('Random Normal (mean=0.0, stddev=1.0)', tf.random_normal([1000]))", "Let's compare the normal distribution against the previous uniform distribution.", "normal_01_weights = [\n tf.Variable(tf.random_normal(layer_1_weight_shape, stddev=0.1)),\n tf.Variable(tf.random_normal(layer_2_weight_shape, stddev=0.1)),\n tf.Variable(tf.random_normal(layer_3_weight_shape, stddev=0.1))\n]\n\nhelper.compare_init_weights(\n mnist,\n 'Uniform [-0.1, 0.1) vs Normal stddev 0.1',\n [\n (uniform_neg01to01_weights, 'Uniform [-0.1, 0.1)'),\n (normal_01_weights, 'Normal stddev 0.1')])", "The normal distribution gave a slight increasse in accuracy and loss. Let's move closer to 0 and drop picked numbers that are x number of standard deviations away. This distribution is called Truncated Normal Distribution.\nTruncated Normal Distribution\n\ntf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)\nOutputs random values from a truncated normal distribution.\nThe generated values follow a normal distribution with specified mean and standard deviation, except that values whose magnitude is more than 2 standard deviations from the mean are dropped and re-picked.\n\nshape: A 1-D integer Tensor or Python array. The shape of the output tensor.\nmean: A 0-D Tensor or Python value of type dtype. The mean of the truncated normal distribution.\nstddev: A 0-D Tensor or Python value of type dtype. The standard deviation of the truncated normal distribution.\ndtype: The type of the output.\nseed: A Python integer. Used to create a random seed for the distribution. See tf.set_random_seed for behavior.\nname: A name for the operation (optional).", "helper.hist_dist('Truncated Normal (mean=0.0, stddev=1.0)', tf.truncated_normal([1000]))", "Again, let's compare the previous results with the previous distribution.", "trunc_normal_01_weights = [\n tf.Variable(tf.truncated_normal(layer_1_weight_shape, stddev=0.1)),\n tf.Variable(tf.truncated_normal(layer_2_weight_shape, stddev=0.1)),\n tf.Variable(tf.truncated_normal(layer_3_weight_shape, stddev=0.1))\n]\n\nhelper.compare_init_weights(\n mnist,\n 'Normal vs Truncated Normal',\n [\n (normal_01_weights, 'Normal'),\n (trunc_normal_01_weights, 'Truncated Normal')])", "There's no difference between the two, but that's because the neural network we're using is too small. A larger neural network will pick more points on the normal distribution, increasing the likelihood it's choices are larger than 2 standard deviations.\nWe've come a long way from the first set of weights we tested. Let's see the difference between the weights we used then and now.", "helper.compare_init_weights(\n mnist,\n 'Baseline vs Truncated Normal',\n [\n (basline_weights, 'Baseline'),\n (trunc_normal_01_weights, 'Truncated Normal')])", "That's a huge difference. You can barely see the truncated normal line. However, this is not the end your learning path. We've provided more resources for initializing weights in the classroom!" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
sraejones/phys202-2015-work
days/day12/Integration.ipynb
mit
[ "Numerical Integration\nLearning Objectives: Learn how to numerically integrate 1d and 2d functions that are represented as Python functions or numerical arrays of data using scipy.integrate.\nThis lesson was orginally developed by Jennifer Klay under the terms of the MIT license. The original version is in this repo (https://github.com/Computing4Physics/C4P). Her materials was in turn based on content from the Computational Physics book by Mark Newman at University of Michigan, materials developed by Matt Moelter and Jodi Christiansen for PHYS 202 at Cal Poly, as well as the SciPy tutorials.\nImports", "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np", "Introduction\nWe often calculate integrals in physics (electromagnetism, thermodynamics, quantum mechanics, etc.). In calculus, you learned how to evaluate integrals analytically. Some functions are too difficult to integrate analytically and for these we need to use the computer to integrate numerically. A numerical integral goes back to the basic principles of calculus. Given a function $f(x)$, we need to find the area under the curve between two limits, $a$ and $b$:\n$$\nI(a,b) = \\int_a^b f(x) dx\n$$\nThere is no known way to calculate such an area exactly in all cases on a computer, but we can do it approximately by dividing up the area into rectangular slices and adding them all together. Unfortunately, this is a poor approximation, since the rectangles under and overshoot the function:\n<img src=\"rectangles.png\" width=400>\n\nTrapezoidal Rule\nA better approach, which involves very little extra work, is to divide the area into trapezoids rather than rectangles. The area under the trapezoids is a considerably better approximation to the area under the curve, and this approach, though simple, often gives perfectly adequate results.\n<img src=\"trapz.png\" width=420>\nWe can improve the approximation by making the size of the trapezoids smaller. Suppose we divide the interval from $a$ to $b$ into $N$ slices or steps, so that each slice has width $h = (b − a)/N$ . Then the right-hand side of the $k$ th slice falls at $a+kh$, and the left-hand side falls at $a+kh−h$ = $a+(k−1)h$ . Thus the area of the trapezoid for this slice is\n$$\nA_k = \\tfrac{1}{2}h[ f(a+(k−1)h)+ f(a+kh) ]\n$$\nThis is the trapezoidal rule. It gives us a trapezoidal approximation to the area under one slice of our function.\nNow our approximation for the area under the whole curve is the sum of the areas of the trapezoids for all $N$ slices\n$$\nI(a,b) \\simeq \\sum\\limits_{k=1}^N A_k = \\tfrac{1}{2}h \\sum\\limits_{k=1}^N [ f(a+(k−1)h)+ f(a+kh) ] = h \\left[ \\tfrac{1}{2}f(a) + \\tfrac{1}{2}f(b) + \\sum\\limits_{k=1}^{N-1} f(a+kh)\\right]\n$$\nNote the structure of the formula: the quantity inside the square brackets is a sum over values of $f(x)$ measured at equally spaced points in the integration domain, and we take a half of the values at the start and end points but one times the value at all the interior points.\nApplying the Trapezoidal rule\nUse the trapezoidal rule to calculate the integral of $x^4 − 2x + 1$ from $x$ = 0 to $x$ = 2.\nThis is an integral we can do by hand, so we can check our work. To define the function, let's use a lambda expression (you learned about these in the advanced python section of CodeCademy). It's basically just a way of defining a function of some variables in one line. For this case, it is just a function of x:", "func = lambda x: x**4 - 2*x + 1\n\nN = 10\na = 0.0\nb = 2.0\nh = (b-a)/N\n\nk = np.arange(1,N)\nI = h*(0.5*func(a) + 0.5*func(b) + func(a+k*h).sum())\n\nprint(I)", "The correct answer is\n$$\nI(0,2) = \\int_0^2 (x^4-2x+1)dx = \\left[\\tfrac{1}{5}x^5-x^2+x\\right]_0^2 = 4.4\n$$\nSo our result is off by about 2%.\nSimpson's Rule\nThe trapezoidal rule estimates the area under a curve by approximating the curve with straight-line segments. We can often get a better result if we approximate the function instead with curves of some kind. Simpson's rule uses quadratic curves. In order to specify a quadratic completely one needs three points, not just two as with a straight line. So in this method we take a pair of adjacent slices and fit a quadratic through the three points that mark the boundaries of those slices. \nGiven a function $f(x)$ and spacing between adjacent points $h$, if we fit a quadratic curve $ax^2 + bx + c$ through the points $x$ = $-h$, 0, $+h$, we get\n$$\nf(-h) = ah^2 - bh + c, \\hspace{1cm} f(0) = c, \\hspace{1cm} f(h) = ah^2 +bh +c\n$$\nSolving for $a$, $b$, and $c$ gives:\n$$\na = \\frac{1}{h^2}\\left[\\tfrac{1}{2}f(-h) - f(0) + \\tfrac{1}{2}f(h)\\right], \\hspace{1cm} b = \\frac{1}{2h}\\left[f(h)-f(-h)\\right], \\hspace{1cm} c = f(0)\n$$\nand the area under the curve of $f(x)$ from $-h$ to $+h$ is given approximately by the area under the quadratic:\n$$\nI(-h,h) \\simeq \\int_{-h}^h (ax^2+bx+c)dx = \\tfrac{2}{3}ah^3 + 2ch = \\tfrac{1}{3}h[f(-h)+4f(0)+f(h)]\n$$\nThis is Simpson’s rule. It gives us an approximation to the area under two adjacent slices of our function. Note that the final formula for the area involves only $h$ and the value of the function at evenly spaced points, just as with the trapezoidal rule. So to use Simpson’s rule we don’t actually have to worry about the details of fitting a quadratic—we just plug numbers into this formula and it gives us an answer. This makes Simpson’s rule almost as simple to use as the trapezoidal rule, and yet Simpson’s rule often gives much more accurate answers.\nApplying Simpson’s rule involves dividing the domain of integration into many slices and using the rule to separately estimate the area under successive pairs of slices, then adding the estimates for all pairs to get the final answer.\nIf we are integrating from $x = a$ to $x = b$ in slices of width $h$ then Simpson’s rule gives the area under the $k$ th pair, approximately, as\n$$\nA_k = \\tfrac{1}{3}h[f(a+(2k-2)h)+4f(a+(2k-1)h) + f(a+2kh)]\n$$\nWith $N$ slices in total, there are $N/2$ pairs of slices, and the approximate value of the entire integral is given by the sum\n$$\nI(a,b) \\simeq \\sum\\limits_{k=1}^{N/2}A_k = \\tfrac{1}{3}h\\left[f(a)+f(b)+4\\sum\\limits_{k=1}^{N/2}f(a+(2k-1)h)+2\\sum\\limits_{k=1}^{N/2-1}f(a+2kh)\\right]\n$$\nNote that the total number of slices must be even for Simpson's rule to work.\nApplying Simpson's rule\nNow let's code Simpson's rule to compute the integral of the same function from before, $f(x) = x^4 - 2x + 1$ from 0 to 2.", "N = 10\na = 0.0\nb = 2.0\nh = (b-a)/N\n\nk1 = np.arange(1,N/2+1)\nk2 = np.arange(1,N/2)\nI = (1./3.)*h*(func(a) + func(b) + 4.*func(a+(2*k1-1)*h).sum() + 2.*func(a+2*k2*h).sum())\n \nprint(I)", "Adaptive methods and higher order approximations\nIn some cases, particularly for integrands that are rapidly varying, a very large number of steps may be needed to achieve the desired accuracy, which means the calculation can become slow. \nSo how do we choose the number $N$ of steps for our integrals? In our example calculations we just chose round numbers and looked to see if the results seemed reasonable. A more common situation is that we want to calculate the value of an integral to a given accuracy, such as four decimal places, and we would like to know how many steps will be needed. So long as the desired accuracy does not exceed the fundamental limit set by the machine precision of our computer— the rounding error that limits all calculations—then it should always be possible to meet our goal by using a large enough number of steps. At the same time, we want to avoid using more steps than are necessary, since more steps take more time and our calculation will be slower. \nIdeally we would like an $N$ that gives us the accuracy we want and no more. A simple way to achieve this is to start with a small value of $N$ and repeatedly double it until we achieve the accuracy we want. This method is an example of an adaptive integration method, one that changes its own parameters to get a desired answer.\nThe trapezoidal rule is based on approximating an integrand $f(x)$ with straight-line segments, while Simpson’s rule uses quadratics. We can create higher-order (and hence potentially more accurate) rules by using higher-order polynomials, fitting $f(x)$ with cubics, quartics, and so forth. The general form of the trapezoidal and Simpson rules is\n$$\n\\int_a^b f(x)dx \\simeq \\sum\\limits_{k=1}^{N}w_kf(x_k)\n$$\nwhere the $x_k$ are the positions of the sample points at which we calculate the integrand and the $w_k$ are some set of weights. In the trapezoidal rule, the first and last weights are $\\tfrac{1}{2}$ and the others are all 1, while in Simpson’s rule the weights are $\\tfrac{1}{3}$ for the first and last slices and alternate between $\\tfrac{4}{3}$ and $\\tfrac{2}{3}$ for the other slices. For higher-order rules the basic form is the same: after fitting to the appropriate polynomial and integrating we end up with a set of weights that multiply the values $f(x_k)$ of the integrand at evenly spaced sample points. \nNotice that the trapezoidal rule is exact if the function being integrated is actually a straight line, because then the straight-line approximation isn’t an approximation at all. Similarly, Simpson’s rule is exact if the function being integrated is a quadratic, and so on for higher order polynomials.\nThere are other more advanced schemes for calculating integrals that can achieve high accuracy while still arriving at an answer quickly. These typically combine the higher order polynomial approximations with adaptive methods for choosing the number of slices, in some cases allowing their sizes to vary over different regions of the integrand. \nOne such method, called Gaussian Quadrature - after its inventor, Carl Friedrich Gauss, uses Legendre polynomials to choose the $x_k$ and $w_k$ such that we can obtain an integration rule accurate to the highest possible order of $2N−1$. It is beyond the scope of this course to derive the Gaussian quadrature method, but you can learn more about it by searching the literature. \nNow that we understand the basics of numerical integration and have even coded our own trapezoidal and Simpson's rules, we can feel justified in using scipy's built-in library of numerical integrators that build on these basic ideas, without coding them ourselves.\nscipy.integrate\nIt is time to look at scipy's built-in functions for integrating functions numerically. Start by importing the library.", "import scipy.integrate as integrate\n\nintegrate?", "An overview of the module is provided by the help command, but it produces a lot of output. Here's a quick summary:\nMethods for Integrating Functions given function object.\nquad -- General purpose integration.\ndblquad -- General purpose double integration.\ntplquad -- General purpose triple integration.\nfixed_quad -- Integrate func(x) using Gaussian quadrature of order n.\nquadrature -- Integrate with given tolerance using Gaussian quadrature.\nromberg -- Integrate func using Romberg integration.\n\nMethods for Integrating Functions given fixed samples.\ntrapz -- Use trapezoidal rule to compute integral from samples.\ncumtrapz -- Use trapezoidal rule to cumulatively compute integral.\nsimps -- Use Simpson's rule to compute integral from samples.\nromb -- Use Romberg Integration to compute integral from (2**k + 1) evenly-spaced samples.\n\nSee the <code>special</code> module's orthogonal polynomials (<code>scipy.special</code>) for Gaussian quadrature roots and weights for other weighting factors and regions.\nInterface to numerical integrators of ODE systems.\nodeint -- General integration of ordinary differential equations.\node -- Integrate ODE using VODE and ZVODE routines.\n\nGeneral integration (quad)\nThe scipy function quad is provided to integrate a function of one variable between two points. The points can be $\\pm\\infty$ ($\\pm$ np.infty) to indicate infinite limits. For example, suppose you wish to integrate the following: \n$$\nI = \\int_0^{2\\pi} e^{-x}\\sin(x)dx\n$$\nThis could be computed using quad as:", "fun = lambda x : np.exp(-x)*np.sin(x) \n\nresult,error = integrate.quad(fun, 0, 2*np.pi) \n\nprint(result,error)", "The first argument to quad is a “callable” Python object (i.e a function, method, or class instance). Notice that we used a lambda function in this case as the argument. The next two arguments are the limits of integration. The return value is a tuple, with the first element holding the estimated value of the integral and the second element holding an upper bound on the error.\nThe analytic solution to the integral is \n$$\n\\int_0^{2\\pi} e^{-x} \\sin(x) dx = \\frac{1}{2} - e^{-2\\pi} \\simeq \\textrm{0.499066}\n$$\nso that is pretty good.\nHere it is again, integrated from 0 to infinity:", "I = integrate.quad(fun, 0, np.infty)\n\nprint(I)", "In this case the analytic solution is exactly 1/2, so again pretty good.\nWe can calculate the error in the result by looking at the difference between the exact result and the numerical value from quad with", "print(abs(I[0]-0.5))", "In this case, the numerically-computed integral is within $10^{-16}$ of the exact result — well below the reported error bound.\nIntegrating array data\nWhen you want to compute the integral for an array of data (such as our thermistor resistance-temperature data from the Interpolation lesson), you don't have the luxury of varying your choice of $N$, the number of slices (unless you create an interpolated approximation to your data).\nThere are three functions for computing integrals given only samples: trapz , simps, and romb. The trapezoidal rule approximates the function as a straight line between adjacent points while Simpson’s rule approximates the function between three adjacent points as a parabola, as we have already seen. The first two functions can also handle non-equally-spaced samples (something we did not code ourselves) which is a useful extension to these integration rules.\nIf the samples are equally-spaced and the number of samples available is $2^k+1$ for some integer $k$, then Romberg integration can be used to obtain high-precision estimates of the integral using the available samples. Romberg integration is an adaptive method that uses the trapezoid rule at step-sizes related by a power of two and then performs something called Richardson extrapolation on these estimates to approximate the integral with a higher-degree of accuracy. (A different interface to Romberg integration useful when the function can be provided is also available as romberg).\nApplying simps to array data\nHere is an example of using simps to compute the integral for some discrete data:", "x = np.arange(0, 20, 2)\ny = np.array([0, 3, 5, 2, 8, 9, 0, -3, 4, 9], dtype = float)\nplt.plot(x,y)\nplt.xlabel('x')\nplt.ylabel('y')\n#Show the integration area as a filled region\nplt.fill_between(x, y, y2=0,color='red',hatch='//',alpha=0.2);\n\nI = integrate.simps(y,x) \nprint(I)", "Multiple Integrals\nMultiple integration can be handled using repeated calls to quad. The mechanics of this for double and triple integration have been wrapped up into the functions dblquad and tplquad. The function dblquad performs double integration. Use the help function to be sure that you define the arguments in the correct order. The limits on all inner integrals are actually functions (which can be constant).\nDouble integrals using dblquad\nSuppose we want to integrate $f(x,y)=y\\sin(x)+x\\cos(y)$ over $\\pi \\le x \\le 2\\pi$ and $0 \\le y \\le \\pi$:\n$$\\int_{x=\\pi}^{2\\pi}\\int_{y=0}^{\\pi} y \\sin(x) + x \\cos(y) dxdy$$\nTo use dblquad we have to provide callable functions for the range of the x-variable. Although here they are constants, the use of functions for the limits enables freedom to integrate over non-constant limits. In this case we create trivial lambda functions that return the constants. Note the order of the arguments in the integrand. If you put them in the wrong order you will get the wrong answer.", "from scipy.integrate import dblquad\n\n#NOTE: the order of arguments matters - inner to outer\nintegrand = lambda x,y: y * np.sin(x) + x * np.cos(y)\n\nymin = 0\nymax = np.pi\n\n#The callable functions for the x limits are just constants in this case:\nxmin = lambda y : np.pi\nxmax = lambda y : 2*np.pi\n\n#See the help for correct order of limits\nI, err = dblquad(integrand, ymin, ymax, xmin, xmax)\nprint(I, err)\n\ndblquad?", "Triple integrals using tplquad\nWe can also numerically evaluate a triple integral:\n$$ \\int_{x=0}^{\\pi}\\int_{y=0}^{1}\\int_{z=-1}^{1} y\\sin(x)+z\\cos(x) dxdydz$$", "from scipy.integrate import tplquad\n\n#AGAIN: the order of arguments matters - inner to outer\nintegrand = lambda x,y,z: y * np.sin(x) + z * np.cos(x)\n\nzmin = -1\nzmax = 1\n\nymin = lambda z: 0\nymax = lambda z: 1\n\n#Note the order of these arguments:\nxmin = lambda y,z: 0\nxmax = lambda y,z: np.pi\n\n#Here the order of limits is outer to inner\nI, err = tplquad(integrand, zmin, zmax, ymin, ymax, xmin, xmax)\nprint(I, err)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
martinjrobins/hobo
examples/stats/custom-prior.ipynb
bsd-3-clause
[ "Writing a custom LogPrior\nThis example shows you how to write a custom LogPrior class to use in your inference problems.\nMost priors in Pints are defined over just 1 parameter, and then combined into a multivariate prior using the ComposedLogPrior class.\nBut sometimes you might want to define a prior over multiple variables at once. In such a case, it may make sense to create a custom LogPrior class.\nIn this example, we'll implement a uniform 2d logprior that defines a circle in the parameter space such that points within the circle have probability c = 1/A and points outside it have probability 0.\nBefore we begin, let's define a toy problem, like in the basic MCMC example:", "import pints\nimport pints.toy\nimport pints.plot\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Load a forward model\nmodel = pints.toy.LogisticModel()\n\n# Create some toy data\nreal_parameters = np.array([1, 500])\ntimes = np.linspace(0, 1000, 1000)\norg_values = model.simulate(real_parameters, times)\n\n# Add noise\nnoise = 0.10\nvalues = org_values + np.random.normal(0, noise, org_values.shape)\n\n# Create an object with links to the model and time series\nproblem = pints.SingleOutputProblem(model, times, values)\n\n# Create a log-likelihood function (adds an extra parameter!)\nlog_likelihood = pints.GaussianKnownSigmaLogLikelihood(problem, noise)", "Now let's add our prior.\nFirst, we take a look at the LogPrior class, as well as the LogPDF class which it extends.\nFrom this we learn that:\n\nWe need to provide a method n_parameters() that returns the dimension of the parameter space our prior is defined on.\nObjects of our prior class should be callable: they should have a __call__ method that takes a parameter vector as input and returns a scalar.\nIf we like, we can implement an optional sample() method.\n\nLeaving aside the sample() method, we can implement our prior like this:", "class CircularLogPrior(pints.LogPrior):\n def __init__(self, center, radius):\n # Store center\n self._center = np.array(center)\n # Set circle radius\n self._r = float(radius)\n # Calculate c \n A = np.pi * self._r * self._r\n self._c = np.log(1 / A)\n \n def n_parameters(self):\n return 2\n \n def __call__(self, parameters):\n # Get coordinates relative to center\n p = np.array(parameters) - self._center\n \n # Calculate the radius\n r = np.sqrt(p[0]*p[0] + p[1]*p[1])\n \n # Return\n return self._c if r < self._r else -float('inf')\n ", "Now we can test our prior with a few values:", "p = CircularLogPrior([0, 0], 1)\nprint(p([0, 0])) # c\nprint(p([1, 1])) # -inf\nprint(p([-0.5, -0.5])) # c\nprint(p([-1.0, 0])) # -inf\nprint(p([0.9, 0])) # c", "Now we can try using it in an inference routine:", "# Create a log-prior\nlog_prior = CircularLogPrior(center=real_parameters, radius=0.001)\n\n# Create a posterior log-likelihood (log(likelihood * prior))\nlog_posterior = pints.LogPosterior(log_likelihood, log_prior)\n\n# Choose starting points for 3 mcmc chains\nxs = [\n real_parameters + np.array([0.0005, -0.0005]),\n real_parameters + np.array([-0.0005, -0.0005]),\n real_parameters + np.array([-0.0005, 0.0005]),\n]\n\n# Create mcmc routine\nmcmc = pints.MCMCController(log_posterior, 3, xs, method=pints.HaarioBardenetACMC)\n\n# Add stopping criterion\nmcmc.set_max_iterations(4000)\n\n# Start adapting after 1000 iterations\nmcmc.set_initial_phase_iterations(1000)\n\n# Disable logging\nmcmc.set_log_to_screen(False)\n\n# Run!\nprint('Running...')\nchains = mcmc.run()\nprint('Done!')\n\n# Show traces and histograms\npints.plot.trace(chains)\n\n# Discard warm up\nchains = chains[:, 2000:, :]\n\n# Check convergence and other properties of chains\nresults = pints.MCMCSummary(chains=chains, time=mcmc.time(), parameter_names=['growth rate', 'capacity'])\nprint(results)\n\n# Look at distribution in chain 0\npints.plot.pairwise(chains[0], kde=True)\n\n# Show graphs\nplt.show()" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
ES-DOC/esdoc-jupyterhub
notebooks/inpe/cmip6/models/besm-2-7/ocnbgchem.ipynb
gpl-3.0
[ "ES-DOC CMIP6 Model Properties - Ocnbgchem\nMIP Era: CMIP6\nInstitute: INPE\nSource ID: BESM-2-7\nTopic: Ocnbgchem\nSub-Topics: Tracers. \nProperties: 65 (37 required)\nModel descriptions: Model description details\nInitialized From: -- \nNotebook Help: Goto notebook help page\nNotebook Initialised: 2018-02-15 16:54:06\nDocument Setup\nIMPORTANT: to be executed each time you run the notebook", "# DO NOT EDIT ! \nfrom pyesdoc.ipython.model_topic import NotebookOutput \n\n# DO NOT EDIT ! \nDOC = NotebookOutput('cmip6', 'inpe', 'besm-2-7', 'ocnbgchem')", "Document Authors\nSet document authors", "# Set as follows: DOC.set_author(\"name\", \"email\") \n# TODO - please enter value(s)", "Document Contributors\nSpecify document contributors", "# Set as follows: DOC.set_contributor(\"name\", \"email\") \n# TODO - please enter value(s)", "Document Publication\nSpecify document publication status", "# Set publication status: \n# 0=do not publish, 1=publish. \nDOC.set_publication_status(0)", "Document Table of Contents\n1. Key Properties\n2. Key Properties --&gt; Time Stepping Framework --&gt; Passive Tracers Transport\n3. Key Properties --&gt; Time Stepping Framework --&gt; Biology Sources Sinks\n4. Key Properties --&gt; Transport Scheme\n5. Key Properties --&gt; Boundary Forcing\n6. Key Properties --&gt; Gas Exchange\n7. Key Properties --&gt; Carbon Chemistry\n8. Tracers\n9. Tracers --&gt; Ecosystem\n10. Tracers --&gt; Ecosystem --&gt; Phytoplankton\n11. Tracers --&gt; Ecosystem --&gt; Zooplankton\n12. Tracers --&gt; Disolved Organic Matter\n13. Tracers --&gt; Particules\n14. Tracers --&gt; Dic Alkalinity \n1. Key Properties\nOcean Biogeochemistry key properties\n1.1. Model Overview\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOverview of ocean biogeochemistry model", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.model_overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "1.2. Model Name\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nName of ocean biogeochemistry model code (PISCES 2.0,...)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.model_name') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "1.3. Model Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of ocean biogeochemistry model", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.model_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Geochemical\" \n# \"NPZD\" \n# \"PFT\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "1.4. Elemental Stoichiometry\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe elemental stoichiometry (fixed, variable, mix of the two)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.elemental_stoichiometry') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Fixed\" \n# \"Variable\" \n# \"Mix of both\" \n# TODO - please enter value(s)\n", "1.5. Elemental Stoichiometry Details\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe which elements have fixed/variable stoichiometry", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.elemental_stoichiometry_details') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "1.6. Prognostic Variables\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N\nList of all prognostic tracer variables in the ocean biogeochemistry component", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.prognostic_variables') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "1.7. Diagnostic Variables\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N\nList of all diagnotic tracer variables in the ocean biogeochemistry component", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.diagnostic_variables') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "1.8. Damping\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nDescribe any tracer damping used (such as artificial correction or relaxation to climatology,...)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.damping') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "2. Key Properties --&gt; Time Stepping Framework --&gt; Passive Tracers Transport\nTime stepping method for passive tracers transport in ocean biogeochemistry\n2.1. Method\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nTime stepping framework for passive tracers", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.passive_tracers_transport.method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"use ocean model transport time step\" \n# \"use specific time step\" \n# TODO - please enter value(s)\n", "2.2. Timestep If Not From Ocean\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nTime step for passive tracers (if different from ocean)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.passive_tracers_transport.timestep_if_not_from_ocean') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "3. Key Properties --&gt; Time Stepping Framework --&gt; Biology Sources Sinks\nTime stepping framework for biology sources and sinks in ocean biogeochemistry\n3.1. Method\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nTime stepping framework for biology sources and sinks", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.biology_sources_sinks.method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"use ocean model transport time step\" \n# \"use specific time step\" \n# TODO - please enter value(s)\n", "3.2. Timestep If Not From Ocean\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nTime step for biology sources and sinks (if different from ocean)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.biology_sources_sinks.timestep_if_not_from_ocean') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "4. Key Properties --&gt; Transport Scheme\nTransport scheme in ocean biogeochemistry\n4.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of transport scheme", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.transport_scheme.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Offline\" \n# \"Online\" \n# TODO - please enter value(s)\n", "4.2. Scheme\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nTransport scheme used", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.transport_scheme.scheme') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Use that of ocean model\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "4.3. Use Different Scheme\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nDecribe transport scheme if different than that of ocean model", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.transport_scheme.use_different_scheme') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "5. Key Properties --&gt; Boundary Forcing\nProperties of biogeochemistry boundary forcing\n5.1. Atmospheric Deposition\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe how atmospheric deposition is modeled", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.atmospheric_deposition') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"from file (climatology)\" \n# \"from file (interannual variations)\" \n# \"from Atmospheric Chemistry model\" \n# TODO - please enter value(s)\n", "5.2. River Input\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe how river input is modeled", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.river_input') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"from file (climatology)\" \n# \"from file (interannual variations)\" \n# \"from Land Surface model\" \n# TODO - please enter value(s)\n", "5.3. Sediments From Boundary Conditions\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nList which sediments are speficied from boundary condition", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.sediments_from_boundary_conditions') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "5.4. Sediments From Explicit Model\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nList which sediments are speficied from explicit sediment model", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.sediments_from_explicit_model') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "6. Key Properties --&gt; Gas Exchange\n*Properties of gas exchange in ocean biogeochemistry *\n6.1. CO2 Exchange Present\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs CO2 gas exchange modeled ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CO2_exchange_present') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "6.2. CO2 Exchange Type\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nDescribe CO2 gas exchange", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CO2_exchange_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"OMIP protocol\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "6.3. O2 Exchange Present\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs O2 gas exchange modeled ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.O2_exchange_present') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "6.4. O2 Exchange Type\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nDescribe O2 gas exchange", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.O2_exchange_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"OMIP protocol\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "6.5. DMS Exchange Present\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs DMS gas exchange modeled ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.DMS_exchange_present') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "6.6. DMS Exchange Type\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nSpecify DMS gas exchange scheme type", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.DMS_exchange_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "6.7. N2 Exchange Present\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs N2 gas exchange modeled ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2_exchange_present') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "6.8. N2 Exchange Type\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nSpecify N2 gas exchange scheme type", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2_exchange_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "6.9. N2O Exchange Present\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs N2O gas exchange modeled ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2O_exchange_present') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "6.10. N2O Exchange Type\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nSpecify N2O gas exchange scheme type", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2O_exchange_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "6.11. CFC11 Exchange Present\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs CFC11 gas exchange modeled ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC11_exchange_present') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "6.12. CFC11 Exchange Type\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nSpecify CFC11 gas exchange scheme type", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC11_exchange_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "6.13. CFC12 Exchange Present\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs CFC12 gas exchange modeled ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC12_exchange_present') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "6.14. CFC12 Exchange Type\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nSpecify CFC12 gas exchange scheme type", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC12_exchange_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "6.15. SF6 Exchange Present\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs SF6 gas exchange modeled ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.SF6_exchange_present') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "6.16. SF6 Exchange Type\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nSpecify SF6 gas exchange scheme type", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.SF6_exchange_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "6.17. 13CO2 Exchange Present\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs 13CO2 gas exchange modeled ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.13CO2_exchange_present') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "6.18. 13CO2 Exchange Type\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nSpecify 13CO2 gas exchange scheme type", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.13CO2_exchange_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "6.19. 14CO2 Exchange Present\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs 14CO2 gas exchange modeled ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.14CO2_exchange_present') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "6.20. 14CO2 Exchange Type\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nSpecify 14CO2 gas exchange scheme type", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.14CO2_exchange_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "6.21. Other Gases\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nSpecify any other gas exchange", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.other_gases') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "7. Key Properties --&gt; Carbon Chemistry\nProperties of carbon chemistry biogeochemistry\n7.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe how carbon chemistry is modeled", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.carbon_chemistry.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"OMIP protocol\" \n# \"Other protocol\" \n# TODO - please enter value(s)\n", "7.2. PH Scale\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf NOT OMIP protocol, describe pH scale.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.carbon_chemistry.pH_scale') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Sea water\" \n# \"Free\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "7.3. Constants If Not OMIP\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf NOT OMIP protocol, list carbon chemistry constants.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.key_properties.carbon_chemistry.constants_if_not_OMIP') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "8. Tracers\nOcean biogeochemistry tracers\n8.1. Overview\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOverview of tracers in ocean biogeochemistry", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "8.2. Sulfur Cycle Present\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs sulfur cycle modeled ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.sulfur_cycle_present') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "8.3. Nutrients Present\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N\nList nutrient species present in ocean biogeochemistry model", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.nutrients_present') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Nitrogen (N)\" \n# \"Phosphorous (P)\" \n# \"Silicium (S)\" \n# \"Iron (Fe)\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "8.4. Nitrous Species If N\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N\nIf nitrogen present, list nitrous species.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.nitrous_species_if_N') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Nitrates (NO3)\" \n# \"Amonium (NH4)\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "8.5. Nitrous Processes If N\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N\nIf nitrogen present, list nitrous processes.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.nitrous_processes_if_N') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Dentrification\" \n# \"N fixation\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "9. Tracers --&gt; Ecosystem\nEcosystem properties in ocean biogeochemistry\n9.1. Upper Trophic Levels Definition\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDefinition of upper trophic level (e.g. based on size) ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.upper_trophic_levels_definition') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "9.2. Upper Trophic Levels Treatment\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDefine how upper trophic level are treated", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.upper_trophic_levels_treatment') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "10. Tracers --&gt; Ecosystem --&gt; Phytoplankton\nPhytoplankton properties in ocean biogeochemistry\n10.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of phytoplankton", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.phytoplankton.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"None\" \n# \"Generic\" \n# \"PFT including size based (specify both below)\" \n# \"Size based only (specify below)\" \n# \"PFT only (specify below)\" \n# TODO - please enter value(s)\n", "10.2. Pft\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N\nPhytoplankton functional types (PFT) (if applicable)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.phytoplankton.pft') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Diatoms\" \n# \"Nfixers\" \n# \"Calcifiers\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "10.3. Size Classes\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N\nPhytoplankton size classes (if applicable)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.phytoplankton.size_classes') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Microphytoplankton\" \n# \"Nanophytoplankton\" \n# \"Picophytoplankton\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "11. Tracers --&gt; Ecosystem --&gt; Zooplankton\nZooplankton properties in ocean biogeochemistry\n11.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of zooplankton", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.zooplankton.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"None\" \n# \"Generic\" \n# \"Size based (specify below)\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "11.2. Size Classes\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N\nZooplankton size classes (if applicable)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.zooplankton.size_classes') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Microzooplankton\" \n# \"Mesozooplankton\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "12. Tracers --&gt; Disolved Organic Matter\nDisolved organic matter properties in ocean biogeochemistry\n12.1. Bacteria Present\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs there bacteria representation ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.disolved_organic_matter.bacteria_present') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "12.2. Lability\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe treatment of lability in dissolved organic matter", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.disolved_organic_matter.lability') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"None\" \n# \"Labile\" \n# \"Semi-labile\" \n# \"Refractory\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "13. Tracers --&gt; Particules\nParticulate carbon properties in ocean biogeochemistry\n13.1. Method\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nHow is particulate carbon represented in ocean biogeochemistry?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.particules.method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Diagnostic\" \n# \"Diagnostic (Martin profile)\" \n# \"Diagnostic (Balast)\" \n# \"Prognostic\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "13.2. Types If Prognostic\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N\nIf prognostic, type(s) of particulate matter taken into account", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.particules.types_if_prognostic') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"POC\" \n# \"PIC (calcite)\" \n# \"PIC (aragonite\" \n# \"BSi\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "13.3. Size If Prognostic\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf prognostic, describe if a particule size spectrum is used to represent distribution of particules in water volume", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.particules.size_if_prognostic') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"No size spectrum used\" \n# \"Full size spectrum\" \n# \"Discrete size classes (specify which below)\" \n# TODO - please enter value(s)\n", "13.4. Size If Discrete\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf prognostic and discrete size, describe which size classes are used", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.particules.size_if_discrete') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "13.5. Sinking Speed If Prognostic\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf prognostic, method for calculation of sinking speed of particules", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.particules.sinking_speed_if_prognostic') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Constant\" \n# \"Function of particule size\" \n# \"Function of particule type (balast)\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "14. Tracers --&gt; Dic Alkalinity\nDIC and alkalinity properties in ocean biogeochemistry\n14.1. Carbon Isotopes\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N\nWhich carbon isotopes are modelled (C13, C14)?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.dic_alkalinity.carbon_isotopes') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"C13\" \n# \"C14)\" \n# TODO - please enter value(s)\n", "14.2. Abiotic Carbon\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs abiotic carbon modelled ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.dic_alkalinity.abiotic_carbon') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "14.3. Alkalinity\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nHow is alkalinity modelled ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocnbgchem.tracers.dic_alkalinity.alkalinity') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Prognostic\" \n# \"Diagnostic)\" \n# TODO - please enter value(s)\n", "©2017 ES-DOC" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
mayankjohri/LetsExplorePython
Section 1 - Core Python/Chapter 14 - Properties/property.ipynb
gpl-3.0
[ "property\n\nPython has a great concept called property, which makes the life of an object oriented programmer much simpler. Before defining and going into details of what a property in Python is, let us first build an intuition on why it would be needed in the first place.", "CONST = 10 # some constant\nclass Weather_balloon():\n temp = 222\n \n def convert_temp_to_f(self):\n return self.temp * CONST\n \nw = Weather_balloon()\nw.temp = 122\nprint(w.convert_temp_to_f())\n\nclass Circle():\n area = None\n radius = None\n\n def __init__(self, radius):\n self.radius = radius\n self.area = 3.14*radius*radius\n \nc = Circle(10)\nprint(c.radius)\n\nprint(c.area)\nc.area=222\n\nprint(c.radius)\nprint(c.area)\n\nclass Circle():\n _area = None\n _radius = None\n \n def __init__(self, radius):\n self.set_radius(radius)\n \n def get_area(self):\n return self._area\n \n def get_radius(self):\n return self._radius\n \n def set_radius(self, radius):\n self._radius = radius\n self._area = 3.14*radius*radius\n\n radius = property(get_radius, set_radius)\n\nc = Circle(10)\nprint(c.radius)\nprint(c._area)\n\nc.radius = 222\nprint(c.radius)\nprint(c._area)\n\nimport math\n\nclass Circle():\n _area = None\n _radius = None\n \n def __init__(self, radius):\n self.set_radius(radius)\n \n def get_radius(self):\n return self._radius\n \n def set_radius(self, radius):\n self._radius = radius\n self._area = 3.14*radius*radius\n\n radius = property(get_radius, set_radius)\n \n @property\n def area(self):\n return self._area\n \n @area.setter\n def area(self, area):\n self._area = area\n self._radius = math.sqrt(self._area)/3.14\n \n \nc = Circle(10)\nprint(c.radius)\nprint(c.area)\n\nprint(\"---\")\nc.radius=222\n\nprint(c.radius)\nprint(c.area)\n\nc.area=154751\n\nprint(c.radius)\nprint(c.area)\n\nclass Celsius:\n def __init__(self, temperature = 0):\n self.temperature = temperature\n\n def to_fahrenheit(self):\n return (self.temperature * 1.8) + 32\n\nman = Celsius()\n# set temperature\nman.temperature = 37\n\n# get temperature\nprint(man.temperature)\n\n\n# get degrees Fahrenheit\nprint(man.to_fahrenheit())\n##### print(Celsius.temperature)\n\n##############\n### Riddle ###\n##############\nclass MyClass(): \n x = 0\n y = 100\n\na = MyClass()\nb = MyClass()\n\na.x = 2\nprint(id(a.y), id(b.y))\nprint(id(a.x), id(b.x))\nprint(b.x)\n\nMyClass.x = 4\nprint(a.x)\nprint(b.x)\n\nMyClass.x = 7\nprint(a.x)\nprint(b.x)\nprint(\"~~~~~~\")\nb.x = MyClass.y\nMyClass.x = 4\nprint(b.x)", "Class with Getter and Setter", "class Celsius:\n def __init__(self, temperature = 0):\n self.set_temperature(temperature)\n\n def to_fahrenheit(self):\n return (self.get_temperature() * 1.8) + 32\n\n # new update\n def get_temperature(self):\n return self._temperature\n\n def set_temperature(self, value):\n if value < -273:\n raise ValueError(\"Temperature below -273 is not possible\")\n self._temperature = value", "We can see above that new methods get_temperature() and set_temperature() were defined and furthermore, temperature was replaced with _temperature. An underscore (_) at the beginning is used to denote private variables in Python.\nPython Way - Property\n\nThe pythonic way to deal with the above problem is to use property. Here is how we could have achieved it.", "class Celsius:\n def __init__(self, temperature = 0):\n self.temperature = temperature\n\n def to_fahrenheit(self):\n return (self.temperature * 1.8) + 32\n\n def get_temperature(self):\n print(\"Getting value\")\n return self._temperature\n\n def set_temperature(self, value):\n if value < -273:\n raise ValueError(\"Temperature below -273 is not possible\")\n print(\"Setting value\")\n self._temperature = value\n\n temperature = property(get_temperature, set_temperature)\n\nman = Celsius()\n# set temperature\nman.temperature = 137\n\n# get temperature\nprint(man.temperature)\n\n# get degrees Fahrenheit\nprint(man.to_fahrenheit())\n##### print(Celsius.temperature)", "Deep in Property", "### Method 1\ntemperature = property(get_temperature, set_temperature)\n\n### Method 2\n# make empty property\ntemperature = property()\n# assign getter\ntemperature = temperature.getter(get_temperature)\n# assign setter\ntemperature = temperature.setter(set_temperature)\n\n### Method 3\nclass Celsius:\n def __init__(self, temperature = 0):\n self._temperature = temperature\n\n def to_fahrenheit(self):\n return (self._temperature * 1.8) + 32\n\n @property\n def temperature(self):\n print(\"Getting value\")\n return self._temperature\n\n @temperature.setter\n def temperature(self, value):\n if value < -273:\n raise ValueError(\"Temperature below -273 is not possible\")\n print(\"Setting value\")\n self._temperature = value\n\n \n\ncelc = Celsius()\ncelc.temperature = 100\nprint(celc.temperature)\n# del(celc.temperature) # Need to explicitly define a deleter\n# print(celc.temperature)\n", "Another example to", "### Method 3\nclass Celsius:\n def __init__(self, temperature = 0):\n self._temperature = temperature\n\n def to_fahrenheit(self):\n return (self._temperature * 1.8) + 32\n\n @property\n def temperature(self):\n print(\"Getting value\")\n return self._temperature\n\n @temperature.setter\n def temperature(self, value):\n if value < -273:\n raise ValueError(\"Temperature below -273 is not possible\")\n print(\"Setting value\")\n self._temperature = value\n \n @temperature.deleter\n def temperature(self):\n print(\"deleting the property\")\n del(self._temperature)\n \n\ncelc = Celsius()\ncelc.temperature = 100\nprint(celc.temperature)\ndel(celc.temperature)\nprint(celc.temperature) # This property is no longer valid thus will error out\n" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
kit-cel/wt
ccgbc/ch2_Codes_Basic_Concepts/DMC_Capacity.ipynb
gpl-2.0
[ "Capacity of a Discrete Memoryless Channel (DMC)\nThis code is provided as supplementary material of the lecture Channel Coding 2 - Advanced Methods.\nThis code illustrates\n* Calculating the channel capacity using convex optimization\n* Calculating the capacity of weakly convex channels", "import cvxpy as cp\nimport numpy as np\nimport matplotlib.pyplot as plt", "Helper function to check if a channel is weakly symmetric and hence also symmetric)", "# check if channel is weakly symmetric\ndef is_weakly_symmetric(P):\n V = P.shape[1]\n W = P.shape[0]\n\n # check if matrix P is weakly symmetric\n col1 = np.sort(P[:,0])\n permutation_test = [np.array_equal(np.sort(P[:,k]), col1) for k in range(1,V)]\n\n retval = all(permutation_test)\n \n if retval == True:\n row_sums = np.sum(P,axis=1)\n if not all(row_sums == row_sums[0]):\n retval = False;\n \n return retval", "Compute the capacity of the channel. If the channel is weakly symmetric, use the direct equation\n\\begin{equation}\nC = \\log_2(W) + \\sum_{i=1}^W P_{i,1}\\log_2P_{i,1} \n\\end{equation}\nThe capacity achieving input distribution is obtained as $\\boldsymbol{p}_x = \\begin{pmatrix} \\frac{1}{W} & \\cdots & \\frac{1}{W}\\end{pmatrix}$.\nIf the channel is not weakly symmetric, use numerical optimization (here convex optimization, as we know that the mutual information is concave in the channel input distribution) to find the capacity and the capacity-achieving input distribution by solving the convex program\n\\begin{align}\n\\text{maximize}\\ \\ & (\\boldsymbol{1}{1\\times W}\\cdot\\tilde{\\boldsymbol{P}})\\boldsymbol{p}_x +\\frac{1}{\\ln(2)}\\boldsymbol{1}{1\\times W}\\cdot f_{\\textrm{entr.}}(\\boldsymbol{P}\\boldsymbol{p}x)\\\n\\text{subject to}\\ &\\sum_ip{x,i} = 1\\ \\text{and}\\ p_{x,i} \\geq 0\n\\end{align}", "def channel_capacity(P):\n # input and output dimensions\n V = P.shape[1]\n W = P.shape[0]\n\n if is_weakly_symmetric(P):\n col = P[:,0]\n C = np.log2(W) + np.sum(col * np.log2(col))\n px = np.ones(V)/V\n \n return C,px\n else:\n # compute Ptilde, multiplication is element-wise here (not matrix multiplication!)\n Ptilde = np.zeros_like(P)\n \n Ptilde[P > 0] = P[P > 0] * np.log2(P[P > 0])\n Ptilde[np.isnan(Ptilde)] = 0 # case 0*log2(0) = 0 (and not inf/nan)\n \n # optimize Px\n px = cp.Variable(shape=V)\n \n objective = cp.Maximize(np.sum(Ptilde,axis=0)@px + cp.sum(cp.entr(P@px))/np.log(2.0))\n constraints = [cp.sum(px) == 1.0, px >= 0]\n \n problem = cp.Problem(objective, constraints)\n problem.solve()\n \n return problem.value, px.value \n", "Compute the capacity for the weakly symmetric channel used in the lecture", "# channel transition matrix of a symmetric channel\nP = np.array([[1/3, 1/3], [1/2, 1/6], [1/6, 1/2]])\nprint(channel_capacity(P))", "Compute the capacity for a non-symmetric channel. Observe that the input distribution is not uniform", "# channel transition matrix of an arbitrary channel\nP = np.array([[1/2, 1/8], [1/3, 5/8], [1/6, 1/4]])\nprint(channel_capacity(P))", "Compute the capacity for a Z-channel with error probability $q=0.1$", "# Z-channel\nq = 0.1\nP = np.array([[1, q], [0, 1-q]])\nprint(channel_capacity(P))", "Compute capacitiies of the Z-channel with a varying range of input parameters", "qs = np.linspace(0.00001,0.99999,100)\nCs = np.zeros_like(qs)\npxs = np.empty((0,2))\nfor k in range(len(qs)):\n P = np.array([[1, qs[k]], [0, 1-qs[k]]])\n C,px = channel_capacity(P)\n Cs[k] = C\n pxs = np.vstack((pxs,px))\n\nplt.figure(figsize=(12,7))\nplt.plot(qs, Cs)\nplt.xlim((0,1))\nplt.ylim((0,1))\nplt.xlabel('$q$',fontsize=14)\nplt.ylabel('C (bit/channel use)',fontsize=14)\n\nplt.figure(figsize=(12,3.5))\nfont = {'size' : 18}\nplt.rc('font', **font)\n#plt.rc('text', usetex=True)\nplt.imshow(pxs.T, extent=[0, qs[-1], -1, 1], aspect='auto', vmin=0.2, vmax=0.8)\nplt.xlim(0,1)\nplt.xlabel('$q$')\nplt.yticks([-0.5, 0.5], ('$P(X=1)$', '$P(X=0)$'))\nplt.colorbar();\n#plt.savefig('Zchannel_input_distribution.pdf',bbox_inches='tight')" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
arogozhnikov/einops
docs/2-einops-for-deep-learning.ipynb
mit
[ "Einops tutorial, part 2: deep learning\nPrevious part of tutorial provides visual examples with numpy.\nWhat's in this tutorial?\n\nworking with deep learning packages\nimportant cases for deep learning models\neinsops.asnumpy and einops.layers", "from einops import rearrange, reduce\n\nimport numpy as np\nx = np.random.RandomState(42).normal(size=[10, 32, 100, 200])\n\n# utility to hide answers\nfrom utils import guess", "Select your flavour\nSwitch to the framework you're most comfortable with.", "# select one from 'chainer', 'gluon', 'tensorflow', 'pytorch' \nflavour = 'pytorch'\n\nprint('selected {} backend'.format(flavour))\nif flavour == 'tensorflow':\n import tensorflow as tf\n tape = tf.GradientTape(persistent=True)\n tape.__enter__()\n x = tf.Variable(x) + 0\nelif flavour == 'pytorch':\n import torch\n x = torch.from_numpy(x)\n x.requires_grad = True\nelif flavour == 'chainer':\n import chainer\n x = chainer.Variable(x)\nelse:\n assert flavour == 'gluon'\n import mxnet as mx\n mx.autograd.set_recording(True)\n x = mx.nd.array(x, dtype=x.dtype)\n x.attach_grad()\n\ntype(x), x.shape", "Simple computations\n\nconverting bchw to bhwc format and back is a common operation in CV\ntry to predict output shape and then check your guess!", "y = rearrange(x, 'b c h w -> b h w c')\nguess(y.shape)", "Worked!\nDid you notice? Code above worked for you backend of choice. <br />\nEinops functions work with any tensor like they are native to the framework.\nBackpropagation\n\ngradients are a corner stone of deep learning\nYou can back-propagate through einops operations <br />\n (just as with framework native operations)", "y0 = x\ny1 = reduce(y0, 'b c h w -> b c', 'max')\ny2 = rearrange(y1, 'b c -> c b')\ny3 = reduce(y2, 'c b -> ', 'sum')\n\nif flavour == 'tensorflow':\n print(reduce(tape.gradient(y3, x), 'b c h w -> ', 'sum'))\nelse:\n y3.backward()\n print(reduce(x.grad, 'b c h w -> ', 'sum'))", "Meet einops.asnumpy\nJust converts tensors to numpy (and pulls from gpu if necessary)", "from einops import asnumpy\ny3_numpy = asnumpy(y3)\n\nprint(type(y3_numpy))", "Common building blocks of deep learning\nLet's check how some familiar operations can be written with einops\nFlattening is common operation, frequently appears at the boundary\nbetween convolutional layers and fully connected layers", "y = rearrange(x, 'b c h w -> b (c h w)')\nguess(y.shape)", "space-to-depth", "y = rearrange(x, 'b c (h h1) (w w1) -> b (h1 w1 c) h w', h1=2, w1=2)\nguess(y.shape)", "depth-to-space (notice that it's reverse of the previous)", "y = rearrange(x, 'b (h1 w1 c) h w -> b c (h h1) (w w1)', h1=2, w1=2)\nguess(y.shape)", "Reductions\nSimple global average pooling.", "y = reduce(x, 'b c h w -> b c', reduction='mean')\nguess(y.shape)", "max-pooling with a kernel 2x2", "y = reduce(x, 'b c (h h1) (w w1) -> b c h w', reduction='max', h1=2, w1=2)\nguess(y.shape)\n\n# you can skip names for reduced axes\ny = reduce(x, 'b c (h 2) (w 2) -> b c h w', reduction='max')\nguess(y.shape)", "1d, 2d and 3d pooling are defined in a similar way\nfor sequential 1-d models, you'll probably want pooling over time\npython\nreduce(x, '(t 2) b c -&gt; t b c', reduction='max')\nfor volumetric models, all three dimensions are pooled\npython\nreduce(x, 'b c (x 2) (y 2) (z 2) -&gt; b c x y z', reduction='max')\nUniformity is a strong point of einops, and you don't need specific operation for each particular case.\nGood exercises\n\nwrite a version of space-to-depth for 1d and 3d (2d is provided above)\nwrite an average / max pooling for 1d models. \n\nSqueeze and unsqueeze (expand_dims)", "# models typically work only with batches, \n# so to predict a single image ...\nimage = rearrange(x[0, :3], 'c h w -> h w c')\n# ... create a dummy 1-element axis ...\ny = rearrange(image, 'h w c -> () c h w')\n# ... imagine you predicted this with a convolutional network for classification,\n# we'll just flatten axes ...\npredictions = rearrange(y, 'b c h w -> b (c h w)')\n# ... finally, decompose (remove) dummy axis\npredictions = rearrange(predictions, '() classes -> classes')", "keepdims-like behavior for reductions\n\nempty composition () provides dimensions of length 1, which are broadcastable.\nalternatively, you can use just 1 to introduce new axis, that's a synonym to ()\n\nper-channel mean-normalization for each image:", "y = x - reduce(x, 'b c h w -> b c 1 1', 'mean')\nguess(y.shape)", "per-channel mean-normalization for whole batch:", "y = x - reduce(y, 'b c h w -> 1 c 1 1', 'mean')\nguess(y.shape)", "Stacking\nlet's take a list of tensors", "list_of_tensors = list(x)", "New axis (one that enumerates tensors) appears first on the left side of expression.\nJust as if you were indexing list - first you'd get tensor by index", "tensors = rearrange(list_of_tensors, 'b c h w -> b h w c')\nguess(tensors.shape)\n\n# or maybe stack along last dimension?\ntensors = rearrange(list_of_tensors, 'b c h w -> h w c b')\nguess(tensors.shape)", "Concatenation\nconcatenate over the first dimension?", "tensors = rearrange(list_of_tensors, 'b c h w -> (b h) w c')\nguess(tensors.shape)", "or maybe concatenate along last dimension?", "tensors = rearrange(list_of_tensors, 'b c h w -> h w (b c)')\nguess(tensors.shape)", "Shuffling within a dimension\nchannel shuffle (as it is drawn in shufflenet paper)", "y = rearrange(x, 'b (g1 g2 c) h w-> b (g2 g1 c) h w', g1=4, g2=4)\nguess(y.shape)", "simpler version of channel shuffle", "y = rearrange(x, 'b (g c) h w-> b (c g) h w', g=4)\nguess(y.shape)", "Split a dimension\nHere's a super-convenient trick.\nExample: when a network predicts several bboxes for each position\nAssume we got 8 bboxes, 4 coordinates each. <br />\nTo get coordinated into 4 separate variables, you move corresponding dimension to front and unpack tuple.", "bbox_x, bbox_y, bbox_w, bbox_h = \\\n rearrange(x, 'b (coord bbox) h w -> coord b bbox h w', coord=4, bbox=8)\n# now you can operate on individual variables\nmax_bbox_area = reduce(bbox_w * bbox_h, 'b bbox h w -> b h w', 'max')\nguess(bbox_x.shape)\nguess(max_bbox_area.shape)", "Getting into the weeds of tensor packing\nyou can skip this part - it explains why taking a habit of defining splits and packs explicitly\nwhen implementing custom gated activation (like GLU), split is needed:\npython\ny1, y2 = rearrange(x, 'b (split c) h w -&gt; split b c h w', split=2)\nresult = y2 * sigmoid(y2) # or tanh\n... but we could split differently\npython\ny1, y2 = rearrange(x, 'b (c split) h w -&gt; split b c h w', split=2)\n\nfirst one splits channels into consequent groups: y1 = x[:, :x.shape[1] // 2, :, :]\nwhile second takes channels with a step: y1 = x[:, 0::2, :, :]\n\nThis may drive to very surprising results when input is\n- a result of group convolution\n- a result of bidirectional LSTM/RNN\n- multi-head attention\nLet's focus on the second case (LSTM/RNN), since it is less obvious.\nFor instance, cudnn concatenates LSTM outputs for forward-in-time and backward-in-time\nAlso in pytorch GLU splits channels into consequent groups (first way)\nSo when LSTM's output comes to GLU,\n- forward-in-time produces linear part, and backward-in-time produces activation ...\n- and role of directions is different, and gradients coming to two parts are different\n - that's not what you expect from simple GLU(BLSTM(x)), right?\neinops notation makes such inconsistencies explicit and easy-detectable\nShape parsing\njust a handy utility", "from einops import parse_shape\n\ndef convolve_2d(x):\n # imagine we have a simple 2d convolution with padding,\n # so output has same shape as input.\n # Sorry for laziness, use imagination!\n return x\n\n# imagine we are working with 3d data\nx_5d = rearrange(x, 'b c x (y z) -> b c x y z', z=20)\n# but we have only 2d convolutions. \n# That's not a problem, since we can apply\ny = rearrange(x_5d, 'b c x y z -> (b z) c x y')\ny = convolve_2d(y)\n# not just specifies additional information, but verifies that all dimensions match\ny = rearrange(y, '(b z) c x y -> b c x y z', **parse_shape(x_5d, 'b c x y z'))\n\nparse_shape(x_5d, 'b c x y z')\n\n# we can skip some dimensions by writing underscore\nparse_shape(x_5d, 'batch c _ _ _')", "Striding anything\nFinally, how to convert any operation into a strided operation? <br />\n(like convolution with strides, aka dilated/atrous convolution)", "# each image is split into subgrids, each is now a separate \"image\"\ny = rearrange(x, 'b c (h hs) (w ws) -> (hs ws b) c h w', hs=2, ws=2)\ny = convolve_2d(y)\n# pack subgrids back to an image\ny = rearrange(y, '(hs ws b) c h w -> b c (h hs) (w ws)', hs=2, ws=2)\n\nassert y.shape == x.shape", "Layers\nFor frameworks that prefer operating with layers, layers are available.\nYou'll need to import a proper one depending on your backend:\npython\nfrom einops.layers.chainer import Rearrange, Reduce\nfrom einops.layers.gluon import Rearrange, Reduce\nfrom einops.layers.keras import Rearrange, Reduce\nfrom einops.layers.torch import Rearrange, Reduce\nEinops layers are identical to operations, and have same parameters. <br />\n(for the exception of first argument, which should be passed during call)\n```python\nlayer = Rearrange(pattern, axes_lengths)\nlayer = Reduce(pattern, reduction, axes_lengths)\napply layer to tensor\nx = layer(x)\n```\nUsually it is more convenient to use layers, not operations, to build models\n```python\nexample given for pytorch, but code in other frameworks is almost identical\nfrom torch.nn import Sequential, Conv2d, MaxPool2d, Linear, ReLU\nfrom einops.layers.torch import Reduce\nmodel = Sequential(\n Conv2d(3, 6, kernel_size=5),\n MaxPool2d(kernel_size=2),\n Conv2d(6, 16, kernel_size=5),\n # combined pooling and flattening in a single step\n Reduce('b c (h 2) (w 2) -> b (c h w)', 'max'), \n Linear(1655, 120), \n ReLU(),\n Linear(120, 10), \n)\n```\nWhat's now?\n\nrush through writing better code with einops+pytorch\n\nUse different framework? Not a big issue, most recommendations transfer well to other frameworks. <br />\neinops works the same way in any framework.\nFinally - just write your code with einops!" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
fabriziocosta/pyMotif
glam2_example.ipynb
mit
[ "%load_ext autoreload\n%autoreload 2\n\n%matplotlib inline\nfrom glam2_wrapper import Glam2\n\nfrom utilities import Weblogo\nwl = Weblogo(color_scheme='classic')\n\nglam2 = Glam2(alphabet='dna',\n gap_in_alphabet=True,\n scoring_criteria='pwm',\n alignment_runs=5,\n \n weblogo_obj = wl)\n\nglam2.fit(fasta_file=\"seq18.fa\")\n\nfor i in glam2.original_motives_list:\n for j in i:\n print j\n print\n\nfor i in glam2.aligned_motives_list:\n for j in i:\n print j\n print \n\nfor i in glam2.motives_list:\n for j in i:\n print j\n print\n\npredictions = glam2.predict(input_seqs='seq18.fa', return_list=True)\nfor p in predictions: print p\n\npredictions = glam2.predict(input_seqs=\"seq9.fa\", return_list=False)\nfor p in predictions: print p\n\nmatch = glam2.transform(input_seqs='seq9.fa', return_match=True)\nfor m in match: print m\n\nmatch = glam2.transform(input_seqs='seq9.fa', return_match=False)\nfor m in match: print m\n\nglam_2 = Glam2(alphabet='dna', gap_in_alphabet=True, scoring_criteria='pwm', alignment_runs=6)\n\npredictions = glam_2.fit_predict(fasta_file='seq9.fa', return_list=True)\nfor p in predictions: print p\n\nmatches = glam_2.fit_transform(fasta_file='seq9.fa', return_match=True)\nfor m in matches: print m", "<h3>Print motives as list</h3>", "#printing motives as lists\nfor motif in glam2.motives_list:\n for m in motif:\n print m\n print", "<h3>Display Sequence logo of unaligned motives</h3>", "glam2.display_logo(do_alignment=False)\n\nglam2.display_logo(motif_num=1)", "<h3>Multiple Sequence Alignment of motives with Muscle</h3>\nNote: Motives in this example were already aligned, hence no dashes appear in the alignment", "glam2.align_motives() #MSA with Muscle\nmotives1=glam2.aligned_motives_list\nfor m in motives1:\n for i in m:\n print i\n print", "<h3>Display sequence logo of aligned motives</h3>", "glam2.display_logo(do_alignment=True)", "<h3>Position Weight Matrices of Motives</h3>", "glam2.display()\n\nglam2.matrix()", "<h4>Display PWM of a single motif</h4>", "glam2.display(motif_num=3)", "<h3>Scoring a single sequence w.r.t a motif</h3>", "test_seq = 'GGAGAAAATACCGC' * 10\nseq_score = glam2.score(motif_num=2, seq=test_seq)\nprint seq_score", "<h3> Transform with HMM as scoring criteria</h3>", "glam_3 = Glam2(alphabet='dna', gap_in_alphabet=True, scoring_criteria='hmm', alignment_runs=3)\nmatches = glam_3.fit_transform(fasta_file=\"seq9.fa\", return_match=True)\nfor m in matches: print m" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
grokkaine/biopycourse
day3/howto_work.ipynb
cc0-1.0
[ "Work habits and reproducible research\n\nSource your code\nContinuous Integration\nReproducible research\nUnit Tests\nWorkflows\nAcceleration: profiling, JIT\n\nSource your code", "a = \"important stuff\"\n\nassert(a == \"important stuff\"), \"Ha! You just corrupted your data!\"\n\ndef f(a):\n a = \"corrupted \" + a\n return\n\na = f(a) ", "Why?\n\nBecause you avoid errors. Because reproducibility. And because you must be a responsible programmer and researcher.\nYou can version your code with a version control, track changes, assign error reporting, documentation etc.\nIf the code is kept in Jupyter Notebooks, it should always be executed sequentially.\nDid you know, Jupyter has code editor, terminal and markdown editor, independent from the notebook?\nMake your research presentation easily reproducible by offering the data, the code and the findings separately.\nBut, don't isolate the code from your findings! You can execute your source code from a notebook, that is fine!\nThe bits of notebook that you see on internet are meant to demonstrate code, not do scientific research.\nIf you receive a notebook from a colaborator, always make sure you can run it and reproduce the findings in it (it may already be corrupted).\n\nHow\nPython editors:\n- Simple text processors: Atom, Sublime, Geany, Notepad++ etc\n- Spyder: good for basic scientific programming, ipython interpreter\n- PyCharm: refactoring, internal jupyter, object browsing, etc\nWhat matters:\n- Using the editor most appropriate to the complexity of the task.\n- Full feature editors make it easier to write good code!\n- Syntax and style linting.\n- Code refactoring.\n- Git/svn integration.\n- Remote development.\n- Advanced debugging.\n- Unit testing.\nStandards\n\nSource code can be one or several scripts, it should contain information on deployment, testing and documentation.\nSome care for design should be given. Module hierarchy, will you create classes, use of design patterns.\nhttps://www.geeksforgeeks.org/python-design-patterns/\n\n\nPython style guide.\nhttps://www.python.org/dev/peps/pep-0008/\n\n\n\nQuality of life, or simply good habits\n- Software versioning milestones.\n- Continuous integration.\n- Reproducibility.\n- Workflows.\n- Containerization.\nVersioning example\n\nhttps://www.python.org/dev/peps/pep-0440/\nhttps://en.wikipedia.org/wiki/Software_versioning\n\nmilestone x.x:\n- expected outcomes\n- tests\nX.YaN # Alpha release\nX.YbN # Beta release\nX.YrcN # Release Candidate\nX.Y # Final release\nContinuous Integration\n\nSubmit your code to github often!\nMake backup for your data and findings.\nSet baselines on expected outcomes, and verify often that your code is tested against them.\nUnit tests are one way to do this.\nNotebook keeping helps (internal notebooks) especially if you can re-test.\nTest your code more than once, and everytime you do a modification.\nUse workflows, virtual environments and containers.\n\nReproducible research\n\nThe vast majority of published results today are not reproducible.\nLet us admit this, if our research cannot pe reproduced we probably did something else.\nResearch findings do not only depend on your plotting skill\nFor someone to be able to produce your results several thinks must harmonize:\nOpen data access:\n(on federated databases)\n\n\nOpen source access\non github, gitlab, etc\n\n\nOpen environment:\nconda requirements and container script (or image)\n\n\nFindings (paper AND notebooks)\npublic access\n\n\n\n\n\nDevelopment vs production\n\nThey are separated, fully.\nIf is fine to demo your source code, or just parts of it on a notebook during development.\nMost notebooks you see on the web are in a development stage.\nHow does it impact on the reproducibility if the development and production is not separated?\nBring forward the issue of having different projects using the same source code directory, or the same data directory. What is to do?\n\nReproducible environments: containers and conda\n\nDocker usage is described in another notebook\ncontainers can isolate an environment even better than a package manager!\nProblem: what if the old package versions cannot be maintained?\nProblem: what if the older container instances cannot be spinned or even re-created?\n\nUnit testing\n\nThe unittest module can be used from the command line to run tests from modules, classes or even individual test methods\nhttps://docs.python.org/3/library/unittest.html\nhttps://www.geeksforgeeks.org/unit-testing-python-unittest/\nhttps://realpython.com/python-testing/\n\n\nSome editors give special support for unit tests:\nhttps://www.jetbrains.com/help/pycharm/testing-your-first-python-application.html#choose-test-runner\n\n\n\nDocumentation\n\nDocstrings convention\nhttps://www.python.org/dev/peps/pep-0257/\nhttps://realpython.com/documenting-python-code/\n\n\nhttps://readthedocs.org/\nsimplifies software documentation by building, versioning, and hosting of your docs, automatically. Think of it as Continuous Documentation\n\n\nUsing Sphinx:\nhttps://docs.readthedocs.io/en/latest/intro/getting-started-with-sphinx.html\nhttps://www.sphinx-doc.org/en/master/\n\n\nOther options exist, pydoc, etc\n\nOther development tools:\n- debugger: allows to to follow your code step by step and investigate the program stack\n- profiler: shows memory usage finding possible leaks and bottlenecks (see acceleration notebook)\nWorkflows\nSnakemake\n- https://snakemake.readthedocs.io/en/stable/tutorial/basics.html\n- https://snakemake.github.io/snakemake-workflow-catalog/\nconda install -c bioconda snakemake\nconda install graphviz", "\nSAMPLES = ['ctl1', 'ctl2']\n\nrule all:\n input:\n 'merged.txt'\n\nrule acounts:\n input:\n file='{sample}.fastq'\n output:\n '{sample}_counts.txt'\n run:\n with open(input.file, 'r') as f:\n nc = [str(l.count('A')) for l in f if not l[0]=='@']\n data = ', '.join(nc)+'\\n'\n with open(output[0], 'w') as f: f.write(data)\n\nrule merge:\n input:\n counts=expand('{sample}_counts.txt',sample=SAMPLES)\n output:\n 'merged.txt'\n shell:\n \"\"\"\n for f in {input.counts}\n do\n\t\t\tcat $f >> {output}\n\t\tdone\n \"\"\"\n\nsnakemake --dag merged.txt | dot -Tsvg > dag.svg\n\nsnakemake --name mylittleworkflow.txt", "Nextflow\n- https://www.nextflow.io/", "\n\n#!/usr/bin/env nextflow\n \nparams.range = 100\n \n/*\n * A trivial Perl script producing a list of numbers pair\n */\nprocess perlTask {\n output:\n stdout randNums\n \n shell:\n '''\n #!/usr/bin/env perl\n use strict;\n use warnings;\n \n my $count;\n my $range = !{params.range};\n for ($count = 0; $count < 10; $count++) {\n print rand($range) . ', ' . rand($range) . \"\\n\";\n }\n '''\n}\n \n \n/*\n * A Python script task which parses the output of the previous script\n */\nprocess pyTask {\n echo true\n \n input:\n stdin randNums\n \n '''\n #!/usr/bin/env python\n import sys\n \n x = 0\n y = 0\n lines = 0\n for line in sys.stdin:\n items = line.strip().split(\",\")\n x = x+ float(items[0])\n y = y+ float(items[1])\n lines = lines+1\n \n print \"avg: %s - %s\" % ( x/lines, y/lines )\n '''\n \n}", "Acceleration\nSpeed: Profiling, IPython, JIT\nThe Python standard library contains the cProfile module for determining the time that takes every Python function when running the code. The pstats module allows to read the profiling results. Third party profiling libraries include in particular line_profiler for profiling code line after line, and memory_profiler for profiling memory usage. All these tools are very powerful and extremely useful when optimizing some code, but they might not be very easy to use at first.", "%%writefile script.py\nimport numpy as np\nimport numpy.random as rdn\n\n# uncomment for line_profiler\n# @profile\ndef test():\n a = rdn.randn(100000)\n b = np.repeat(a, 100)\n\ntest()\n\n!python -m cProfile -o prof script.py\n\n$ pip install ipython\n$ ipython --version\n0.13.1\n$ pip install line-profiler\n$ pip install psutil\n$ pip install memory_profiler\n\n\n%timeit?\n\n%run -t slow_functions.py\n\n%time {1 for i in range(10*1000000)}\n%timeit -n 1000 10*1000000\n\ndef foo(n):\n phrase = 'repeat me'\n pmul = phrase * n\n pjoi = ''.join([phrase for x in xrange(n)])\n pinc = ''\n for x in xrange(n):\n pinc += phrase\n del pmul, pjoi, pinc\n\n#%load_ext line_profiler\n%lprun -f foo foo(100000)", "%time & %timeit: See how long a script takes to run (one time, or averaged over a bunch of runs).\n%prun: See how long it took each function in a script to run.\n%lprun: See how long it took each line in a function to run.\n%mprun & %memit: See how much memory a script uses (line-by-line, or averaged over a bunch of runs).\n\nNumba\nNumba is an open source JIT (just in time) compiler that translates a subset of Python and NumPy code into fast machine code.\n- https://numba.pydata.org/\nconda install numba\nconda install cudatoolkit", "from numba import jit\nimport random\n\n@jit(nopython=True)\ndef monte_carlo_pi(nsamples):\n acc = 0\n for i in range(nsamples):\n x = random.random()\n y = random.random()\n if (x ** 2 + y ** 2) < 1.0:\n acc += 1\n return 4.0 * acc / nsamples\n\n@numba.jit(nopython=True, parallel=True)\ndef logistic_regression(Y, X, w, iterations):\n for i in range(iterations):\n w -= np.dot(((1.0 /\n (1.0 + np.exp(-Y * np.dot(X, w)))\n - 1.0) * Y), X)\n return w", "JIT with JAX\nJax is a JIT compiler optimized for machine learning.\n- https://github.com/google/jax\n- https://jax.readthedocs.io/en/latest/notebooks/quickstart.html#using-jit-to-speed-up-functions" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
regardscitoyens/consultation_an
exploitation/analyse_quanti.ipynb
agpl-3.0
[ "%matplotlib inline\n\nimport json\nimport pandas as pd\n\n\n", "Reading the data", "#contributions = pd.read_json(path_or_buf='../data/EGALITE4.brut.json', orient=\"columns\")\n\ndef loadContributions(file, withsexe=False):\n contributions = pd.read_json(path_or_buf=file, orient=\"columns\")\n rows = [];\n rindex = [];\n for i in range(0, contributions.shape[0]):\n row = {};\n row['id'] = contributions['id'][i]\n rindex.append(contributions['id'][i])\n if (withsexe):\n if (contributions['sexe'][i] == 'Homme'):\n row['sexe'] = 0\n else:\n row['sexe'] = 1\n for question in contributions['questions'][i]:\n if (question.get('Reponse')): # and (question['texte'][0:5] != 'Savez') :\n row[question['titreQuestion']+' : '+question['texte']] = 1\n for criteres in question.get('Reponse'):\n # print(criteres['critere'].keys())\n row[question['titreQuestion']+'. (Réponse) '+question['texte']+' -> '+str(criteres['critere'].get('texte'))] = 1\n rows.append(row)\n df = pd.DataFrame(data=rows)\n df.fillna(0, inplace=True)\n return df\n\ndf = loadContributions('../data/EGALITE1.brut.json', True)\ndf = df.merge(right=loadContributions('../data/EGALITE2.brut.json'), how='outer', right_on='id', left_on='id')\ndf = df.merge(right=loadContributions('../data/EGALITE3.brut.json'), how='outer', right_on='id', left_on='id')\ndf = df.merge(right=loadContributions('../data/EGALITE4.brut.json'), how='outer', right_on='id', left_on='id')\ndf = df.merge(right=loadContributions('../data/EGALITE5.brut.json'), how='outer', right_on='id', left_on='id')\ndf = df.merge(right=loadContributions('../data/EGALITE6.brut.json'), how='outer', right_on='id', left_on='id')\ndf.fillna(0, inplace=True)\ndf.index = df['id']\ndf.to_csv('consultation_an.csv', format='%d')\n#df.columns = ['Q_' + str(col+1) for col in range(len(df.columns) - 2)] + ['id' , 'sexe']\ndf.head()\n\ndf = loadContributions('../data/EGALITE4.brut.json', True)\n", "Build clustering model\nHere we build a kmeans model , and select the \"optimal\" of clusters.\nHere we see that the optimal number of clusters is 2.", "from sklearn.cluster import KMeans\nfrom sklearn import metrics\nimport numpy as np\nX = df.drop('id', axis=1).values\n\ndef train_kmeans(nb_clusters, X):\n kmeans = KMeans(n_clusters=nb_clusters, random_state=0).fit(X)\n return kmeans\n#print(kmeans.predict(X))\n#kmeans.cluster_centers_\n\n\ndef select_nb_clusters():\n perfs = {};\n for nbclust in range(2,10):\n kmeans_model = train_kmeans(nbclust, X);\n labels = kmeans_model.labels_\n # from http://scikit-learn.org/stable/modules/clustering.html#calinski-harabaz-index\n # we are in an unsupervised model. cannot get better!\n # perfs[nbclust] = metrics.calinski_harabaz_score(X, labels);\n perfs[nbclust] = metrics.silhouette_score(X, labels);\n print(perfs);\n return perfs;\n\n\ndf['clusterindex'] = train_kmeans(4, X).predict(X)\n#df \n\nperfs = select_nb_clusters();\n# result :\n# {2: 341.07570462155348, 3: 227.39963334619881, 4: 186.90438345452918, 5: 151.03979976346525, 6: 129.11214073405731, 7: 112.37235520885432, 8: 102.35994869157568, 9: 93.848315820675438}\n\noptimal_nb_clusters = max(perfs, key=perfs.get);\n\nprint(\"optimal_nb_clusters\" , optimal_nb_clusters);", "Build the optimal model and apply it", "km_model = train_kmeans(optimal_nb_clusters, X);\ndf['clusterindex'] = km_model.predict(X)\nlGroupBy = df.groupby(['clusterindex']).mean();\n\n# km_model.__dict__\n\ncluster_profile_counts = df.groupby(['clusterindex']).count();\ncluster_profile_means = df.groupby(['clusterindex']).mean();\nglobal_counts = df.count()\nglobal_means = df.mean()\n\n\n\n\ncluster_profile_counts.head()\n\n\n#cluster_profile_means.head()\n\n#df.info()\n\ndf_profiles = pd.DataFrame();\nnbclusters = cluster_profile_means.shape[0]\ndf_profiles['clusterindex'] = range(nbclusters)\nfor col in cluster_profile_means.columns:\n if(col != \"clusterindex\"):\n df_profiles[col] = np.zeros(nbclusters)\n for cluster in range(nbclusters):\n df_profiles[col][cluster] = cluster_profile_means[col][cluster]\n# row.append(df[col].mean());\ndf_profiles.head()\n\n#print(df_profiles.columns) \n\nintereseting_columns = {};\nfor col in df_profiles.columns:\n if(col != \"clusterindex\"):\n global_mean = df[col].mean()\n diff_means_global = abs(df_profiles[col] - global_mean). max();\n # print(col , diff_means_global)\n if(diff_means_global > 0.1):\n intereseting_columns[col] = True\n \n#print(intereseting_columns)\n\n\n%matplotlib inline\n\nimport matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#cols = [ col for col in cluster_profile_counts.columns]\n#cluster_profile_means.ix[0].plot.bar()\n ", "Cluster Profiles\nHere, the optimal model ihas two clusters , cluster 0 with 399 cases, and 1 with 537 cases. \nAs this model is based on binary inputs. Given this, the best description of the clusters is by the distribution of zeros and ones of each input (question).\nThe figure below gives the cluster profiles of this model. Cluster 0 on the left. 1 on the right. The questions invloved as different (highest bars)", "interesting = list(intereseting_columns.keys())\ndf_profiles_sorted = df_profiles[interesting].sort_index(axis=1)\ndf_profiles_sorted.plot.bar(figsize =(1, 1))\ndf_profiles_sorted.plot.bar(figsize =(16, 8), legend=False)\n\n\ndf_profiles_sorted.T\n\ndf_profiles.sort_index(axis=1).T" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
YuriyGuts/kaggle-quora-question-pairs
notebooks/preproc-extract-unique-questions.ipynb
mit
[ "Preprocessing: Unique Question Corpus\nBased on the training and test sets, extract a list of unique documents.\nImports\nThis utility package imports numpy, pandas, matplotlib and a helper kg module into the root namespace.", "from pygoose import *\n\nimport nltk", "Config\nAutomatically discover the paths to various data folders and compose the project structure.", "project = kg.Project.discover()", "Read data\nOriginal question datasets.", "df_train = pd.read_csv(project.data_dir + 'train.csv').fillna('')\ndf_test = pd.read_csv(project.data_dir + 'test.csv').fillna('')", "Load tools", "tokenizer = nltk.tokenize.RegexpTokenizer(r'\\w+')", "Remove duplicate questions", "df = pd.concat([df_train, df_test])\n\nunique_question_texts = [\n question.strip(' \\'\"')\n for question in np.unique(df[['question1', 'question2']].values.ravel())\n]", "Tokenize unique questions", "def tokenize_question_text(q):\n return tokenizer.tokenize(q.lower())\n\nunique_question_tokens = kg.jobs.map_batch_parallel(\n unique_question_texts,\n item_mapper=tokenize_question_text,\n batch_size=1000,\n)", "Save preprocessed data", "kg.io.save_lines(unique_question_texts, project.preprocessed_data_dir + 'unique_questions_raw.txt')\n\nkg.io.save(unique_question_tokens, project.preprocessed_data_dir + 'unique_questions_tokenized.pickle')" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
hchauvet/beampy
doc-src/auto_examples/plot_figure.ipynb
gpl-3.0
[ "%matplotlib inline", "figure\nInsert a figure inside a slide.\nFigure format can be:\n\npdf\nsvg\njpeg\npng\ngif\nMatplotlib figure object\nBokeh figure object\n\nFrom one file", "from beampy import *\n\n# Remove quiet=True to get beampy compilation outputs\ndoc = document(quiet=True)\n\nwith slide('A figure from a file'):\n figure('./ressources/test_0.svg', width=400)\n\n\ndisplay_matplotlib(gcs())", "From Matplotlib", "with slide('A matplotlib figure'):\n import matplotlib.pyplot as mpl\n import numpy as np\n\n f = mpl.figure()\n mpl.plot(np.random.rand(100), np.random.rand(100), 'o')\n\n figure(f, width=500)\n\ndisplay_matplotlib(gcs())", "From a gif", "with slide('An animated gif'):\n figure('../../tests/test.gif', width='50%')", "From Bokeh\n<div class=\"alert alert-info\"><h4>Note</h4><p>No svg export available for now, check the\n html file of the prensetation</p></div>", "with slide('A bokeh figure'):\n from bokeh.plotting import figure as bokfig\n\n p = bokfig(height=300, width=600)\n x = np.random.rand(100)\n y = np.random.rand(100)\n p.circle(x, y, legend=\"sin(x)\")\n\n figure(p)\n\n# Export the 3 slides of the presentation\nsave('./examples_html_outputs/figure.html')", "HTML output\n.. raw:: html\n&lt;iframe src=\"../_static/examples_html_outputs/figure.html\" width=\"100%\" height=\"500px\"&gt;&lt;/iframe&gt;\n\nModule arguments\n.. autoclass:: beampy.figure\n :noindex:" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
widdowquinn/SI_Holmes_etal_2017
notebooks/01-data_qa.ipynb
mit
[ "<img src=\"images/JHI_STRAP_Web.png\" style=\"width: 150px; float: right;\">\nSupplementary Information: Holmes et al. 2020\n1. Data cleaning, normalisation and quality assurance\nThis notebook describes raw data import, cleaning, and QA, then writing out of processed data to the data/ subdirectory, for use in model fitting.\nTable of Contents\n\nMicroarray data\nImport array data\n\n\nData QA\nProblematic probes\nInterpolation for problematic probes \n\n\nNormalisation\nWide to long form\nProbe matches to Sakai and DH10B\nWrite data\n\nPython imports", "%pylab inline\n\nimport os\nimport random\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport numpy as np\nimport pandas as pd\nimport scipy\nimport seaborn as sns\n\nfrom Bio import SeqIO\n\nimport tools", "Microarray data <a id=\"microarray_data\"></a>\n<div class=\"alert alert-warning\">\nRaw array data was previously converted to plain text comma-separated variable format from two `Excel` files:\n\n<ul>\n<li> The file `AH alldata 12082013.xlsx` was converted to `data/treatment_unix_endings.csv`\n<li> The file `AH alldata expt1 flagged 05092013.xlsx` was converted to `data/control_unix_endings_flags.csv`\n</ul>\n</div>\n\nThese describe microarray results for samples that underwent two treatments:\n\nin vitro growth only - i.e. control: data/control_unix_endings_flags.csv\nin vitro growth and plant passage - i.e. treatment: data/treatment_unix_endings.csv", "# Input array data filepaths\ncontrolarrayfile = os.path.join('..', 'data', 'control_unix_endings_flags.csv') # control experiment array data (preprocessed)\ntreatmentarrayfile = os.path.join('..', 'data', 'treatment_unix_endings.csv') # treatment experiment array data (preprocessed)", "Import array data <a id=\"import_data\"></a>", "control = pd.read_csv(controlarrayfile, sep=',', skiprows=4, index_col=0)\ntreatment = pd.read_csv(treatmentarrayfile, sep=',', skiprows=4, index_col=0)\n\n# Uncomment the lines below to inspect the first few rows of each dataframe\n#control.head()\n#treatment.head()\n\nlen(control)", "<div class=\"alert alert-warning\">\nWe reduce the full dataset to only the raw intensity values. We also rename the columns in each of the `control` and `treatment` dataframes. \n</div>\n\nIn both control and treatment datasets, the mapping of experimental samples (input and output) across the three replicates is:\n\nreplicate 1 input: Raw $\\rightarrow$ input.1\nreplicate 1 output: Raw.1 $\\rightarrow$ output.1\nreplicate 2 input: Raw.2 $\\rightarrow$ input.2\nreplicate 2 output: Raw.3 $\\rightarrow$ output.2\nreplicate 3 input: Raw.4 $\\rightarrow$ input.3\nreplicate 3 output: Raw.5 $\\rightarrow$ output.3", "colnames_in = ['Raw', 'Raw.1', 'Raw.2', 'Raw.3', 'Raw.4', 'Raw.5'] # raw data columns\ncolnames_out = ['input.1', 'output.1', 'input.2', 'output.2', 'input.3', 'output.3'] # renamed raw data columns\n\n# Reduce control and treatment arrays to raw data columns only\ncontrol = control[colnames_in]\ncontrol.columns = colnames_out\ntreatment = treatment[colnames_in]\ntreatment.columns = colnames_out", "Data QA <a id=\"data_qa\"></a>\nWe expect that there is good agreement between input and output raw intensities for each replicate control or treatment experiment. We also expect that there should be good agreement across replicates within the controls, and within the treatment. We inspect this agreement visually with a matrix of scatterplots, below.\nThe plot_correlation() function can be found in the accompanying tools.py module.", "# Plot correlations for control data\ntools.plot_correlation(control);", "There is good visual correlation between the intensities for the control arrays, and the Spearman's R values also indicate good correlation.", "# Plot correlations for treatment data\ntools.plot_correlation(treatment);", "There is - mostly - good visual correlation between the intensities for the control arrays, and the Spearman's R values also indicate good correlation. There appear to be three problematic probes in replicate 3 that we may need to deal with in the data cleanup.\n<div class=\"alert alert-success\">\n<b>Taken together, these plots indicate:</b>\n<ul>\n<li> the intensities of the control arrays are systematically larger than intensities for the treatment arrays, suggesting that the effects of noise may be proportionally greater for the treatment arrays. This might be a concern for reliably inferring enrichment or depletion in the treatment.\n<li> the control arrays are good candidates for quantile normalisation (QN; $r > 0.95$, with similar density distributions)\n<li> the treatment array `input.3` dataset is potentially problematic, due to three treatment probe datapoints with intensities greater than 40,000 units having large leverage.\n</ul>\n</div>\n\nProblematic probes <a id=\"problem_probes\"></a>\n<div class=\"alert-warning\">\nWe can readily identify problematic probes in treatment replicate 3, as they are the only probes with intensity greater than 40,000.\n\nThe problematic probes are:\n<ul>\n <li> <code>A_07_P000070</code>\n <li> <code>A_07_P061472</code>\n <li> <code>A_07_P052489</code>\n</ul>\n</div>", "# Select outlying treatment input.3 values\ntreatment.loc[treatment['input.3'] > 4e4]\n\n# Define problem probes:\nproblem_probes = list(treatment.loc[treatment['input.3'] > 4e4].index)", "Interpolating values for problem probes <a id=\"interpolation\"></a>\nWe replace the three clear outlying values for the three problematic probes in input.3 of the treatment array with interpolated values. We assume that input.1 and input.2 are typical of the input intensities for these three probes, and take the average of their values to substitute for input.3 for each.", "# Interpolate values \ntreatment.set_value(index=problem_probes, col='input.3',\n value=treatment.loc[problem_probes][['input.1', 'input.2']].mean(1))\ntreatment.loc[problem_probes]", "We can visualise the change in correlation for the treatment dataframe that results:", "# Plot correlations for treatment data\ntools.plot_correlation(treatment);", "Normalisation <a id=\"normalisation\"></a>\nWe expect the array intensity distribution to vary according to whether the sample was from the input (strong) or output (weak) set, and whether the sample came from the control or treatment pools. We therefore divide the dataset into four independently-normalised components:\n\ncontrol_input\ncontrol_output\ntreatment_input\ntreatment_output\n\n<br /><div class=\"alert-success\">\nWe have established that because the input and output arrays in both control and treatment conditions have strong correlation across all intensities, and have similar intensity distributions, we are justified in using quantile (mean) normalisation.\n</div>", "input_cols = ['input.1', 'input.2', 'input.3'] # input columns\noutput_cols = ['output.1', 'output.2', 'output.3'] # output columns\n\n# Normalise inputs and outputs for control and treatment separately\ncontrol_input = tools.quantile_norm(control, columns=input_cols)\ncontrol_output = tools.quantile_norm(control, columns=output_cols)\ntreatment_input = tools.quantile_norm(treatment, columns=input_cols)\ntreatment_output = tools.quantile_norm(treatment, columns=output_cols)", "We visualise the resulting distributions, in violin plots:", "# Make violinplots of normalised data \ntools.plot_normalised(control_input, control_output,\n treatment_input, treatment_output)", "<div class=\"alert-success\">\nThese plots illustrate that there is relative reduction in measured array intensity between control and treatment arrays for both the input and output arrays.\n</div>\n\nWide to long form <a id=\"wide_to_long\"></a>\nWe have four dataframes containing normalised data:\n\ncontrol_input\ncontrol_output\ntreatment_input\ntreatment_output\n\nEach dataframe is indexed by the array probe systematic name, with three columns that correspond to replicates 1, 2, and 3 for either a control or a treatment run. For downstream analysis we want to organise this data as the following columns:\n\nindex: unique ID\nprobe: probe name (these apply across treatment/control and input/output)\ninput: normalised input intensity value (for a particular probe and replicate)\noutput: normalised input intensity value (for a particular probe and replicate)\ntreatment: 0/1 indicating whether the measurement was made for the control or treatment sample\nreplicate: 1, 2, 3 indicating which replicate the measurement was made from\n\n<br /><div class=\"alert-warning\">\nWe will add other columns with relevant data later, and to enable this, we convert the control and treatment data frames from wide (e.g. input.1, input.2, input.3 columns) to long (e.g. probe, input, output, replicate) form - once for the control data, and once for the treatment data. We match on a multi-index of probe and replicate.\n</div>", "# Convert data from wide to long form\ndata = tools.wide_to_long(control_input, control_output,\n treatment_input, treatment_output)\ndata.head()", "Long form data has some advantages for melting into new arrangments for visualisation, analysis, and incorporation of new data. For instance, we can visualise the distributions of input and output log intensities against each other, as below:", "# Visualise input v output distributions\ntools.plot_input_output_violin(data)", "<div class=\"alert-success\">\nThis visualisation again shows that treatment intensities are generally lower than control intensities, but also suggests that the bulk of output intensities are lower than input intensities.\n<br /><br />\nThere is a population of low-intensity values for each set of arrays, however. These appear to have a slight increase in intensity in the output, compared to input arrays.\n</div>\n\nProbe matches to Sakai and DH10B <a id=\"probe_matches\"></a>\n<div class=\"alert-warning\">\nEvidence for potential hybridisation of probes to DH10B or Sakai isolates was determined by default `BLASTN` query of each probe sequence against chromosome and plasmid feature nucleotide sequences from the NCBI records:\n\n<ul>\n<li> `GCF_000019425.1_ASM1942v1_cds_from_genomic.fna`\n<li> `GCF_000008865.1_ASM886v1_cds_from_genomic.fna`\n</ul>\n</div>\n\n$ blastn -query Array/probe_seqlist.fas -subject Sakai/GCF_000008865.1_ASM886v1_cds_from_genomic.fna -outfmt 6 -out probes_blastn_sakai.tab -perc_identity 100\n$ blastn -query Array/probe_seqlist.fas -subject DH10B/GCF_000019425.1_ASM1942v1_cds_from_genomic.fna -outfmt 6 -out probes_blastn_dh10b.tab -perc_identity 100\nWe first identify the probes that match uniquely at 100% identity to a single E. coli gene product from either Sakai or DH10B", "# BLASTN results files\nsakai_blastfile = os.path.join('..', 'data', 'probes_blastn_sakai.tab')\ndh10b_blastfile = os.path.join('..', 'data', 'probes_blastn_dh10b.tab')\n\n# Obtain a dataframe of unique probes and their BLASTN matches\nunique_probe_hits = tools.unique_probe_matches((sakai_blastfile, dh10b_blastfile))", "We then add parent gene annotations to the unique probes:", "# Sequence data files\nsakai_seqfile = os.path.join('..', 'data', 'Sakai', 'GCF_000008865.1_ASM886v1_cds_from_genomic.fna')\ndh10b_seqfile = os.path.join('..', 'data', 'DH10B', 'GCF_000019425.1_ASM1942v1_cds_from_genomic.fna')\n\n# Add locus tag information to each unique probe\nunique_probe_hits = tools.annotate_seqdata(unique_probe_hits, (sakai_seqfile, dh10b_seqfile))", "<div class=\"alert-danger\">\nWe will certainly be interested in probes that hybridise unambiguously to Sakai or to DH10B. The [array was however designed to report on several *E. coli* isolates](http://www.ebi.ac.uk/arrayexpress/arrays/A-GEOD-13359/?ref=E-GEOD-46455), and not all probes should be expected to hybridise, so we could consider the non-uniquely matching probes not to be of interest, and censor them.\n<br /><br />\nA strong reason to censor probes is that we will be estimating locus tag/gene-level treatment effects, on the basis of probe-level intensity measurements. Probes that may be reporting on multiple genes may mislead our model fit, and so are better excluded.\n</div>\n\nWe exclude non-unique matching probes by performing an inner join between the data and unique_probe_hits dataframes.", "censored_data = pd.merge(data, unique_probe_hits[['probe', 'match', 'locus_tag']],\n how='inner', on='probe')\ncensored_data.head()", "<div class=\"alert-success\">\nThis leaves us with a dataset comprising:\n\n<ul>\n<li> 49872 datapoints (rows)\n<li> 8312 unique probes\n<li> 6084 unique locus tags\n</ul>\n</div>\n\nAs can be seen in the violin plot below, censoring the data in this way removes a large number of low-intensity probes from all datasets.", "# Visually inspect the effect of censoring on distribution\ntools.plot_input_output_violin(censored_data)", "Write data <a id=\"write\"></a>\n<div class=\"alert-warning\">\n<b>We write the censored, normalised, long-format data to the `datasets/` subdirectory.</b>\n</div>", "# Create output directory\noutdir = 'datasets'\nos.makedirs(outdir, exist_ok=True)\n\n# Output files\nfull_dataset = os.path.join(outdir, \"normalised_array_data.tab\") # all censored data\nreduced_probe_dataset = os.path.join(outdir, \"reduced_probe_data.tab\") # subset of data grouped by probe\nreduced_locus_dataset = os.path.join(outdir, \"reduced_locus_data.tab\") # subset of data grouped by locus tag", "For modelling with Stan, we assign indexes for common probe ID, locus tag, and array (combination of replicate and treatment) to each probe, before writing out the complete dataset.", "# Index on probes\nindexed_data = tools.index_column(censored_data, 'probe')\n\n# Index on locus tags\nindexed_data = tools.index_column(indexed_data, 'locus_tag')\n\n# Index on array (replicate X treatment)\nindexed_data = tools.index_column(indexed_data, 'repXtrt')\n\n# Uncomment the line below to inspect the data\n#indexed_data.head(20)\n\n# Write the full dataset to file\nindexed_data.to_csv(full_dataset, sep=\"\\t\", index=False)", "For testing, we want to create two data subsets, one containing a reduced number of probes, and one with a reduced number of genes/locus tags.", "# Reduced probe set\nreduced_probes = tools.reduce_dataset(indexed_data, 'probe')\nreduced_probes.to_csv(reduced_probe_dataset, sep=\"\\t\", index=False)\n\n# Reduced locus tag set\nreduced_lts = tools.reduce_dataset(indexed_data, 'locus_tag')\nreduced_lts.to_csv(reduced_locus_dataset, sep=\"\\t\", index=False)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
CrowdTruth/CrowdTruth-core
tutorial/notebooks/Sparse Multiple Choice Task - Relation Extraction.ipynb
apache-2.0
[ "CrowdTruth for Sparse Multiple Choice Tasks: Relation Extraction\nIn this tutorial, we will apply CrowdTruth metrics to a sparse multiple choice crowdsourcing task for Relation Extraction from sentences. The workers were asked to read a sentence with 2 highlighted terms, then pick from a multiple choice list what are the relations expressed between the 2 terms in the sentence. The options available in the multiple choice list change with the input sentence. The task was executed on FigureEight. For more crowdsourcing annotation task examples, click here.\nTo replicate this experiment, the code used to design and implement this crowdsourcing annotation template is available here: template, css, javascript. \nThis is a screenshot of the task as it appeared to workers:\n\nA sample dataset for this task is available in this file, containing raw output from the crowd on FigureEight. Download the file and place it in a folder named data that has the same root as this notebook. Now you can check your data:", "import pandas as pd\n\ntest_data = pd.read_csv(\"../data/relex-sparse-multiple-choice.csv\")\ntest_data.head()", "Declaring a pre-processing configuration\nThe pre-processing configuration defines how to interpret the raw crowdsourcing input. To do this, we need to define a configuration class. First, we import the default CrowdTruth configuration class:", "import crowdtruth\nfrom crowdtruth.configuration import DefaultConfig", "Our test class inherits the default configuration DefaultConfig, while also declaring some additional attributes that are specific to the Relation Extraction task:\n\ninputColumns: list of input columns from the .csv file with the input data\noutputColumns: list of output columns from the .csv file with the answers from the workers\nannotation_separator: string that separates between the crowd annotations in outputColumns\nopen_ended_task: boolean variable defining whether the task is open-ended (i.e. the possible crowd annotations are not known beforehand, like in the case of free text input); in the task that we are processing, workers pick the answers from a pre-defined list, therefore the task is not open ended, and this variable is set to False\nannotation_vector: list of possible crowd answers, mandatory to declare when open_ended_task is False; for our task, this is the list of all relations that were given as input to the crowd in at least one sentence\nprocessJudgments: method that defines processing of the raw crowd data; for this task, we process the crowd answers to correspond to the values in annotation_vector\n\nThe complete configuration class is declared below:", "class TestConfig(DefaultConfig):\n inputColumns = [\"sent_id\", \"term1\", \"b1\", \"e1\", \"term2\", \"b2\", \"e2\", \"sentence\", \"input_relations\"]\n outputColumns = [\"output_relations\"]\n \n annotation_separator = \"\\n\"\n \n # processing of a closed task\n open_ended_task = False\n annotation_vector = [\n \"title\", \"founded_org\", \"place_of_birth\", \"children\", \"cause_of_death\",\n \"top_member_employee_of_org\", \"employee_or_member_of\", \"spouse\",\n \"alternate_names\", \"subsidiaries\", \"place_of_death\", \"schools_attended\",\n \"place_of_headquarters\", \"charges\", \"origin\", \"places_of_residence\",\n \"none\"]\n \n def processJudgments(self, judgments):\n # pre-process output to match the values in annotation_vector\n for col in self.outputColumns:\n # transform to lowercase\n judgments[col] = judgments[col].apply(lambda x: str(x).lower())\n return judgments", "Pre-processing the input data\nAfter declaring the configuration of our input file, we are ready to pre-process the crowd data:", "data, config = crowdtruth.load(\n file = \"../data/relex-sparse-multiple-choice.csv\",\n config = TestConfig()\n)\n\ndata['judgments'].head()", "Computing the CrowdTruth metrics\nThe pre-processed data can then be used to calculate the CrowdTruth metrics:", "results = crowdtruth.run(data, config)", "results is a dict object that contains the quality metrics for sentences, relations and crowd workers.\nThe sentence metrics are stored in results[\"units\"]:", "results[\"units\"].head()", "The uqs column in results[\"units\"] contains the sentence quality scores, capturing the overall workers agreement over each sentence. Here we plot its histogram:", "import matplotlib.pyplot as plt\n%matplotlib inline\n\nplt.hist(results[\"units\"][\"uqs\"])\nplt.xlabel(\"Sentence Quality Score\")\nplt.ylabel(\"Sentences\")", "The unit_annotation_score column in results[\"units\"] contains the sentence-relation scores, capturing the likelihood that a relation is expressed in a sentence. For each sentence, we store a dictionary mapping each relation to its sentence-relation score.", "results[\"units\"][\"unit_annotation_score\"].head(10)", "The worker metrics are stored in results[\"workers\"]:", "results[\"workers\"].head()", "The wqs columns in results[\"workers\"] contains the worker quality scores, capturing the overall agreement between one worker and all the other workers.", "plt.hist(results[\"workers\"][\"wqs\"])\nplt.xlabel(\"Worker Quality Score\")\nplt.ylabel(\"Workers\")", "The relation metrics are stored in results[\"annotations\"]. The aqs column contains the relation quality scores, capturing the overall worker agreement over one relation.", "results[\"annotations\"]\n\nresults[\"units\"].to_csv(\"../data/results/sparsemultchoice-relex-units.csv\")\nresults[\"workers\"].to_csv(\"../data/results/sparsemultchoice-relex-workers.csv\")\nresults[\"annotations\"].to_csv(\"../data/results/sparsemultchoice-relex-annotations.csv\")", "To further explore the CrowdTruth quality metrics, download the aggregation results in .csv format for:\n\nunits\nworkers\nannotations" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
nordam/TFY4305
Notebooks/ODE.ipynb
gpl-3.0
[ "%matplotlib inline\nimport numpy as np\nfrom matplotlib import pyplot as plt\n# nicer looking default plots\nplt.style.use('bmh')\nfrom time import time", "Example 1 - Forward Euler\nConsider first the ODE\n$$ \\dot{x} = x $$\nThis has analytic solution\n$$ x(t) = x_0\\mathrm{e}^t $$\nwhere $$x_0 = x(t=0)$$", "def f(x, t):\n return x\n\n# Initial conditions\nx = 1/2\nt = 0\nTmax = 10\n# Timestep\nh = 0.001\n\n# Keep list of trajectories and times for plotting\nXs = [x]\nTs = [t]\nwhile t < Tmax:\n # At each step, use derivative at that position\n x = x + h*f(x, t)\n # Increment time\n t += h\n # Store time and position\n Ts.append(t)\n Xs.append(x)\n\nfig = plt.figure(figsize = (12,6))\n\n# Plot numerical solution\nplt.plot(Ts, Xs, marker = 'o', label = 'Numerical')\n\n# Plot analytic solution\nx0 = Xs[0]\n# Define an array of times at high resolution\nts = np.linspace(Ts[0], Ts[-1], 1000)\nplt.plot(ts, x0*np.exp(ts), '--', c = 'k', label = 'Exact')\nplt.xlabel('Time')\nplt.ylabel('x(t)')\nplt.legend(loc = 'upper left', fontsize = 20)", "Example 2 - Better coding practice\nand also comparison between Forward Euler and 4th-order Runge-Kutta\n\nImplement integrator to take f as an argument\nUse consistent call signature for f\n\nMake a function that will take f and an integrator, and step forward in time until Tmax\n\n\nAlso: Try modifying the timestep, and note how much faster the 4th-order Runge-Kutta converges compared to the 1st-order Euler method", "#####################\n#### Integrators ####\n#####################\n\n# The forward Euler method\ndef euler(x, t, h, f):\n # x is coordinates (as a vector)\n # h is timestep\n # f(x) is a function that returns the derivative\n # \"Slopes\"\n k1 = f(x, t)\n # Update time and position\n x_ = x + h*k1\n return x_\n\n# Heun's Method\ndef rk2(x, t, h, f):\n # x is coordinates (as a vector)\n # h is timestep\n # f(x) is a function that returns the derivative\n # \"Slopes\"\n k1 = f(x, t)\n k2 = f(x + k1*h, t + h)\n # Update time and position\n x_ = x + h*(k1 + k2)/2\n return x_\n\n# Kutta's method\ndef rk3(x, t, h, f):\n # x is coordinates (as a vector)\n # h is timestep\n # f(x) is a function that returns the derivative\n # \"Slopes\"\n k1 = f(x, t)\n k2 = f(x + k1*h/2, t + h/2)\n k3 = f(x - k1*h + 2*k2*h, t + h)\n # Update time and position\n x_ = x + h*(k1 + 4*k2 + k3)/6\n return x_\n\n# 4th-order Runge-Kutta\ndef rk4(x, t, h, f):\n # x is coordinates (as a vector)\n # h is timestep\n # f(x) is a function that returns the derivative\n # \"Slopes\"\n k1 = f(x, t)\n k2 = f(x + k1*h/2, t + h/2)\n k3 = f(x + k2*h/2, t + h/2)\n k4 = f(x + k3*h, t + h)\n # Update time and position\n x_ = x + h*(k1 + 2*k2 + 2*k3 + k4)/6\n return x_\n\n###########################\n#### Utility functions ####\n###########################\n\ndef trajectory(X0, T0, Tmax, h, f, integrator):\n # Number of timesteps\n Nt = int((Tmax) / h)\n # Add 2 for initial position and fractional step at end\n # X0.size lets X hold Nt+2 arrays of the same size as X0\n X0 = np.array(X0)\n X = np.zeros((Nt+2, X0.size))\n T = np.zeros(Nt+2)\n # Initialise\n X[0,:] = X0\n T[0] = T0\n # Loop over timesteps\n t = T0\n for i in range(Nt+1):\n # Make sure the last step stops exactly at Tmax\n h = min(h, Tmax - t)\n # Calculate next position\n X[i+1,:] = integrator(X[i,:], t, h, f)\n T[i+1] = T[i] + h\n # Increment time\n t += h\n return X, T\n\ndef f(x, t):\n return x\n\n# Initial conditions\nx0 = 1/2\nt0 = 0\nTmax = 10\n# Timestep\nh = 0.5\n\n# The integrators and the function trajectory are implemented\n# at the top of the notebook\nX_euler, Ts = trajectory(x0, t0, Tmax, h, f, euler)\nX_rk4, Ts = trajectory(x0, t0, Tmax, h, f, rk4)\n\n# Make a figure\nfig = plt.figure(figsize = (12,6))\n\n# Plot numerical solutions\nplt.plot(Ts, X_euler, label = 'Euler')\nplt.plot(Ts, X_rk4, label = 'RK4')\n\n# Plot analytic solution\n# Define an array of times at high resolution\nts = np.linspace(Ts[0], Ts[-1], 1000)\nx0 = Xs[0]\nplt.plot(ts, x0*np.exp(ts), '--', c = 'k', label = 'Exact')\n\n# Labels\nplt.xlabel('Time')\nplt.ylabel('x(t)')\nplt.legend(loc = 'upper left', fontsize = 20)", "Example 3 - Error as function of timestep\nTo look at error as a function of timestep:\n* Calculate trajectory for many different timesteps\n* Calculate error as $x(t_N) - x_N$, where $N$ is the total number of timesteps and $x(t_N)$ is the exact solution at $t_N$.\n* Plot on log-log scale, and add straight lines proportiona to $h$ and $h^4$ to compare slope\n* The reason the error doesn't get smaller than about $10^{-12}$ in this case is due to limited precision in floating point numbers, and the large number of steps for the shorter timesteps", "def f(x, t):\n return x\n\n# Initial conditions\nx0 = 1/2\nt0 = 0\nTmax = 10\n\n# Define Nh logarithmically spaced timesteps from 0.0001 to 1\nNh = 50\ntimesteps = np.logspace(-4, 0, Nh)\n\n# For each of those timesteps, calculate the endpoint of the trajectory\nXe_euler = np.zeros(Nh)\nXe_rk4 = np.zeros(Nh)\nfor i, h in enumerate(timesteps):\n Xs, Ts = trajectory(x0, t0, Tmax, h, f, euler )\n Xe_euler[i] = Xs[-1]\n Xs, Ts = trajectory(x0, t0, Tmax, h, f, rk4 )\n Xe_rk4[i] = Xs[-1]\n\n \n# Analytic solution\nXact = x0*np.exp(Tmax)\n# Calculate error, normalised by exact solution\nerr_euler = np.abs(Xe_euler - Xact) / Xact\nerr_rk4 = np.abs(Xe_rk4 - Xact) / Xact\n\nfig = plt.figure(figsize = (12,6))\n# Plot error as function of timesteps\n# And plot straight lines to show slope\nl, = plt.plot(timesteps, err_euler, marker = '.', label = 'Euler')\nplt.plot(timesteps, 4.0*timesteps**1, '--', c = l.get_color(), label = '$\\sim h^1$')\nl, = plt.plot(timesteps, err_rk4, marker = '.', label = 'RK4')\nplt.plot(timesteps, 0.15*timesteps**4, '--', c = l.get_color(), label = '$\\sim h^4$')\n\nplt.legend(loc = 'lower right', fontsize = 20)\nplt.xlabel('Timestep')\nplt.ylabel('Normalised error')\n\n# Logscale\nplt.xscale('log')\nplt.yscale('log')", "Example 4 - Restricted three-body problem\nThis example is taken from Solving Ordinary Differential Equations, vol I by Hairer, Nørsett and Wanner, beginning of Chapter II. You can download the book as a free pdf from Springer if you are on the NTNU network:\nhttp://link.springer.com/book/10.1007%2F978-3-540-78862-1\nThe system is the gravitational three-body problem, for a system made up of the Earth, the Moon and a spacecraft, and with the simplification that the motion of the Earth and Moon are unaffected by the spacecraft (which seems reasonable). The equations are given in dimensionless form.\nThe equations are given as second order equations for the two components of the position vector:\n$$ \\ddot{y_1} = y_1 + 2\\dot{y_2} - \\mu' \\frac{y_1 + \\mu}{D_1} - \\mu\\frac{y_1 - \\mu'}{D_2}$$\n$$ \\ddot{y_2} = y_2 + 2\\dot{y_1} - \\mu' \\frac{y_2}{D_1} - \\mu\\frac{y_1}{D_2}$$\n$$ D_1 = \\left( (y_1 + \\mu)^2 + y_2^2\\right)^{3/2} $$\n$$ D_1 = \\left( (y_1 - \\mu')^2 + y_2^2\\right)^{3/2} $$\n$$ \\mu = 0.012277471 $$\n$$ \\mu' = 1 - \\mu. $$\nWith the initial conditions\n$$ y_1(0) = 0.994 $$\n$$ \\dot{y_1}(0) = 0 $$\n$$ y_2(0) = 0 $$\n$$ \\dot{y_2}(0) = -2.00158520637908252240537862224, $$\nthese equations will exhibit a periodic solution with period\n$$ T = 17.0652165601579625588917206249. $$\nThe point of the example is that the trajectory changes quickly close to the Moon, and less quickly elsewhere. However, since we must choose the timestep short enough to capture the dynamics close to the Moon, we are forced to use an excessively short timestep for the rest of the orbit as well, unless we use a method with adaptive timestep.\nBelow, we first define the function fa(x, t) which implements the above equations, rewritten into a system of four first-order ODEs. We then integrate the trajectories using the 4th-order Runge-Kutta method, before moving on to variable timestep methods.", "def fa(X, t):\n # Example taken from beginning of Chapter II in\n # Hairer, Nørsett, Wanner\n # Solving Ordinary Differential Equations, vol I\n # X[0] = y1\n # X[1] = y1dot\n # X[2] = y2\n # X[3] = y2dot\n # Constants\n mu = 0.012277471\n mu_ = 1 - mu\n # Variable parameters\n D1 = ((X[0] + mu )**2 + X[2]**2)**(3/2)\n D2 = ((X[0] - mu_)**2 + X[2]**2)**(3/2)\n # Derivatives\n dX0 = X[1]\n dX1 = X[0] + 2*X[3] - mu_*(X[0] + mu)/D1 - mu*(X[0] - mu_)/D2\n dX2 = X[3]\n dX3 = X[2] - 2*X[1] - mu_*X[2]/D1 - mu*X[2]/D2\n return np.array([dX0, dX1, dX2, dX3])\n \n \nt = 0\nT = 17.06521656015796\nX0 = np.array([\n 0.994, # y1(0)\n 0.0, # y1'(0)\n 0.0, # y2(0)\n -2.001585106379082522405 # y2'(0)\n ])\n\n\n# Intergrate for a duration equal to 2T.\n# If the error after the first orbit is too large,\n# the second orbit will be completely off.\n# Try experimenting with the timestep.\nh = 5e-4\n\n# Also, measure the time of the calculation\ntic = time()\nXs, Ts = trajectory(X0, t, 2*T, h, fa, rk4)\ntoc = time()\nprint('Number of steps: ', len(Ts))\nprint('Simulation took ', toc - tic, ' seconds')\n\nfig = plt.figure(figsize = (12, 6))\nplt.plot(Xs[:,0], Xs[:,2])", "Example 5 - Variable timestep\nBelow is an example of a very straightforward implementation of a variable timestep code. It makes two estimates of the next position, compares the two, and assumes that the error is related to the difference. If the difference is small, the timestep is probably short enough, if the difference is large, we should reduce the timestep.\nA more advanced implementation is shown further down.", "#######################################\n#### Variable stepsize integrators ####\n#######################################\n\ndef rk43(x, t, h, f, atol = 1e-4, rtol = 1e-4):\n # Calculate 3rd and 4th order prediction\n x3 = rk3(x, t, h, f)\n x4 = rk4(x, t, h, f)\n # Error is related to difference between x3 and x4\n # Choosing here to use norm of difference divided by norm of x4\n # Other measures of error exists\n # rtol is relative tolerance\n # atol is absolute tolerance\n sc = rtol*np.sum(np.sqrt(x4**2)) + atol\n err = np.sum(np.sqrt((x3 - x4)**2)) / sc\n if err < 1:\n # Step is accepted\n # Use 4th order as next position and update time\n x_ = x4\n t_ = t + h\n # Try increasing timestep a bit\n h_ = 1.5*h\n else:\n # Step is rejected\n # Do not update time and position\n x_ = x\n t_ = t\n # Try decreasing timestep a bit\n h_ = 0.5*h\n return x_, t_, h_\n\n\n#############################################\n#### Function for calculating trajectory ####\n#############################################\n\ndef variable_step_trajectory(X0, T0, Tmax, h, f, integrator, tol = 1e-3):\n # In this case, number of steps is not known beforehand.\n # If we want to plot the trajectory, there are two simple options:\n # 1: Specify an output timestep, and store that often\n # 2: Store all steps in a list that grows \n # We'll go for 2, since that allows us to visualise the steplengths,\n X = [X0]\n T = [0.0]\n t = 0\n rejected = 0\n while t < Tmax:\n # Make sure last step doesn't take us past Tmax\n h = min(h, Tmax - t)\n # Integrator now returns not only x, but also h and t\n # Overwrite h, but store x_ and t_ in temporary variables\n x_, t_, h = integrator(X[-1], t, h, f, atol = tol, rtol = tol)\n # Only store x_ if step was accepted (in which case t_ > t)\n if t_ > t:\n X.append(x_)\n T.append(t_)\n t = t_\n else:\n rejected += 1\n # Now we must return t as well, since h is variable\n # Convert to array before returning\n return np.array(X), np.array(T), rejected\n\nt = 0\nT = 17.06521656015796\nX0 = np.array([\n 0.994, # y1(0)\n 0.0, # y1'(0)\n 0.0, # y2(0)a\n -2.001585106379082522405 # y2'(0)\n ])\n\n\n# Starting timestep\nh0 = 1e-3\n# Again integrating two orbits. Compare number of steps to R-K 4 above.\ntic = time()\nXs, Ts, R = variable_step_trajectory(X0, t, 2*T, h0, fa, rk43, tol = 2e-6)\ntoc = time()\nprint('Number of steps: ', len(Ts))\nprint('Simulation took ', toc - tic, ' seconds')\nprint('Number of rejected steps: ', R)\n\nfig = plt.figure(figsize = (12, 8))\nplt.plot(Xs[:,0], Xs[:,2])#, marker = '.')\n\n# Plot steplengths as function of time\nhs = Ts[1:] - Ts[:-1]\n\nfig = plt.figure(figsize = (12, 6))\nplt.plot(Ts[1:], hs)\nplt.ylabel('Timestep')\nplt.xlabel('Time')", "Example 6 - Dormand and Prince 5(4)\nThis example includes an implementation of the Dormand-Prince method, which is a method that makes one 5th-order and one 4th-order prediction of the next step, using only 7 evaluations of $f(x,t)$, and uses the 5th-order prediction as the estimate of the next point.\nStepsize control is based on a recipe from Solving Ordinary Differential Equations, vol I by Hairer, Nørsett and Wanner, page 167-168 (see link further up). It uses the error and the current timestep to calculate the optimal timestep, i.e., the timestep that would produce an error exactly matching the tolerance. It then sets the sets the timestep a little smaller than this. The result is a quite efficient method where fewer steps are rejected than the simpler approach above.", "def dopri5(x, t, h, f, atol = 1e-6, rtol = 1e-6):\n # x and t are coordinates\n # h is timestep\n # f(t, x) is a function that returns the derivative\n \n # Nodes\n c1 = 0\n c2 = 1./5.\n c3 = 3./10.\n c4 = 4./5.\n c5 = 8./9.\n c6 = 1.\n c7 = 1.\n # Matrix elements\n a21 = 1./5.\n a31 = 3./40.\n a32 = 9./40.\n a41 = 44./45.\n a42 = -56./15.\n a43 = 32./9.\n a51 = 19372./6561.\n a52 = -25360./2187.\n a53 = 64448./6561.\n a54 = -212./729.\n a61 = 9017./3168.\n a62 = -355./33.\n a63 = 46732./5247.\n a64 = 49./176.\n a65 = -5103./18656.\n a71 = 35./384.\n a72 = 0.\n a73 = 500./1113.\n a74 = 125./192.\n a75 = -2187./6784.\n a76 = 11./84.\n # Fourth order weights\n b41 = 5179./57600.\n b42 = 0.\n b43 = 7571./16695.\n b44 = 393./640.\n b45 = -92097./339200.\n b46 = 187./2100.\n b47 = 1./40.\n # Fifth order weights\n b51 = 35./384.\n b52 = 0.\n b53 = 500./1113.\n b54 = 125./192.\n b55 = -2187./6784.\n b56 = 11./84.\n b57 = 0.\n \n # \"Slopes\"\n k1 = f( x, t + c1*h )\n k2 = f( x + a21*h*k1, t + c2*h )\n k3 = f( x + a31*h*k1 + a32*h*k2, t + c3*h )\n k4 = f( x + a41*h*k1 + a42*h*k2 + a43*h*k3, t + c4*h )\n k5 = f( x + a51*h*k1 + a52*h*k2 + a53*h*k3 + a54*h*k4, t + c5*h )\n k6 = f( x + a61*h*k1 + a62*h*k2 + a63*h*k3 + a64*h*k4 + a65*h*k5, t + c6*h )\n k7 = f( x + a71*h*k1 + a72*h*k2 + a73*h*k3 + a74*h*k4 + a75*h*k5 + a76*h*k6, t + c7*h )\n\n # Calculate fourth and fifth order prediction of new point\n x4 = x + h*(k1*b41 + k2*b42 + k3*b43 + k4*b44 + k5*b45 + k6*b46 + k7*b47)\n x5 = x + h*(k1*b51 + k2*b52 + k3*b53 + k4*b54 + k5*b55 + k6*b56 + k7*b57)\n \n # Implementing error checking and variable stepsize roughly as in\n # Hairer, Nørsett and Wanner:\n # Solving ordinary differential equations I -- Nonstiff problems\n # pages 167 and 168 in the 2008 printing\n\n # these are 4th and 5th order methods, q = min(4, 5)\n q = 4.\n sc = np.maximum(np.abs(x4), np.abs(x5)) * rtol + atol\n err = np.amax(np.sqrt(((x4 - x5) / sc)**2))\n # parameters limiting change in timestep\n fac = 0.8\n maxfac = 2.5\n # Calculating optimal h\n # If err happens to be 0 (can happen, depending on problem)\n # then hopt = Infinity. Set some lower limit.\n if err < 1e-21:\n err = 1e-21\n h_opt = h * (1./err) ** (1./(q+1.))\n if err <= 1.0:\n # Step is accepted:\n # Use fifth order result as next position\n x_ = x5\n t_ = t + h\n # Increase steplength somewhat less than predicted, to\n # make it likely the next step is accepted\n h_ = min(maxfac * h, fac * h_opt)\n else:\n # Step is rejected:\n # Position and time is not updated\n x_ = x\n t_ = t\n # Decrease steplength\n h_ = fac * h_opt\n return x_, t_, h_\n\nt = 0\nT = 17.06521656015796\nX0 = np.array([\n 0.994, # y1(0)\n 0.0, # y1'(0)\n 0.0, # y2(0)a\n -2.001585106379082522405 # y2'(0)\n ])\n\n# Starting timestep\nh0 = 1e-3\n# Again integrating two orbits. Compare number of steps to R-K 4 above.\ntic = time()\nXs, Ts, R = variable_step_trajectory(X0, t, 2*T, h0, fa, dopri5, tol = 2e-6)\ntoc = time()\nprint('Number of steps: ', len(Ts))\nprint('Simulation took ', toc - tic, ' seconds')\nprint('Number of rejected steps: ', R)\n\n\nfig = plt.figure(figsize = (12, 8))\n# Include markers a each point to illustrate stepsize\nplt.plot(Xs[:,0], Xs[:,2])#, marker = '.')\n\n# Plot steplengths as function of time\nhs = Ts[1:] - Ts[:-1]\n\nfig = plt.figure(figsize = (12, 8))\nplt.plot(Ts[1:], hs)\nplt.ylabel('Timestep')\nplt.xlabel('Time')", "Example 7 - Stiff equations\nThe idea here is to compare two equations that predict almost exactly equal trajectories, but with very different numerical properties.\nConsider first an equation that discribes a trajectory moving towards $x=0$, with speed proportional to the distance:\n$$\\dot{x} = v(x),$$\nwhere\n$$v(x) = -x.$$\nConsider next an equation that discribes a trajectory that experiences acceleration if the speed deviates from $v(x)$, proportional to the difference:\n$$\\ddot{x} = \\alpha (v(x) - \\dot{x}) $$\nagain with\n$$v(x) = -x.$$\nThe physical interpretation can be in the first case a particle that moves with the velocity given by $v(x)$, and in the second case of a particle that experiences a force, which will tend to make it move with the velocity given by $v(x)$. In this case, $\\alpha$ plays the role of a coupling coefficient.\nIf $\\alpha$ is small, the second trajectory will oscillate towards $x=0$, if $\\alpha$ is large, the second trajectory will almost immediately reach the velocity given by $v(x)$, and thereafter decay exponentially towards $x=0$, just like in the first case.\nBelow, we have implemented the two cases as different functions, f1(x, t) and f2(x, t), and we integrate the trajectories and compare the behaviour.\nThings to note:\n* Initially, f2 is integrated with a much shorter timestep than f1, and the trajectories look identical.\n* Try increasing the timestep of f2, and explain what happens\n* The reason we need a shorter timestep for f2 is because the acceleration happens quickly, and we need to resolve the acceleration to get the velocity and position right, even if we are really only interested in the position.\nA system of equation such as case 2, where we need a timestep that is much much shorter than the timescale at which we are interested in the dynamics, is an example of a stiff system of equations.", "def v(x):\n return -x\n\ndef f1(x, t):\n return v(x)\n\ndef f2(X, t):\n # x[0] = x\n # x[1] = xdot\n alpha = 1e3\n dX = np.zeros(2)\n dX[0] = X[1]\n dX[1] = alpha*(v(X[0]) - X[1])\n return dX\n\n# Common time variables\nt0 = 0\nTmax = 5\n\n# Initial conditions for f1\nx01 = 2\n# Timestep\nh1 = 0.2\n# Calculate trajectories\nX1_euler, T1s = trajectory(x01, t0, Tmax, h1, f1, euler)\nX1_rk4, T1s = trajectory(x01, t0, Tmax, h1, f1, rk4)\n\n\n# Initial conditions for f2, note that in this case\n# we also need an initial value for the velocity\nx02 = np.array([2, -2])\n# Timestep\n# Try also with h2 = 0.002009\nh2 = 0.00200\n# Calculate trajectories\nX2_euler, T2s = trajectory(x02, t0, Tmax, h2, f2, euler)\nX2_rk4, T2s = trajectory(x02, t0, Tmax, h2, f2, rk4)\n\n# Make a figure with two subplots\nfig, ax = plt.subplots(nrows = 2, sharex = True, figsize = (12,6))\n\n# Plot numerical solutions of position\nax[0].plot(T2s, X2_euler[:,0], label = 'f2 Euler')\nax[0].plot(T2s, X2_rk4[:,0], label = 'f2 RK4')\n\n# Plot numerical solutions of position\nax[0].plot(T1s, X1_euler, '--', label = 'f1 Euler')\nax[0].plot(T1s, X1_rk4, '--', label = 'f1 RK4')\n\n# Plot numerical solutions of velocity (f2 only)\nax[1].plot(T2s, X2_euler[:,1], label = 'f2 Euler')\nax[1].plot(T2s, X2_rk4[:,1], label = 'f2 RK4')\n\n# Labels\nax[0].set_ylabel('$x$', fontsize = 24)\nax[1].set_ylabel('$\\dot{x}$', fontsize = 24)\nax[1].set_xlabel('$t$', fontsize = 24)\n# Add legend\nax[0].legend(fontsize = 16)\nax[1].legend(fontsize = 16)\n# Plot limits\nax[0].set_ylim(-3, 3)\nax[1].set_ylim(-3, 3)\nax[1].set_xlim(-0.05, 5)\n# Reduce whitespace\nplt.tight_layout()", "Example 8 - Implicit solvers\nFor stiff equations, the best solution is often to use an implicit solver. In practice, the most common approach is to use a numerical library (see the scipy example below), but we illustrate the principle here, using the implicit Euler method.\nRecall that the forward Euler method was\n$$ x_{n+1} = x_n + h\\cdot f(x_n, t_n).$$\nThe implicit Euler method (also known as backward Euler) is instead\n$$ x_{n+1} = x_n + h\\cdot f(x_{n+1}, t_{n+1}).$$\nThe problem then is of course that $x_{n+1}$ is unknown, and we have to solve an equation to find it. Methods of this kind are known as implicit methods, since $x_{n+1}$ is given implicitly, instead of explicitly. In general, some kind of numerical equation solver is used to find $x_{n+1}$.\nIn simple cases, such as the above example, we can solve the equation analytically. We have the second order ODE\n$$\\ddot{x} = \\alpha (v(x) - \\dot{x}).$$\nWe use the substitutions $x = x_1$, $\\dot{x} = x_2$ to rewrite into a system of two first-order ODEs:\n$$\\dot{x_1} = x_2,$$\n$$\\dot{x_2} = \\alpha \\big(v(x_1) - x_2\\big).$$\nInserting into the implicit Euler scheme, we find\n$$ x_{1_{n+1}} = x_{1_n} + h \\cdot x_{2_{n+1}}, $$\n$$ x_{2_{n+1}} = x_{2_n} + h \\cdot \\alpha \\big(v(x_{1_{n+1}}) - x_{2_{n+1}}\\big).$$\nThis is a system of equations with two unknowns. Using that $v(x) = -x$, we can solve this system to find\n$$ x_{1_{n+1}} = x_{1_n} + h \\cdot \\frac{x_{2_n} - \\alpha h x_{1_n}}{1 + \\alpha h + \\alpha h^2}, $$\n$$ x_{2_{n+1}} = \\frac{x_{2_n} - \\alpha h x_{1_n}}{1 + \\alpha h + \\alpha h^2}.$$", "# Implementing the above equations in an implicit scheme\n# Note that we are writing this method specifically for\n# the problem we are looking at here. It does not work\n# for other problems.\n\ndef implicit_euler(X, t, h, f):\n # The f isn't used for anything, but keeping\n # the call signature consistent allows us to\n # re-use the earlier trajectory function.\n alpha = 1e3\n x1 = X[0] + h*(X[1]-alpha*h*X[0]) / (1 + alpha*h + alpha*h**2)\n x2 = (X[1]-alpha*h*X[0]) / (1 + alpha*h + alpha*h**2)\n return np.array([x1, x2])\n\n\n# Initial conditions for f2\nx02 = np.array([2, -2])\n# Timestep\n# Note that the timestep can be orders of magnitude larger\n# than what we found above for the explicit schemes.\nh2 = 0.2\n# Calculate trajectories\nX2s, T2s = trajectory(x02, t0, Tmax, h2, f2, implicit_euler)\n\n# Make a figure with two subplots\nfig, ax = plt.subplots(nrows = 2, sharex = True, figsize = (12,8))\n\n# Plot numerical solutions of position\nax[0].plot(T2s, X2s[:,0], label = 'f2 Implicit Euler')\n\n# Plot numerical solutions of velocity\nax[1].plot(T2s, X2s[:,1], label = 'f2 Implicit Euler')\n\n# Labels\nax[0].set_ylabel('$x$', fontsize = 24)\nax[1].set_ylabel('$\\dot{x}$', fontsize = 24)\nax[1].set_xlabel('$t$', fontsize = 24)\n# Add legend\nax[0].legend(fontsize = 16)\nax[1].legend(fontsize = 16)\n# Plot limits\nax[0].set_ylim(-3, 3)\nax[1].set_ylim(-3, 3)\nax[1].set_xlim(-0.05, 5)\n# Reduce whitespace\nplt.tight_layout()", "Example 9 - Scipy.integrate.odeint\n(which is in practice a wrapper for lsoda)\n(which is written in fortran)\nIn practice, the best approach to numerical integration of ODEs is often to use code written by someone else. A useful example is scipy.integrate.odeint. This is a python wrapper to a fortran library called odepack, and specifically to the solver called lsoda. For more information, have a look at the scipy documentation:\nhttps://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.integrate.odeint.html\nThis particular solver uses dynamic timestep, and will automatically switch to an implicit solver if it detects a stiff equation.\nBelow, we try it out on the equation from case 2 above.\nThings to try:\n* Compare number of steps to the smallest number needed by Euler or 4th-order Runge-Kutta", "from scipy.integrate import odeint\n\ndef v(x):\n return -x\n\ndef f2(X, t):\n # x_1 = x\n # x_2 = xdot\n alpha = 1e3\n dX = np.zeros(2)\n dX[0] = X[1]\n dX[1] = alpha*(v(X[0]) - X[1])\n return dX\n\n# Initial conditions for f2\nx02 = np.array([2, -2])\nt0 = 0\nTmax = 5\n# Calculate trajectories\ntimes = np.linspace(t0, Tmax, 100)\nX2_lsoda, infodict = odeint(f2, x02, times, full_output = True, rtol = 1e-2, atol = 1e-2)\n\nprint('Number of steps: ', infodict['nst'][-1])\nprint('Average stepsize: ', Tmax / infodict['nst'][-1])\n\n# Make a figure with two subplots\nfig, ax = plt.subplots(nrows = 2, sharex = True, figsize = (12,8))\n\n# Plot numerical solutions of position\nax[0].plot(times, X2_lsoda[:,0], label = 'f2 lsoda')\n\n# Plot numerical solutions of velocity\nax[1].plot(times, X2_lsoda[:,1], label = 'f2 lsoda')\n\n# Labels\nax[0].set_ylabel('$x$', fontsize = 24)\nax[1].set_ylabel('$\\dot{x}$', fontsize = 24)\nax[1].set_xlabel('$t$', fontsize = 24)\n# Add legend\nax[0].legend(fontsize = 16)\nax[1].legend(fontsize = 16)\n# Plot limits\nax[0].set_ylim(-3, 3)\nax[1].set_ylim(-3, 3)\nax[1].set_xlim(-0.05, 5)\n# Reduce whitespace\nplt.tight_layout()" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
aldian/tensorflow
tensorflow/lite/g3doc/performance/post_training_float16_quant.ipynb
apache-2.0
[ "Copyright 2019 The TensorFlow Authors.", "#@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.", "Post-training float16 quantization\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/lite/performance/post_training_float16_quant\"><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/tensorflow/blob/master/tensorflow/lite/g3doc/performance/post_training_float16_quant.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/tensorflow/blob/master/tensorflow/lite/g3doc/performance/post_training_float16_quant.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/tensorflow/lite/g3doc/performance/post_training_float16_quant.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>\n\nOverview\nTensorFlow Lite now supports\nconverting weights to 16-bit floating point values during model conversion from TensorFlow to TensorFlow Lite's flat buffer format. This results in a 2x reduction in model size. Some harware, like GPUs, can compute natively in this reduced precision arithmetic, realizing a speedup over traditional floating point execution. The Tensorflow Lite GPU delegate can be configured to run in this way. However, a model converted to float16 weights can still run on the CPU without additional modification: the float16 weights are upsampled to float32 prior to the first inference. This permits a significant reduction in model size in exchange for a minimal impacts to latency and accuracy.\nIn this tutorial, you train an MNIST model from scratch, check its accuracy in TensorFlow, and then convert the model into a Tensorflow Lite flatbuffer\nwith float16 quantization. Finally, check the accuracy of the converted model and compare it to the original float32 model.\nBuild an MNIST model\nSetup", "import logging\nlogging.getLogger(\"tensorflow\").setLevel(logging.DEBUG)\n\nimport tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nimport pathlib\n\ntf.float16", "Train and export the model", "# Load MNIST dataset\nmnist = keras.datasets.mnist\n(train_images, train_labels), (test_images, test_labels) = mnist.load_data()\n\n# Normalize the input image so that each pixel value is between 0 to 1.\ntrain_images = train_images / 255.0\ntest_images = test_images / 255.0\n\n# Define the model architecture\nmodel = keras.Sequential([\n keras.layers.InputLayer(input_shape=(28, 28)),\n keras.layers.Reshape(target_shape=(28, 28, 1)),\n keras.layers.Conv2D(filters=12, kernel_size=(3, 3), activation=tf.nn.relu),\n keras.layers.MaxPooling2D(pool_size=(2, 2)),\n keras.layers.Flatten(),\n keras.layers.Dense(10)\n])\n\n# Train the digit classification model\nmodel.compile(optimizer='adam',\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\nmodel.fit(\n train_images,\n train_labels,\n epochs=1,\n validation_data=(test_images, test_labels)\n)", "For the example, you trained the model for just a single epoch, so it only trains to ~96% accuracy.\nConvert to a TensorFlow Lite model\nUsing the Python TFLiteConverter, you can now convert the trained model into a TensorFlow Lite model.\nNow load the model using the TFLiteConverter:", "converter = tf.lite.TFLiteConverter.from_keras_model(model)\ntflite_model = converter.convert()", "Write it out to a .tflite file:", "tflite_models_dir = pathlib.Path(\"/tmp/mnist_tflite_models/\")\ntflite_models_dir.mkdir(exist_ok=True, parents=True)\n\ntflite_model_file = tflite_models_dir/\"mnist_model.tflite\"\ntflite_model_file.write_bytes(tflite_model)", "To instead quantize the model to float16 on export, first set the optimizations flag to use default optimizations. Then specify that float16 is the supported type on the target platform:", "converter.optimizations = [tf.lite.Optimize.DEFAULT]\nconverter.target_spec.supported_types = [tf.float16]", "Finally, convert the model like usual. Note, by default the converted model will still use float input and outputs for invocation convenience.", "tflite_fp16_model = converter.convert()\ntflite_model_fp16_file = tflite_models_dir/\"mnist_model_quant_f16.tflite\"\ntflite_model_fp16_file.write_bytes(tflite_fp16_model)", "Note how the resulting file is approximately 1/2 the size.", "!ls -lh {tflite_models_dir}", "Run the TensorFlow Lite models\nRun the TensorFlow Lite model using the Python TensorFlow Lite Interpreter.\nLoad the model into the interpreters", "interpreter = tf.lite.Interpreter(model_path=str(tflite_model_file))\ninterpreter.allocate_tensors()\n\ninterpreter_fp16 = tf.lite.Interpreter(model_path=str(tflite_model_fp16_file))\ninterpreter_fp16.allocate_tensors()", "Test the models on one image", "test_image = np.expand_dims(test_images[0], axis=0).astype(np.float32)\n\ninput_index = interpreter.get_input_details()[0][\"index\"]\noutput_index = interpreter.get_output_details()[0][\"index\"]\n\ninterpreter.set_tensor(input_index, test_image)\ninterpreter.invoke()\npredictions = interpreter.get_tensor(output_index)\n\nimport matplotlib.pylab as plt\n\nplt.imshow(test_images[0])\ntemplate = \"True:{true}, predicted:{predict}\"\n_ = plt.title(template.format(true= str(test_labels[0]),\n predict=str(np.argmax(predictions[0]))))\nplt.grid(False)\n\ntest_image = np.expand_dims(test_images[0], axis=0).astype(np.float32)\n\ninput_index = interpreter_fp16.get_input_details()[0][\"index\"]\noutput_index = interpreter_fp16.get_output_details()[0][\"index\"]\n\ninterpreter_fp16.set_tensor(input_index, test_image)\ninterpreter_fp16.invoke()\npredictions = interpreter_fp16.get_tensor(output_index)\n\nplt.imshow(test_images[0])\ntemplate = \"True:{true}, predicted:{predict}\"\n_ = plt.title(template.format(true= str(test_labels[0]),\n predict=str(np.argmax(predictions[0]))))\nplt.grid(False)", "Evaluate the models", "# A helper function to evaluate the TF Lite model using \"test\" dataset.\ndef evaluate_model(interpreter):\n input_index = interpreter.get_input_details()[0][\"index\"]\n output_index = interpreter.get_output_details()[0][\"index\"]\n\n # Run predictions on every image in the \"test\" dataset.\n prediction_digits = []\n for test_image in test_images:\n # Pre-processing: add batch dimension and convert to float32 to match with\n # the model's input data format.\n test_image = np.expand_dims(test_image, axis=0).astype(np.float32)\n interpreter.set_tensor(input_index, test_image)\n\n # Run inference.\n interpreter.invoke()\n\n # Post-processing: remove batch dimension and find the digit with highest\n # probability.\n output = interpreter.tensor(output_index)\n digit = np.argmax(output()[0])\n prediction_digits.append(digit)\n\n # Compare prediction results with ground truth labels to calculate accuracy.\n accurate_count = 0\n for index in range(len(prediction_digits)):\n if prediction_digits[index] == test_labels[index]:\n accurate_count += 1\n accuracy = accurate_count * 1.0 / len(prediction_digits)\n\n return accuracy\n\nprint(evaluate_model(interpreter))", "Repeat the evaluation on the float16 quantized model to obtain:", "# NOTE: Colab runs on server CPUs. At the time of writing this, TensorFlow Lite\n# doesn't have super optimized server CPU kernels. For this reason this may be\n# slower than the above float interpreter. But for mobile CPUs, considerable\n# speedup can be observed.\nprint(evaluate_model(interpreter_fp16))", "In this example, you have quantized a model to float16 with no difference in the accuracy.\nIt's also possible to evaluate the fp16 quantized model on the GPU. To perform all arithmetic with the reduced precision values, be sure to create the TfLiteGPUDelegateOptions struct in your app and set precision_loss_allowed to 1, like this:\n//Prepare GPU delegate.\nconst TfLiteGpuDelegateOptions options = {\n .metadata = NULL,\n .compile_options = {\n .precision_loss_allowed = 1, // FP16\n .preferred_gl_object_type = TFLITE_GL_OBJECT_TYPE_FASTEST,\n .dynamic_batch_enabled = 0, // Not fully functional yet\n },\n};\nDetailed documentation on the TFLite GPU delegate and how to use it in your application can be found here" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
uranc/locmea
tutorials/Data_Analysis.ipynb
gpl-3.0
[ "import numpy as np\nfrom locData import data_in", "The task in this tutorial is to load some data, visualize, and analyze it. Let's start by adding the data. \nYou can Use data options to load also the cell morphology files, or electrode geometry:", "# Data path/filename\nt_ind = 38\ndata_path = '../data/'\nfile_name = data_path + 'data_sim_low.hdf5'\n\ndata_options = {'flag_cell': True, 'flag_electode': False}\ndata = data_in(file_name, **data_options)", "The recordings are loaded into the data object. You can check the functions that are in it:\ndata.car_data data.cmp_pca_ica data.flag_cell\ndata.cell_csd data.electrode_pos data.load_h5py_data\ndata.cell_pos data.electrode_rec data.load_with_pickle\ndata.cell_pos_end data.epoch_data data.srate\ndata.cell_pos_start data.f_name \ndata.cmp_cov_sensor data.filter_bpass_data", "data.filter_bpass_data([500,2000[])" ]
[ "code", "markdown", "code", "markdown", "code" ]
tensorflow/docs-l10n
site/zh-cn/guide/keras/train_and_evaluate.ipynb
apache-2.0
[ "Copyright 2020 The TensorFlow Authors.", "#@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.", "使用内置方法进行训练和评估\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td> <a target=\"_blank\" href=\"https://tensorflow.google.cn/guide/keras/train_and_evaluate\"><img src=\"https://tensorflow.google.cn/images/tf_logo_32px.png\">在 TensorFlow.org 上查看</a> </td>\n <td><a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/zh-cn/guide/keras/train_and_evaluate.ipynb\"><img src=\"https://tensorflow.google.cn/images/colab_logo_32px.png\">在 Google Colab 中运行 </a></td>\n <td> <a target=\"_blank\" href=\"https://github.com/tensorflow/docs-l10n/blob/master/site/zh-cn/guide/keras/train_and_evaluate.ipynb\"><img src=\"https://tensorflow.google.cn/images/GitHub-Mark-32px.png\">在 GitHub 上查看源代码</a> </td>\n <td> <a href=\"https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/zh-cn/guide/keras/train_and_evaluate.ipynb\"><img src=\"https://tensorflow.google.cn/images/download_logo_32px.png\">下载笔记本</a> </td>\n</table>\n\n设置", "import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers", "简介\n本指南涵盖使用内置 API 进行训练和验证时的训练、评估和预测(推断)模型(例如 Model.fit()、Model.evaluate() 和 Model.predict())。\n如果您有兴趣在指定自己的训练步骤函数时利用 fit(),请参阅<a href=\"https://tensorflow.google.cn/guide/keras/customizing_what_happens_in_fit/\" data-md-type=\"link\">自定义 fit() 的功能</a>指南。\n如果您有兴趣从头开始编写自己的训练和评估循环,请参阅从头开始编写训练循环指南。\n一般而言,无论您使用内置循环还是编写自己的循环,模型训练和评估都会在每种 Keras 模型(序贯模型、使用函数式 API 构建的模型以及通过模型子类化从头编写的模型)中严格按照相同的方式工作。\n本指南不涉及分布式训练,这部分内容会在我们的多 GPU 和分布式训练指南中进行介绍。\nAPI 概述:第一个端到端示例\n将数据传递到模型的内置训练循环时,应当使用 NumPy 数组(如果数据很小且适合装入内存)或 tf.data Dataset 对象。在接下来的段落中,我们将 MNIST 数据集用作 NumPy 数组,以演示如何使用优化器、损失和指标。\n我们考虑以下模型(在这里,我们使用函数式 API 构建了此模型,但它也可以是序贯模型或子类化模型):", "inputs = keras.Input(shape=(784,), name=\"digits\")\nx = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\nx = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x)\noutputs = layers.Dense(10, activation=\"softmax\", name=\"predictions\")(x)\n\nmodel = keras.Model(inputs=inputs, outputs=outputs)", "下面是典型的端到端工作流,包括:\n\n训练\n根据从原始训练数据生成的预留集进行验证\n对测试数据进行评估\n\n在此示例中,我们使用 MNIST 数据。", "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n\n# Preprocess the data (these are NumPy arrays)\nx_train = x_train.reshape(60000, 784).astype(\"float32\") / 255\nx_test = x_test.reshape(10000, 784).astype(\"float32\") / 255\n\ny_train = y_train.astype(\"float32\")\ny_test = y_test.astype(\"float32\")\n\n# Reserve 10,000 samples for validation\nx_val = x_train[-10000:]\ny_val = y_train[-10000:]\nx_train = x_train[:-10000]\ny_train = y_train[:-10000]", "我们指定训练配置(优化器、损失、指标):", "model.compile(\n optimizer=keras.optimizers.RMSprop(), # Optimizer\n # Loss function to minimize\n loss=keras.losses.SparseCategoricalCrossentropy(),\n # List of metrics to monitor\n metrics=[keras.metrics.SparseCategoricalAccuracy()],\n)", "我们调用 fit(),它会通过将数据切分成大小为 batch_size 的“批次”,然后在给定数量的 epochs 内重复遍历整个数据集来训练模型。", "print(\"Fit model on training data\")\nhistory = model.fit(\n x_train,\n y_train,\n batch_size=64,\n epochs=2,\n # We pass some validation for\n # monitoring validation loss and metrics\n # at the end of each epoch\n validation_data=(x_val, y_val),\n)", "返回的 history 对象保存训练期间的损失值和指标值记录:", "history.history", "我们通过 evaluate() 在测试数据上评估模型:", "# Evaluate the model on the test data using `evaluate`\nprint(\"Evaluate on test data\")\nresults = model.evaluate(x_test, y_test, batch_size=128)\nprint(\"test loss, test acc:\", results)\n\n# Generate predictions (probabilities -- the output of the last layer)\n# on new data using `predict`\nprint(\"Generate predictions for 3 samples\")\npredictions = model.predict(x_test[:3])\nprint(\"predictions shape:\", predictions.shape)", "现在,我们来详细查看此工作流的每一部分。\ncompile() 方法:指定损失、指标和优化器\n要使用 fit() 训练模型,您需要指定损失函数、优化器以及一些要监视的指标(可选)。\n将它们作为 compile() 方法的参数传递给模型:", "model.compile(\n optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()],\n)", "metrics 参数应当为列表 - 您的模型可以具有任意数量的指标。\n如果您的模型具有多个输出,则可以为每个输出指定不同的损失和指标,并且可以调整每个输出对模型总损失的贡献。您可以在将数据传递到多输入、多输出模型部分中找到有关此问题的更多详细信息。\n请注意,如果您对默认设置感到满意,那么在许多情况下,都可以通过字符串标识符将优化器、损失和指标指定为捷径:", "model.compile(\n optimizer=\"rmsprop\",\n loss=\"sparse_categorical_crossentropy\",\n metrics=[\"sparse_categorical_accuracy\"],\n)", "为方便以后重用,我们将模型定义和编译步骤放入函数中;我们将在本指南的不同示例中多次调用它们。", "def get_uncompiled_model():\n inputs = keras.Input(shape=(784,), name=\"digits\")\n x = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\n x = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x)\n outputs = layers.Dense(10, activation=\"softmax\", name=\"predictions\")(x)\n model = keras.Model(inputs=inputs, outputs=outputs)\n return model\n\n\ndef get_compiled_model():\n model = get_uncompiled_model()\n model.compile(\n optimizer=\"rmsprop\",\n loss=\"sparse_categorical_crossentropy\",\n metrics=[\"sparse_categorical_accuracy\"],\n )\n return model\n", "提供许多内置优化器、损失和指标\n通常,您不必从头开始创建自己的损失、指标或优化器,因为您需要的可能已经是 Keras API 的一部分:\n优化器:\n\nSGD()(有或没有动量)\nRMSprop()\nAdam()\n等等\n\n损失:\n\nMeanSquaredError()\nKLDivergence()\nCosineSimilarity()\n等等\n\n指标:\n\nAUC()\nPrecision()\nRecall()\n等等\n\n自定义损失\n如果您需要创建自定义损失,Keras 提供了两种方式。\n第一种方式涉及创建一个接受输入 y_true 和 y_pred 的函数。下面的示例显示了一个计算实际数据与预测值之间均方误差的损失函数:", "def custom_mean_squared_error(y_true, y_pred):\n return tf.math.reduce_mean(tf.square(y_true - y_pred))\n\n\nmodel = get_uncompiled_model()\nmodel.compile(optimizer=keras.optimizers.Adam(), loss=custom_mean_squared_error)\n\n# We need to one-hot encode the labels to use MSE\ny_train_one_hot = tf.one_hot(y_train, depth=10)\nmodel.fit(x_train, y_train_one_hot, batch_size=64, epochs=1)", "如果您需要一个使用除 y_true 和 y_pred 之外的其他参数的损失函数,则可以将 tf.keras.losses.Loss 类子类化,并实现以下两种方法:\n\n__init__(self):接受要在调用损失函数期间传递的参数\ncall(self, y_true, y_pred):使用目标 (y_true) 和模型预测 (y_pred) 来计算模型的损失\n\n假设您要使用均方误差,但存在一个会抑制预测值远离 0.5(我们假设分类目标采用独热编码,且取值介于 0 和 1 之间)的附加项。这会为模型创建一个激励,使其不会对预测值过于自信,这可能有助于减轻过拟合(在尝试之前,我们不知道它是否有效!)。\n您可以按以下方式处理:", "class CustomMSE(keras.losses.Loss):\n def __init__(self, regularization_factor=0.1, name=\"custom_mse\"):\n super().__init__(name=name)\n self.regularization_factor = regularization_factor\n\n def call(self, y_true, y_pred):\n mse = tf.math.reduce_mean(tf.square(y_true - y_pred))\n reg = tf.math.reduce_mean(tf.square(0.5 - y_pred))\n return mse + reg * self.regularization_factor\n\n\nmodel = get_uncompiled_model()\nmodel.compile(optimizer=keras.optimizers.Adam(), loss=CustomMSE())\n\ny_train_one_hot = tf.one_hot(y_train, depth=10)\nmodel.fit(x_train, y_train_one_hot, batch_size=64, epochs=1)", "自定义指标\n如果您需要不属于 API 的指标,则可以通过将 tf.keras.metrics.Metric 类子类化来轻松创建自定义指标。您将需要实现 4 个方法:\n\n__init__(self),您将在其中为指标创建状态变量。\nupdate_state(self, y_true, y_pred, sample_weight=None),使用目标 y_true 和模型预测 y_pred 更新状态变量。\nresult(self),使用状态变量来计算最终结果。\nreset_states(self),用于重新初始化指标的状态。\n\n状态更新和结果计算分开处理(分别在 update_state() 和 result() 中),因为在某些情况下,结果计算的开销可能非常大,只能定期执行。\n下面是一个展示如何实现 CategoricalTruePositives 指标的简单示例,该指标可以计算有多少样本被正确分类为属于给定类:", "class CategoricalTruePositives(keras.metrics.Metric):\n def __init__(self, name=\"categorical_true_positives\", **kwargs):\n super(CategoricalTruePositives, self).__init__(name=name, **kwargs)\n self.true_positives = self.add_weight(name=\"ctp\", initializer=\"zeros\")\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n y_pred = tf.reshape(tf.argmax(y_pred, axis=1), shape=(-1, 1))\n values = tf.cast(y_true, \"int32\") == tf.cast(y_pred, \"int32\")\n values = tf.cast(values, \"float32\")\n if sample_weight is not None:\n sample_weight = tf.cast(sample_weight, \"float32\")\n values = tf.multiply(values, sample_weight)\n self.true_positives.assign_add(tf.reduce_sum(values))\n\n def result(self):\n return self.true_positives\n\n def reset_states(self):\n # The state of the metric will be reset at the start of each epoch.\n self.true_positives.assign(0.0)\n\n\nmodel = get_uncompiled_model()\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[CategoricalTruePositives()],\n)\nmodel.fit(x_train, y_train, batch_size=64, epochs=3)", "处理不适合标准签名的损失和指标\n绝大多数损失和指标都可以通过 y_true 和 y_pred 计算得出,其中 y_pred 是模型的输出,但不是全部。例如,正则化损失可能仅需要激活层(在这种情况下没有目标),并且这种激活可能不是模型输出。\n在此类情况下,您可以从自定义层的调用方法内部调用 self.add_loss(loss_value)。以这种方式添加的损失会在训练期间添加到“主要”损失中(传递给 compile() 的损失)。下面是一个添加激活正则化的简单示例(请注意,激活正则化内置于所有 Keras 层中 - 此层只是为了提供一个具体示例):", "class ActivityRegularizationLayer(layers.Layer):\n def call(self, inputs):\n self.add_loss(tf.reduce_sum(inputs) * 0.1)\n return inputs # Pass-through layer.\n\n\ninputs = keras.Input(shape=(784,), name=\"digits\")\nx = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\n\n# Insert activity regularization as a layer\nx = ActivityRegularizationLayer()(x)\n\nx = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x)\noutputs = layers.Dense(10, name=\"predictions\")(x)\n\nmodel = keras.Model(inputs=inputs, outputs=outputs)\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n)\n\n# The displayed loss will be much higher than before\n# due to the regularization component.\nmodel.fit(x_train, y_train, batch_size=64, epochs=1)", "您可以使用 add_metric() 对记录指标值执行相同的操作:", "class MetricLoggingLayer(layers.Layer):\n def call(self, inputs):\n # The `aggregation` argument defines\n # how to aggregate the per-batch values\n # over each epoch:\n # in this case we simply average them.\n self.add_metric(\n keras.backend.std(inputs), name=\"std_of_activation\", aggregation=\"mean\"\n )\n return inputs # Pass-through layer.\n\n\ninputs = keras.Input(shape=(784,), name=\"digits\")\nx = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\n\n# Insert std logging as a layer.\nx = MetricLoggingLayer()(x)\n\nx = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x)\noutputs = layers.Dense(10, name=\"predictions\")(x)\n\nmodel = keras.Model(inputs=inputs, outputs=outputs)\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n)\nmodel.fit(x_train, y_train, batch_size=64, epochs=1)", "在函数式 API 中,您还可以调用 model.add_loss(loss_tensor) 或 model.add_metric(metric_tensor, name, aggregation)。\n下面是一个简单的示例:", "inputs = keras.Input(shape=(784,), name=\"digits\")\nx1 = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\nx2 = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x1)\noutputs = layers.Dense(10, name=\"predictions\")(x2)\nmodel = keras.Model(inputs=inputs, outputs=outputs)\n\nmodel.add_loss(tf.reduce_sum(x1) * 0.1)\n\nmodel.add_metric(keras.backend.std(x1), name=\"std_of_activation\", aggregation=\"mean\")\n\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n)\nmodel.fit(x_train, y_train, batch_size=64, epochs=1)", "请注意,当您通过 add_loss() 传递损失时,可以在没有损失函数的情况下调用 compile(),因为模型已经有损失要最小化。\n考虑以下 LogisticEndpoint 层:它以目标和 logits 作为输入,并通过 add_loss() 跟踪交叉熵损失。另外,它还通过 add_metric() 跟踪分类准确率。", "class LogisticEndpoint(keras.layers.Layer):\n def __init__(self, name=None):\n super(LogisticEndpoint, self).__init__(name=name)\n self.loss_fn = keras.losses.BinaryCrossentropy(from_logits=True)\n self.accuracy_fn = keras.metrics.BinaryAccuracy()\n\n def call(self, targets, logits, sample_weights=None):\n # Compute the training-time loss value and add it\n # to the layer using `self.add_loss()`.\n loss = self.loss_fn(targets, logits, sample_weights)\n self.add_loss(loss)\n\n # Log accuracy as a metric and add it\n # to the layer using `self.add_metric()`.\n acc = self.accuracy_fn(targets, logits, sample_weights)\n self.add_metric(acc, name=\"accuracy\")\n\n # Return the inference-time prediction tensor (for `.predict()`).\n return tf.nn.softmax(logits)\n", "您可以在具有两个输入(输入数据和目标)的模型中使用它,编译时无需 loss 参数,如下所示:", "import numpy as np\n\ninputs = keras.Input(shape=(3,), name=\"inputs\")\ntargets = keras.Input(shape=(10,), name=\"targets\")\nlogits = keras.layers.Dense(10)(inputs)\npredictions = LogisticEndpoint(name=\"predictions\")(logits, targets)\n\nmodel = keras.Model(inputs=[inputs, targets], outputs=predictions)\nmodel.compile(optimizer=\"adam\") # No loss argument!\n\ndata = {\n \"inputs\": np.random.random((3, 3)),\n \"targets\": np.random.random((3, 10)),\n}\nmodel.fit(data)", "有关训练多输入模型的更多信息,请参阅将数据传递到多输入、多输出模型部分。\n自动分离验证预留集\n在您看到的第一个端到端示例中,我们使用了 validation_data 参数将 NumPy 数组 (x_val, y_val) 的元组传递给模型,用于在每个周期结束时评估验证损失和验证指标。\n这是另一个选项:参数 validation_split 允许您自动保留部分训练数据以供验证。参数值表示要保留用于验证的数据比例,因此应将其设置为大于 0 且小于 1 的数字。例如,validation_split=0.2 表示“使用 20% 的数据进行验证”,而 validation_split=0.6 表示“使用 60% 的数据进行验证”。\n验证的计算方法是在进行任何打乱顺序之前,获取 fit() 调用接收到的数组的最后 x% 个样本。\n请注意,仅在使用 NumPy 数据进行训练时才能使用 validation_split。", "model = get_compiled_model()\nmodel.fit(x_train, y_train, batch_size=64, validation_split=0.2, epochs=1)", "通过 tf.data 数据集进行训练和评估\n在上面的几个段落中,您已经了解了如何处理损失、指标和优化器,并且已经了解当数据作为 NumPy 数组传递时,如何在 fit() 中使用 validation_data 和 validation_split 参数。\n现在,让我们看一下数据以 tf.data.Dataset 对象形式出现的情况。\ntf.data API 是 TensorFlow 2.0 中的一组实用工具,用于以快速且可扩展的方式加载和预处理数据。\n有关创建 Datasets 的完整指南,请参阅 tf.data 文档。\n您可以将 Dataset 实例直接传递给方法 fit()、evaluate() 和 predict():", "model = get_compiled_model()\n\n# First, let's create a training Dataset instance.\n# For the sake of our example, we'll use the same MNIST data as before.\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\n# Shuffle and slice the dataset.\ntrain_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n\n# Now we get a test dataset.\ntest_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))\ntest_dataset = test_dataset.batch(64)\n\n# Since the dataset already takes care of batching,\n# we don't pass a `batch_size` argument.\nmodel.fit(train_dataset, epochs=3)\n\n# You can also evaluate or predict on a dataset.\nprint(\"Evaluate\")\nresult = model.evaluate(test_dataset)\ndict(zip(model.metrics_names, result))", "请注意,数据集会在每个周期结束时重置,因此可以在下一个周期重复使用。\n如果您只想在来自此数据集的特定数量批次上进行训练,则可以传递 steps_per_epoch 参数,此参数可以指定在继续下一个周期之前,模型应使用此数据集运行多少训练步骤。\n如果执行此操作,则不会在每个周期结束时重置数据集,而是会继续绘制接下来的批次。数据集最终将用尽数据(除非它是无限循环的数据集)。", "model = get_compiled_model()\n\n# Prepare the training dataset\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\ntrain_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n\n# Only use the 100 batches per epoch (that's 64 * 100 samples)\nmodel.fit(train_dataset, epochs=3, steps_per_epoch=100)", "使用验证数据集\n您可以在 fit() 中将 Dataset 实例作为 validation_data 参数传递:", "model = get_compiled_model()\n\n# Prepare the training dataset\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\ntrain_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n\n# Prepare the validation dataset\nval_dataset = tf.data.Dataset.from_tensor_slices((x_val, y_val))\nval_dataset = val_dataset.batch(64)\n\nmodel.fit(train_dataset, epochs=1, validation_data=val_dataset)", "在每个周期结束时,模型将迭代验证数据集并计算验证损失和验证指标。\n如果只想对此数据集中的特定数量批次运行验证,则可以传递 validation_steps 参数,此参数可以指定在中断验证并进入下一个周期之前,模型应使用验证数据集运行多少个验证步骤:", "model = get_compiled_model()\n\n# Prepare the training dataset\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\ntrain_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n\n# Prepare the validation dataset\nval_dataset = tf.data.Dataset.from_tensor_slices((x_val, y_val))\nval_dataset = val_dataset.batch(64)\n\nmodel.fit(\n train_dataset,\n epochs=1,\n # Only run validation using the first 10 batches of the dataset\n # using the `validation_steps` argument\n validation_data=val_dataset,\n validation_steps=10,\n)", "请注意,验证数据集将在每次使用后重置(这样您就可以在不同周期中始终根据相同的样本进行评估)。\n通过 Dataset 对象进行训练时,不支持参数 validation_split(从训练数据生成预留集),因为此功能需要为数据集样本编制索引的能力,而 Dataset API 通常无法做到这一点。\n支持的其他输入格式\n除 NumPy 数组、Eager 张量和 TensorFlow Datasets 外,还可以使用 Pandas 数据帧或通过产生批量数据和标签的 Python 生成器训练 Keras 模型。\n特别是,keras.utils.Sequence 类提供了一个简单的接口来构建可感知多处理并且可以打乱顺序的 Python 数据生成器。\n通常,我们建议您使用:\n\nNumPy 输入数据,前提是您的数据很小且适合装入内存\nDataset 对象,前提是您有大型数据集,且需要执行分布式训练\nSequence 对象,前提是您具有大型数据集,且需要执行很多无法在 TensorFlow 中完成的自定义 Python 端处理(例如,如果您依赖外部库进行数据加载或预处理)。\n\n使用 keras.utils.Sequence 对象作为输入\nkeras.utils.Sequence 是一个实用工具,您可以将其子类化以获得具有两个重要属性的 Python 生成器:\n\n它适用于多处理。\n可以打乱它的顺序(例如,在 fit() 中传递 shuffle=True 时)。\n\nSequence 必须实现两个方法:\n\n__getitem__\n__len__\n\n__getitem__ 方法应返回完整的批次。如果要在各个周期之间修改数据集,可以实现 on_epoch_end。\n下面是一个简单的示例:\n```python\nfrom skimage.io import imread\nfrom skimage.transform import resize\nimport numpy as np\nHere, filenames is list of path to the images\nand labels are the associated labels.\nclass CIFAR10Sequence(Sequence):\n def init(self, filenames, labels, batch_size):\n self.filenames, self.labels = filenames, labels\n self.batch_size = batch_size\ndef __len__(self):\n return int(np.ceil(len(self.filenames) / float(self.batch_size)))\n\ndef __getitem__(self, idx):\n batch_x = self.filenames[idx * self.batch_size:(idx + 1) * self.batch_size]\n batch_y = self.labels[idx * self.batch_size:(idx + 1) * self.batch_size]\n return np.array([\n resize(imread(filename), (200, 200))\n for filename in batch_x]), np.array(batch_y)\n\nsequence = CIFAR10Sequence(filenames, labels, batch_size)\nmodel.fit(sequence, epochs=10)\n```\n使用样本加权和类加权\n在默认设置下,样本的权重由其在数据集中出现的频率决定。您可以通过两种方式独立于样本频率来加权数据:\n\n类权重\n样本权重\n\n类权重\n通过将字典传递给 Model.fit() 的 class_weight 参数来进行设置。此字典会将类索引映射到应当用于属于此类的样本的权重。\n这可用于在不重采样的情况下平衡类,或者用于训练更重视特定类的模型。\n例如,在您的数据中,如果类“0”表示类“1”的一半,则可以使用 Model.fit(..., class_weight={0: 1., 1: 0.5})。\n下面是一个 NumPy 示例,我们在其中使用类权重或样本权重来提高对类 #5(MNIST 数据集中的数字“5”)进行正确分类的重要性。", "import numpy as np\n\nclass_weight = {\n 0: 1.0,\n 1: 1.0,\n 2: 1.0,\n 3: 1.0,\n 4: 1.0,\n # Set weight \"2\" for class \"5\",\n # making this class 2x more important\n 5: 2.0,\n 6: 1.0,\n 7: 1.0,\n 8: 1.0,\n 9: 1.0,\n}\n\nprint(\"Fit with class weight\")\nmodel = get_compiled_model()\nmodel.fit(x_train, y_train, class_weight=class_weight, batch_size=64, epochs=1)", "样本权重\n对于细粒度控制,或者如果您不构建分类器,则可以使用“样本权重”。\n\n通过 NumPy 数据进行训练时:将 sample_weight 参数传递给 Model.fit()。\n通过 tf.data 或任何其他类型的迭代器进行训练时:产生 (input_batch, label_batch, sample_weight_batch) 元组。\n\n“样本权重”数组是一个由数字组成的数组,这些数字用于指定批次中每个样本在计算总损失时应当具有的权重。它通常用于不平衡的分类问题(理念是将更多权重分配给罕见类)。\n当使用的权重为 1 和 0 时,此数组可用作损失函数的掩码(完全丢弃某些样本对总损失的贡献)。", "sample_weight = np.ones(shape=(len(y_train),))\nsample_weight[y_train == 5] = 2.0\n\nprint(\"Fit with sample weight\")\nmodel = get_compiled_model()\nmodel.fit(x_train, y_train, sample_weight=sample_weight, batch_size=64, epochs=1)", "下面是一个匹配的 Dataset 示例:", "sample_weight = np.ones(shape=(len(y_train),))\nsample_weight[y_train == 5] = 2.0\n\n# Create a Dataset that includes sample weights\n# (3rd element in the return tuple).\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train, sample_weight))\n\n# Shuffle and slice the dataset.\ntrain_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n\nmodel = get_compiled_model()\nmodel.fit(train_dataset, epochs=1)", "将数据传递到多输入、多输出模型\n在前面的示例中,我们考虑的是具有单个输入(形状为 (764,) 的张量)和单个输出(形状为 (10,) 的预测张量)的模型。但具有多个输入或输出的模型呢?\n考虑以下模型,该模型具有形状为 (32, 32, 3) 的图像输入(即 (height, width, channels))和形状为 (None, 10) 的时间序列输入(即 (timesteps, features))。我们的模型将具有根据这些输入的组合计算出的两个输出:“得分”(形状为 (1,))和在五个类上的概率分布(形状为 (5,))。", "image_input = keras.Input(shape=(32, 32, 3), name=\"img_input\")\ntimeseries_input = keras.Input(shape=(None, 10), name=\"ts_input\")\n\nx1 = layers.Conv2D(3, 3)(image_input)\nx1 = layers.GlobalMaxPooling2D()(x1)\n\nx2 = layers.Conv1D(3, 3)(timeseries_input)\nx2 = layers.GlobalMaxPooling1D()(x2)\n\nx = layers.concatenate([x1, x2])\n\nscore_output = layers.Dense(1, name=\"score_output\")(x)\nclass_output = layers.Dense(5, name=\"class_output\")(x)\n\nmodel = keras.Model(\n inputs=[image_input, timeseries_input], outputs=[score_output, class_output]\n)", "我们来绘制这个模型,以便您可以清楚地看到我们在这里执行的操作(请注意,图中显示的形状是批次形状,而不是每个样本的形状)。", "keras.utils.plot_model(model, \"multi_input_and_output_model.png\", show_shapes=True)", "在编译时,通过将损失函数作为列表传递,我们可以为不同的输出指定不同的损失:", "model.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss=[keras.losses.MeanSquaredError(), keras.losses.CategoricalCrossentropy()],\n)", "如果我们仅将单个损失函数传递给模型,则相同的损失函数将应用于每个输出(此处不合适)。\n对于指标同样如此:", "model.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss=[keras.losses.MeanSquaredError(), keras.losses.CategoricalCrossentropy()],\n metrics=[\n [\n keras.metrics.MeanAbsolutePercentageError(),\n keras.metrics.MeanAbsoluteError(),\n ],\n [keras.metrics.CategoricalAccuracy()],\n ],\n)", "由于我们已为输出层命名,我们还可以通过字典指定每个输出的损失和指标:", "model.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss={\n \"score_output\": keras.losses.MeanSquaredError(),\n \"class_output\": keras.losses.CategoricalCrossentropy(),\n },\n metrics={\n \"score_output\": [\n keras.metrics.MeanAbsolutePercentageError(),\n keras.metrics.MeanAbsoluteError(),\n ],\n \"class_output\": [keras.metrics.CategoricalAccuracy()],\n },\n)", "如果您的输出超过 2 个,我们建议使用显式名称和字典。\n可以使用 loss_weights 参数为特定于输出的不同损失赋予不同的权重(例如,在我们的示例中,我们可能希望通过为类损失赋予 2 倍重要性来向“得分”损失赋予特权):", "model.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss={\n \"score_output\": keras.losses.MeanSquaredError(),\n \"class_output\": keras.losses.CategoricalCrossentropy(),\n },\n metrics={\n \"score_output\": [\n keras.metrics.MeanAbsolutePercentageError(),\n keras.metrics.MeanAbsoluteError(),\n ],\n \"class_output\": [keras.metrics.CategoricalAccuracy()],\n },\n loss_weights={\"score_output\": 2.0, \"class_output\": 1.0},\n)", "如果这些输出用于预测而不是用于训练,也可以选择不计算某些输出的损失:", "# List loss version\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss=[None, keras.losses.CategoricalCrossentropy()],\n)\n\n# Or dict loss version\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss={\"class_output\": keras.losses.CategoricalCrossentropy()},\n)", "将数据传递给 fit() 中的多输入或多输出模型的工作方式与在编译中指定损失函数的方式类似:您可以传递 NumPy 数组的列表(1:1 映射到接收损失函数的输出),或者通过字典将输出名称映射到 NumPy 数组。", "model.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss=[keras.losses.MeanSquaredError(), keras.losses.CategoricalCrossentropy()],\n)\n\n# Generate dummy NumPy data\nimg_data = np.random.random_sample(size=(100, 32, 32, 3))\nts_data = np.random.random_sample(size=(100, 20, 10))\nscore_targets = np.random.random_sample(size=(100, 1))\nclass_targets = np.random.random_sample(size=(100, 5))\n\n# Fit on lists\nmodel.fit([img_data, ts_data], [score_targets, class_targets], batch_size=32, epochs=1)\n\n# Alternatively, fit on dicts\nmodel.fit(\n {\"img_input\": img_data, \"ts_input\": ts_data},\n {\"score_output\": score_targets, \"class_output\": class_targets},\n batch_size=32,\n epochs=1,\n)", "下面是 Dataset 的用例:与我们对 NumPy 数组执行的操作类似,Dataset 应返回一个字典元组。", "train_dataset = tf.data.Dataset.from_tensor_slices(\n (\n {\"img_input\": img_data, \"ts_input\": ts_data},\n {\"score_output\": score_targets, \"class_output\": class_targets},\n )\n)\ntrain_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n\nmodel.fit(train_dataset, epochs=1)", "使用回调\nKeras 中的回调是在训练过程中的不同时间点(在某个周期开始时、在批次结束时、在某个周期结束时等)调用的对象。它们可用于实现特定行为,例如:\n\n在训练期间的不同时间点进行验证(除了内置的按周期验证外)\n定期或在超过一定准确率阈值时为模型设置检查点\n当训练似乎停滞不前时,更改模型的学习率\n当训练似乎停滞不前时,对顶层进行微调\n在训练结束或超出特定性能阈值时发送电子邮件或即时消息通知\n等等\n\n回调可以作为列表传递给您对 fit() 的调用:", "model = get_compiled_model()\n\ncallbacks = [\n keras.callbacks.EarlyStopping(\n # Stop training when `val_loss` is no longer improving\n monitor=\"val_loss\",\n # \"no longer improving\" being defined as \"no better than 1e-2 less\"\n min_delta=1e-2,\n # \"no longer improving\" being further defined as \"for at least 2 epochs\"\n patience=2,\n verbose=1,\n )\n]\nmodel.fit(\n x_train,\n y_train,\n epochs=20,\n batch_size=64,\n callbacks=callbacks,\n validation_split=0.2,\n)", "提供多个内置回调\nKeras 中已经提供多个内置回调,例如:\n\nModelCheckpoint:定期保存模型。\nEarlyStopping:当训练不再改善验证指标时,停止训练。\nTensorBoard:定期编写可在 TensorBoard 中可视化的模型日志(更多详细信息,请参阅“可视化”部分)。\nCSVLogger:将损失和指标数据流式传输到 CSV 文件。\n等等\n\n有关完整列表,请参阅回调文档。\n编写您自己的回调\n您可以通过扩展基类 keras.callbacks.Callback 来创建自定义回调。回调可以通过类属性 self.model 访问其关联的模型。\n确保阅读编写自定义回调的完整指南。\n下面是一个简单的示例,在训练期间保存每个批次的损失值列表:", "class LossHistory(keras.callbacks.Callback):\n def on_train_begin(self, logs):\n self.per_batch_losses = []\n\n def on_batch_end(self, batch, logs):\n self.per_batch_losses.append(logs.get(\"loss\"))\n", "为模型设置检查点\n根据相对较大的数据集训练模型时,经常保存模型的检查点至关重要。\n实现此目标的最简单方式是使用 ModelCheckpoint 回调:", "model = get_compiled_model()\n\ncallbacks = [\n keras.callbacks.ModelCheckpoint(\n # Path where to save the model\n # The two parameters below mean that we will overwrite\n # the current checkpoint if and only if\n # the `val_loss` score has improved.\n # The saved model name will include the current epoch.\n filepath=\"mymodel_{epoch}\",\n save_best_only=True, # Only save a model if `val_loss` has improved.\n monitor=\"val_loss\",\n verbose=1,\n )\n]\nmodel.fit(\n x_train, y_train, epochs=2, batch_size=64, callbacks=callbacks, validation_split=0.2\n)", "ModelCheckpoint 回调可用于实现容错:在训练随机中断的情况下,从模型的最后保存状态重新开始训练的能力。下面是一个基本示例:", "import os\n\n# Prepare a directory to store all the checkpoints.\ncheckpoint_dir = \"./ckpt\"\nif not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n\n\ndef make_or_restore_model():\n # Either restore the latest model, or create a fresh one\n # if there is no checkpoint available.\n checkpoints = [checkpoint_dir + \"/\" + name for name in os.listdir(checkpoint_dir)]\n if checkpoints:\n latest_checkpoint = max(checkpoints, key=os.path.getctime)\n print(\"Restoring from\", latest_checkpoint)\n return keras.models.load_model(latest_checkpoint)\n print(\"Creating a new model\")\n return get_compiled_model()\n\n\nmodel = make_or_restore_model()\ncallbacks = [\n # This callback saves a SavedModel every 100 batches.\n # We include the training loss in the saved model name.\n keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_dir + \"/ckpt-loss={loss:.2f}\", save_freq=100\n )\n]\nmodel.fit(x_train, y_train, epochs=1, callbacks=callbacks)", "您还可以编写自己的回调来保存和恢复模型。\n有关序列化和保存的完整指南,请参阅保存和序列化模型指南。\n使用学习率时间表\n训练深度学习模型的常见模式是随着训练的进行逐渐减少学习。这通常称为“学习率衰减”。\n学习衰减时间表可以是静态的(根据当前周期或当前批次索引预先确定),也可以是动态的(响应模型的当前行为,尤其是验证损失)。\n将时间表传递给优化器\n通过将时间表对象作为优化器中的 learning_rate 参数传递,您可以轻松使用静态学习率衰减时间表:", "initial_learning_rate = 0.1\nlr_schedule = keras.optimizers.schedules.ExponentialDecay(\n initial_learning_rate, decay_steps=100000, decay_rate=0.96, staircase=True\n)\n\noptimizer = keras.optimizers.RMSprop(learning_rate=lr_schedule)", "提供了几个内置时间表:ExponentialDecay、PiecewiseConstantDecay、PolynomialDecay 和 InverseTimeDecay。\n使用回调实现动态学习率时间表\n由于优化器无法访问验证指标,因此无法使用这些时间表对象来实现动态学习率时间表(例如,当验证损失不再改善时降低学习率)。\n但是,回调确实可以访问所有指标,包括验证指标!因此,您可以通过使用可修改优化器上的当前学习率的回调来实现此模式。实际上,它甚至以 ReduceLROnPlateau 回调的形式内置。\n可视化训练期间的损失和指标\n在训练期间密切关注模型的最佳方式是使用 TensorBoard,这是一个基于浏览器的应用,它可以在本地运行,为您提供:\n\n训练和评估的实时损失和指标图\n(可选)层激活直方图的可视化\n(可选)Embedding 层学习的嵌入向量空间的 3D 可视化\n\n如果您已通过 pip 安装了 TensorFlow,则应当能够从命令行启动 TensorBoard:\ntensorboard --logdir=/full_path_to_your_logs\n使用 TensorBoard 回调\n将 TensorBoard 与 Keras 模型和 fit 方法一起使用的最简单方式是 TensorBoard 回调。\n在最简单的情况下,只需指定您希望回调写入日志的位置即可:", "keras.callbacks.TensorBoard(\n log_dir=\"/full_path_to_your_logs\",\n histogram_freq=0, # How often to log histogram visualizations\n embeddings_freq=0, # How often to log embedding visualizations\n update_freq=\"epoch\",\n) # How often to write logs (default: once per epoch)", "有关详情,请参阅 TensorBoard 回调的文档。" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
liganega/Gongsu-DataSci
notebooks/GongSu11_List_Comprehension.ipynb
gpl-3.0
[ "리스트 조건제시법(List Comprehension)\n주요 내용\n주어진 리스트를 이용하여 특정 성질을 만족하는 새로운 리스트를 생성하고자 할 때 \n리스트 조건제시법을 활용하면 매우 효율적인 코딩을 할 수 있다.\n리스트 조건제시법은 집합을 정의할 때 사용하는 조건제시법과 매우 유사하다. \n예를 들어,0부터 1억 사이에 있는 홀수들을 원소로 갖는 집합을 정의하려면 \n두 가지 방법을 활용할 수 있다. \n\n\n원소나열법\n{1, 3, 5, 7, 9, 11, ..., 99999999} \n 중간에 사용한 점점점(...) 중략기호는 0부터 1억 사이의 총 5천만개의 홀수를 \n 나열하는 것은 불가능하기에 사용한 기호이다.\n 실제로 1초에 하나씩 숫자를 적는다 해도 5천만 초, 약 1년 8개월이 걸린다.\n\n\n조건제시법\n{ x | 0 &lt;= x &lt;= 1억, 단 x는 홀수}\n\n\n여기서는 조건제시법을 활용하여 새로운 리스트를 생성하는 방법을 알아본다. \n오늘의 주요 예제\n$y = x^2$ 함수의 그래프를 아래와 같이 그려보자. \n단, $x$는 -10에서 10사이의 값을 가진다.\n<p>\n<table cellspacing=\"20\">\n\n<tr>\n<td>\n<img src=\"images/pyplot_exp.png\" style=\"width:350\">\n</td>\n</tr>\n\n</table>\n</p>\n\n특정 성질을 만족하는 리스트 생성하기\n예제\n0부터 20 사이의 모든 홀수를 순서대로 담고 있는 리스트를 어떻게 구현할까?\n집합의 경우에서처럼 원소나열법 또는 조건제시법을 활용할 수 있다.", "odd_20 = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]", "아니면, 반복문을 활용할 수 있다.\n\nwhile 반복문: 리스트의 append() 메소드를 활용한다.", "i = 0\nodd_20 = []\n\nwhile i <= 20:\n if i % 2 == 1:\n odd_20.append(i)\n i += 1\n \nprint(odd_20) ", "for 반복문: range() 함수를 활용한다.", "odd_20 = []\n\nfor i in range(21):\n if i % 2 == 1:\n odd_20.append(i)\n \nprint(odd_20) ", "예제\n이제 0부터 1억 사이의 모든 홀수를 순서대로 담고 있는 리스트를 원소나열법으로 구현할 수 있을까?\n답은 '아니다'이다. 집합을 정의할 때처럼 생략기호를 사용할 수는 있지만, 제대로 작동하지 않는다. \n예를 들어, 0부터 1억 사이의 모든 홀수들의 리스트를 아래와 같이 선언해 보자.", "odd_nums = [1, 3, 5, 7, 9, 11, ..., 99999999]", "확인하면 학교에서 배운 것과 비슷하게 작동하는 것처럼 보인다.", "print(odd_nums)", "주의: Ellipsis는 생략을 나타낸다.\n하지만 처음 10개의 홀수를 얻기 위해 슬라이싱을 사용하면 다음과 같이 엉뚱하게 나온다.", "odd_nums[:10]", "위와 같이 작동하는 이유는 생략된 부분이 어떤 규칙으로 나열되는지 파이썬 해석기가 알지 못하기 때문이다.\n반면에 반복문을 활용하는 것은 언제든지 가능하다. \n예를 들어, 아래 함수는 0부터 정해진 숫자 사이의 모든 홀수를 순서대로 담은 리스트를 생성하려 리턴한다.", "def odd_number(num):\n L=[]\n for i in range(num):\n if i%2 == 1:\n L.append(i)\n return L ", "0과 20 사이의 홀수들의 리스트는 다음과 같다.", "odd_number(20)", "이제 0과 1억 사이의 홀수들의 리스트를 생성해보자.\n주의: 아래와 같은 명령어는 실행하지 말자. 5천만개의 숫자를 출력하는 바보같은 일은 하지 말아야 한다.\nprint(odd_number(100000000))", "odd_100M = odd_number(100000000)", "좀 오래 걸린다. \n사용하는 컴퓨터 사양에 따라 시간차이가 발생하지만 1억보다 작은 5천만 개의 홀수를 생성하는 \n데에 최신 노트북인 경우 10여초 걸린다.\n홀수들의 리스트가 제대로 생성되었는지를 확인하기 위해 처음 20개의 홀수를 확인해보자.", "print(odd_100M[:20])", "부록: 프로그램 실행시간 측정하기\n프로그램의 실행시간을 확인하려면 time 모듈의 clock() 함수를 활용하면 된다.\nclock() 함수의 리턴값은 이 함수를 호출할 때까지 걸린 프로세스 시간을 나타낸다. \n프로세스 시간의 의미를 이해하지 못해도 상관 없다. \n대신에 time 모듈의 clock() 함수의 활용법을 한 번쯤 본 것으로 만족한다.", "import time\n\nstart_time = time.clock()\nodd_100M = odd_number(100000000)\nend_time = time.clock()\n\nprint(end_time - start_time, \"초\")", "이제 질문을 좀 다르게 하자.\nodd_number 함수를 좀 더 간결하게 정의할 수 없을까? \n이에 대해 파이썬에서는 리스트 조건제시법이라는 기술을 제공한다. \n이 기술을 모든 언어가 지원하지는 않는다. \n예를 들어, C# 언어는 from ... where ... select ... 가 비슷한 역할을 지원하지만 좀 다르고, \nJava 언어에서는 함수 인터페이스를 이용하여 비슷한 기능을 구현할 수 있다.\n리스트 조건제시법 이해\n리스트 조건제시법은 집합 정의에 사용되는 조건제시법과 매우 비슷하게 작동한다.\n예를 들어, 0부터 1억 사이의 홀수들을 순서대로 항목으로 갖는 리스트를 생성하는 과정을 \n설명하면서 조건제시법의 이해를 돕고자 한다. \n\n\n먼저, 앞서 개요에서 설명한 대로 0부터 1억 사이의 홀수들의 집합을 \n 조건제시법으로로 표현한다. \n{x | 0 &lt;= x &lt;= 100000000, 단 x는 홀수} \n\n\n이제 집합기호를 리스트 기호로 대체한다.\n[x | 0 &lt;= x &lt;= 100000000, 단 x는 홀수] \n\n\n집합의 짝대기(|) 기호는 for로 대체한다.\n[x for 0 &lt;= x &lt;= 100000000, 단 x는 홀수] \n\n\n짝대기 기호 오른편에 위치하고, 변수 x가 어느 범위에서 움직이는지를 설명하는 \n 부등식인 0 &lt;= x &lt;= 100000000 부분을 파이썬 수식으로 변경한다.\n 주로, 기존에 정의된 리스트를 사용하거나 range() 함수를 활용하여\n 범위를 x in ... 형식으로 지정한다. \n[x for x in range(100000000+1), 단 x는 홀수] \n\n\n마지막으로 변수 x에 대한 제한조건인 단 x는 홀수 부분을 \n 파이썬의 if 문장으로 변경한다. \n 예를 들어, x는 홀수는 파이썬의 x % 2 == 1로 나타낼 수 있다.\n[x for x in range(100000001) if x % 2 == 1]", "odd_100M = [x for x in range(100000001) if x % 2 == 1]\n\nodd_100M[:10]", "예제\n0부터 1억 사이의 홀수들의 제곱을 항목으로 갖는 리스트를 조건제시법으로 생성할 수 있다.", "odd_100M_square = [x**2 for x in range(100000000) if x % 2== 1]\n\nodd_100M_square[:10]", "물론 앞서 만든 odd_100M을 재활용할 수 있다.", "odd_100M_square = [x**2 for x in odd_100M]\n\nodd_100M_square[:10]", "예제\n0부터 1억 사이의 홀수들을 항목으로 갖는 리스트를 다른 조건제시법으로 생성해보자.\n먼저, 모든 홀수는 2*x + 1의 모양을 갖는다는 점에 주의한다.\n따라서 1억보다 작은 홀수는 아래와 같이 생성할 수 있다.", "odd_100M2 = [2 * x + 1 for x in range(50000000)]\n\nodd_100M2[:10]", "이 방식은 좀 더 쉬워 보인다. if 문이 없기 때문이다. \n위에서 사용한 조건제시법을 for 반복문을 이용하여 구현하면 아래처럼 할 수 있다.", "odd_100M2 = []\n\nfor x in range(50000000):\n odd_100M2.append(2*x+1)\n\nodd_100M2[:10]", "오늘의 주요 예제 해결\n$y = x^2$ 함수의 그래프를 그리고자 한다. \n그래프를 그리기 위해 matplotlib.pyplot 이란 모듈을 이용한다. \n아래 코드처럼 퍼센트 기호(%)로 시작하는 코드는 쥬피터 노트북에만 사용하는 코드이며,\n아래 코드는 쥬피터 노트북에 그래프를 직접 나타내기 위해 사용한다.\nspyder 등 파이썬 에디터를 사용하는 경우 필요하지 않는 코드이다.", "%matplotlib inline", "matplotlib.pyplot 모듈 이름이 길어서 보통은 plt 라고 줄여서 부른다.", "import matplotlib.pyplot as plt", "그래프를 그리기 위해서는 먼저 필요한 만큼의 점을 찍어야 한다.\n2차원 그래프의 점은 x좌표와 y좌표의 쌍으로 이루어져 있음을 기억한다.\n그리고 파이썬의 경우 점들의 그래프를 그리기 위해서는 점들의 x좌표 값들의 리스트와 \ny좌표 값들의 리스트를 제공해야 한다.\n기본적으로 점을 많이 찍을 수록 보다 정확한 그래프를 그릴 수 있지만 몇 개의 점으로도 \n그럴싸한 그래프를 그릴 수 있다.\n예를 들어, (-10, 100), (-5, 25), (0, 0), (5, 25), (10, 100) \n다섯 개의 점을 잇는 그래프를 그리기 위해\nxs = [-10, -5, 0, 5, 10]\n와 \nys = [100, 25, 0, 25, 100]\n의 각각의 점들의 x좌표 값들의 리스트와 y좌표 값들의 리스트를 활용한다.\nys 리스트의 각각의 항목은 xs 리스트의 동일한 위치에 해당하는 항목의 제곱임에 주의하라.", "### 그래프 준비 시작 ###\n# 여기부터 아래 세 개의 우물정 표시 부분까지는 그래프를 그리기 위해 준비하는 부분이다.\n# 이해하려 하지 말고 그냥 기억만 해두면 된다.\n\n# 그림을 그리기 위한 도화지를 준비하는 용도이다.\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n\n# x축은 아래에, y축은 그림의 중심에 위치하도록 한다.\nax.spines['left'].set_position('center')\nax.spines['bottom'].set_position('zero')\n\n# 그래프를 둘러싸는 상자를 없앤다.\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\n### 그래프 그리기 준비 끝 ###\n\n# x좌표와 y좌표 값들의 리스트를 제공한다.\n# 여기서는 조건제시법을 활용한다.\nxs = [x for x in range(-10, 11, 5)]\nys = [x**2 for x in xs]\n\n# 이제 plot() 함수를 호출하여 그래프를 그린다.\nplt.plot(xs, ys)\nplt.show()", "보다 많은 점을 찍으면 보다 부드러운 그래프를 얻을 수 있다.", "### 그래프 준비 시작 ###\n# 여기부터 아래 세 개의 우물정 표시 부분까지는 그래프를 그리기 위해 준비하는 부분이다.\n# 이해하려 하지 말고 그냥 기억만 해두면 된다.\n\n# 그림을 그리기 위한 도화지를 준비하는 용도이다.\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n\n# x축은 아래에, y축은 그림의 중심에 위치하도록 한다.\nax.spines['left'].set_position('center')\nax.spines['bottom'].set_position('zero')\n\n# 그래프를 둘러싸는 상자를 없앤다.\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\n### 그래프 그리기 준비 끝 ###\n\n# x좌표와 y좌표 값들의 리스트를 제공한다.\n# 여기서는 조건제시법을 활용한다.\nxs = [x for x in range(-10, 11)]\nys = [x**2 for x in xs]\n\n# 이제 plot() 함수를 호출하여 그래프를 그린다.\nplt.plot(xs, ys)\nplt.show()", "연습문제\n연습\n수학에서 사용되는 대표적인 지수함수인 $f(x) = e^x$는 math 모듈의 exp()로 정의되어 있다. \n아래 리스트를 조건제시법으로 구현하라. \n$$[e^1, e^3, e^5, e^7, e^9]$$\n주의: $e$의 값은 대략 2.718 정도이다.\n견본답안:", "from math import exp\n\n[exp(n) for n in range(10) if n % 2 == 1]", "연습\n아래 리스트를 조건제시법으로 구현하라.\n$$[e^3, e^6, e^9, e^{12}, e^{15}]$$\n힌트: range(1, 6)을 활용할 수 있다.\n견본답안:", "[exp(3*n) for n in range(1,6)]", "연습\n조건제시법은 데이터를 처리하는 데에 매우 효과적이다. \n예를 들어, 어떤 영어 문장에 사용된 단어들의 길이를 분석할 수 있다. \n아래와 같이 파이썬을 소개하는 문장이 있다.", "about_python = 'Python is a general-purpose programming language. \\\n It is becoming more and more popular \\\n for doing data science.'", "위 문장에 사용된 단어들의 길이를 분석하기 위해 먼저 위 문장을 단어로 쪼갠다. \n이를 위해, 문자열에 사용하는 split() 메소드를 사용한다.", "words = about_python.split()\nwords", "위 words 리스트의 각 항목의 문자열들을 모두 대문자로 바꾼 단어와 그리고 해당 항목의 문자열의 길이를 항목으로 갖는 튜플들의 리스트를 작성하고자 한다. \n[('PYTHON', 6), ('IS', 2), ....] \n반복문을 이용하여 아래와 같이 작성할 수 있다.", "L =[]\nfor x in words:\n L.append((x.upper(), len(x)))\n \nL", "리스트 조건제시법으로는 아래와 같이 보다 간결하게 구현할 수 있다.", "[(x.upper(), len(x)) for x in words]", "처음 다섯 개의 단어만 다루고자 할 경우에는 아래처럼 하면 된다.", "[(x.upper(), len(x)) for x in words[:5]]", "아래처럼 인덱스에 제한을 가하는 방식도 가능하다. 즉, if 문을 추가로 활용한다.", "[(words[n].upper(), len(words[n])) for n in range(len(words)) if n < 5]", "질문:\n위 단어들 중에서 'language.'와 'science.' 두 경우에 마침표가 사용되었다. \n마침표를 제외한 단어의 길이를 표시하도록 위 코드를 수정하라.\n힌트: strip() 문자열 메소드를 활용한다.\n견본답안:", "[(x.strip('.').upper(), len(x.strip('.'))) for x in words]", "연습\n머신러닝의 인공신경만(Artificial Neural Network) 분야에서 활성화 함수(activation function)로 많이 사용되는 ReLU(Rectified Linear Unit) 함수를 그래프로 그려보자. ReLu 함수의 정의는 다음과 같다.\n$$\nf(x) = \\begin{cases} 0 & x <0 \\text{ 인 경우,} \\ 1 & x \\ge 0 \\text{ 인 경우.}\\end{cases}\n$$\n참조: ReLU 함수에 대한 간단한 설명은 여기에서 확인할 수 있다.\n견본답안:", "import matplotlib.pyplot as plt\n\nfig = plt.figure()\n\nax = fig.add_subplot(1, 1, 1)\nax.spines['left'].set_position('center')\nax.spines['bottom'].set_position('zero')\n\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\n\nxs = [x for x in range(-10, 11)]\nys = [max(0, x) for x in xs]\n\nplt.plot(xs, ys)\nplt.show()" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
unmrds/cc-python
1.2-The Basics.ipynb
apache-2.0
[ "The Basics\nAt the core of Python (and any programming language) there are some key characteristics of how a program is structured that enable the proper execution of that program. These characteristics include the structure of the code itself, the core data types from which others are built, and core operators that modify objects or create new ones. From these raw materials more complex commands, functions, and modules are built.\nFor guidance on recommended Python structure refer to the Python Style Guide.\nExamples: Variables and Data Types\nThe Interpreter", "# The interpreter can be used as a calculator, and can also echo or concatenate strings.\n\n3 + 3\n\n3 * 3\n\n3 ** 3\n\n3 / 2 # classic division - output is a floating point number\n\n# Use quotes around strings, single or double, but be consistent to the extent possible\n\n'dogs'\n\n\"dogs\"\n\n\"They're going to the beach\"\n\n'He said \"I like mac and cheese\"'\n\n# sometimes you can't escape the escape\n'He said \"I\\'d like mac and cheese\"'\n\n# + operator can be used to concatenate strings\n\n'dogs' + \"cats\"\n\nprint('Hello World!')", "Try It Yourself\nGo to the section 4.4. Numeric Types in the Python 3 documentation at https://docs.python.org/3.4/library/stdtypes.html. The table in that section describes different operators - try some!\nWhat is the difference between the different division operators (/, //, and %)?\nVariables\nVariables allow us to store values for later use.", "a = 5\nb = 10\na + b", "Variables can be reassigned:", "b = 38764289.1097\na + b", "The ability to reassign variable values becomes important when iterating through groups of objects for batch processing or other purposes. In the example below, the value of b is dynamically updated every time the while loop is executed:", "a = 5\nb = 10\nwhile b > a:\n print(\"b=\"+str(b))\n b = b-1", "Variable data types can be inferred, so Python does not require us to declare the data type of a variable on assignment.", "a = 5\ntype(a)", "is equivalent to", "a = int(5)\ntype(a)\n\nc = 'dogs'\nprint(type(c))\n\nc = str('dogs')\nprint(type(c))", "There are cases when we may want to declare the data type, for example to assign a different data type from the default that will be inferred. Concatenating strings provides a good example.", "customer = 'Carol'\npizzas = 2\nprint(customer + ' ordered ' + pizzas + ' pizzas.')", "Above, Python has inferred the type of the variable pizza to be an integer. Since strings can only be concatenated with other strings, our print statement generates an error. There are two ways we can resolve the error:\n\nDeclare the pizzas variable as type string (str) on assignment or\nRe-cast the pizzas variable as a string within the print statement.", "customer = 'Carol'\npizzas = str(2)\nprint(customer + ' ordered ' + pizzas + ' pizzas.')\n\ncustomer = 'Carol'\npizzas = 2\nprint(customer + ' ordered ' + str(pizzas) + ' pizzas.')", "Given the following variable assignments:\nx = 12\ny = str(14)\nz = donuts\nPredict the output of the following:\n\ny + z\nx + y\nx + int(y)\nstr(x) + y\n\nCheck your answers in the interpreter.\nVariable Naming Rules\nVariable names are case senstive and:\n\nCan only consist of one \"word\" (no spaces).\nMust begin with a letter or underscore character ('_').\nCan only use letters, numbers, and the underscore character.\n\nWe further recommend using variable names that are meaningful within the context of the script and the research.\nReading Files\nWe can accomplish a lot by assigning variables within our code as demonstrated above, but often we are interested in working with objects and data that exist in other files and directories on our system.\nWhen we want to read data files into a script, we do so by assigning the content of the file to a variable. This stores the data in memory and lets us perform processes and analyses on the data without changing the content of the source file.\nThere are several ways to read files in Python - many libraries have methods for reading text, Excel and Word documents, PDFs, etc. This morning we're going to demonstrate using the read() and readlines() method in the standard library, and the Pandasread_csv() function.", "# Read unstructured text\n\n# One way is to open the whole file as a block\nfile_path = \"./beowulf\" # We can save the path to the file as a variable\nfile_in = open(file_path, \"r\") # Options are 'r', 'w', and 'a' (read, write, append)\nbeowulf_a = file_in.read()\nfile_in.close()\nprint(beowulf_a)\n\n# Another way is to read the file as a list of individual lines\n\nwith open(file_path, \"r\") as b:\n beowulf_b = b.readlines()\n\nprint(beowulf_b)\n\n# In order to get a similar printout to the first method, we use a for loop\n# to print line by line - more on for loops below!\n\nfor l in beowulf_b:\n print(l)\n\n# We now have two variables with the content of our 'beowulf' file represented using two different data structures.\n# Why do you think we get the different outputs from the next two statements?\n\n# Beowulf text stored as one large string\nprint(\"As string:\", beowulf_a[0])\n\n# Beowulf text stored as a list of lines\nprint(\"As list of lines:\", beowulf_b[0])\n\n# We can confirm our expectations by checking on the types of our two beowulf variables\nprint(type(beowulf_a))\nprint(type(beowulf_b))\n\n# Read CSV files using the Pandas read_csv method.\n# Note: Pandas also includes methods for reading Excel.\n\n# First we need to import the pandas library\nimport pandas as pd\n\n# Create a variable to hold the path to the file\nfpath = \"aaj1945_DataS1_Egg_shape_by_species_v2.csv\"\negg_data = pd.read_csv(fpath)\n\n# We can get all kinds of info about the dataset\n\n# info() provides an overview of the structure\nprint(egg_data.info())\n\n# Look at the first five rows\negg_data.head()\n\n# Names of columns\nprint(egg_data.columns.values)\n\n# Dimensions (number of rows and columns)\nprint(egg_data.shape)\n\n# And much more! But as a final example we can perform operations on the data.\n# Descriptive statistics on the \"Number of eggs\" column\nprint(egg_data[\"Number of eggs\"].describe())\n\n# Or all of the columns in whole table with numeric data types:\nprint(egg_data.describe())", "Structure\nNow that we have practiced assigning variables and reading information from files, we will have a look at concepts that are key to developing processes to use and analyze this information.\nBlocks\nThe structure of a Python program is pretty simple:\nBlocks of code are defined using indentation. Code that is at a lower level of indentation is not considerd part of a block. Indentation can be defined using spaces or tabs (spaces are recommended by the style guide), but be consistent (and prepared to defend your choice). As we will see, code blocks define the boundaries of sets of commands that fit within a given section of code. This indentation model for defining blocks of code significantly increases the readabiltiy of Python code.\nFor example:\n&gt;&gt;&gt;a = 5\n&gt;&gt;&gt;b = 10\n&gt;&gt;&gt;while b &gt; a:\n... print(\"b=\"+str(b))\n... b = b-1\n&gt;&gt;&gt;print(\"I'm outside the block\")\n\nComments & Documentation\nYou can (and should) also include documentation and comments in the code your write - both for yourself, and potential future users (including yourself). Comments are pretty much any content on a line that follows a # symbol (unless it is between quotation marks. For example:\n&gt;&gt;&gt;# we're going to do some math now\n&gt;&gt;&gt;yae = 5 # the number of votes in favor\n&gt;&gt;&gt;nay = 10 # the number of votes against\n&gt;&gt;&gt;proportion = yae / nay # the proportion of votes in favor\n&gt;&gt;&gt;print(proportion)\n\nWhen you are creating functions or classes (a bit more on what these are in a bit) you can also create what are called doc strings that provide a defined location for content that is used to generate the help() information highlighted above and is also used by other systems for the automatic generation of documentation for packages that contain these doc strings. Creating a doc string is simple - just create a single or multi-line text string (more on this soon) that starts on the first indented line following the start of the definition of the function or class. For example: \n&gt;&gt;&gt;# we're going to create a documented function and then access the information about the function\n&gt;&gt;&gt;def doc_demo(some_text=\"Ill skewer yer gizzard, ye salty sea bass\"):\n... \"\"\"This function takes the provided text and prints it out in Pirate\n... \n... If a string is not provided for `some_text` a default message will be displayed\n... \"\"\"\n... out_string = \"Ahoy Matey. \" + some_text\n... print(out_string)\n&gt;&gt;&gt;help(doc_demo)\n&gt;&gt;&gt;doc_demo()\n&gt;&gt;&gt;doc_demo(\"Sail ho!\")\n\nStandard Objects\nAny programming language has at its foundation a collection of types or in Python's terminology objects. The standard objects of Python consist of the following:\n\nNumbers - integer, floating point, complex, and multiple-base defined numeric values\nStrings - immutable strings of characters, numbers, and symbols that are bounded by single- or double-quotes\nLists - an ordered collection of objects that is bounded by square-brackets - []. Elements in lists are extracted or referenced by their position in the list. For example, my_list[0] refers to the first item in the list, my_list[5] the sixth, and my_list[-1] to the last item in the list. \n\nDictionaries - an unordered collection of objects that are referenced by keys that allow for referring to those objexts by reference to those keys. Dictionaries are bounded by curley-brackets - {} with each element of the dictionary consisting of a key (string) and a value (object) separated by a colon :. Elements of a dictionary are extracted or referenced using their keys. for example:\nmy_dict = {\"key1\":\"value1\", \"key2\":36, \"key3\":[1,2,3]}\nmy_dict['key1'] returns \"value1\"\nmy_dict['key3'] returns [1,2,3]\n\n\n\nTuples - immutable lists that are bounded by parentheses = (). Referencing elements in a tuple is the same as referencing elements in a list above. \n\nFiles - objects that represent external files on the file system. Programs can interact with (e.g. read, write, append) external files through their representative file objects in the program.\nSets - unordered, collections of immutable objects (i.e. ints, floats, strings, and tuples) where membership in the set and uniqueness within the set are defining characteristics of the member objects. Sets are created using the set function on a sequence of objects. A specialized list of operators on sets allow for identifying union, intersection, and difference (among others) between sets. \nOther core types - Booleans, types, None\nProgram unit types - functions, modules, and classes for example\nImplementation-related types (not covered in this workshop)\n\nThese objects have their own sets of related methods (as we saw in the help() examples above) that enable their creation, and operations upon them.", "# Fun with types\n\nthis = 12\nthat = 15\nthe_other = \"27\"\nmy_stuff = [this,that,the_other,[\"a\",\"b\",\"c\",4]]\nmore_stuff = {\n \"item1\": this, \n \"item2\": that, \n \"item3\": the_other, \n \"item4\": my_stuff\n}\nthis + that\n\n# this won't work ...\n# this + that + the_other\n\n# ... but this will ...\nthis + that + int(the_other)\n\n# ...and this too\nstr(this) + str(that) + the_other", "Lists\nhttps://docs.python.org/3/library/stdtypes.html?highlight=lists#list\nLists are a type of collection in Python. Lists allow us to store sequences of items that are typically but not always similar. All of the following lists are legal in Python:", "# Separate list items with commas!\n\nnumber_list = [1, 2, 3, 4, 5]\nstring_list = ['apples', 'oranges', 'pears', 'grapes', 'pineapples']\ncombined_list = [1, 2, 'oranges', 3.14, 'peaches', 'grapes', 99.19876]\n\n# Nested lists - lists of lists - are allowed.\n\nlist_of_lists = [[1, 2, 3], \n ['oranges', 'grapes', 8], \n [['small list'], \n ['bigger', 'list', 55], \n ['url_1', 'url_2']\n ]\n ]", "There are multiple ways to create a list:", "# Create an empty list\n\nempty_list = []\n\n# As we did above, by using square brackets around a comma-separated sequence of items\n\nnew_list = [1, 2, 3]\n\n# Using the type constructor\n\nconstructed_list = list('purple')\n\n# Using a list comprehension\n\nresult_list = [i for i in range(1, 20)]", "We can inspect our lists:", "empty_list\n\nnew_list\n\nresult_list\n\nconstructed_list", "The above output for constructed_list may seem odd. Referring to the documentation, we see that the argument to the type constructor is an iterable, which according to the documentation is \"An object capable of returning its members one at a time.\" In our construtor statement above\n```\nUsing the type constructor\nconstructed_list = list('purple')\n```\nthe word 'purple' is the object - in this case a str (string) consisting of the word 'purple' - that when used to construct a list returns its members (individual letters) one at a time.\nCompare the outputs below:", "constructed_list_int = list(123)\n\nconstructed_list_str = list('123')\nconstructed_list_str", "Lists in Python are:\n\nmutable - the list and list items can be changed\nordered - list items keep the same \"place\" in the list\n\nOrdered here does not mean sorted. The list below is printed with the numbers in the order we added them to the list, not in numeric order:", "ordered = [3, 2, 7, 1, 19, 0]\nordered\n\n# There is a 'sort' method for sorting list items as needed:\n\nordered.sort()\nordered", "Info on additional list methods is available at https://docs.python.org/3/library/stdtypes.html?highlight=lists#mutable-sequence-types\nBecause lists are ordered, it is possible to access list items by referencing their positions. Note that the position of the first item in a list is 0 (zero), not 1!", "string_list = ['apples', 'oranges', 'pears', 'grapes', 'pineapples']\n\nstring_list[0]\n\n# We can use positions to 'slice' or select sections of a list:\n\nstring_list[3:] # start at index '3' and continue to the end\n\nstring_list[:3] # start at index '0' and go up to, but don't include index '3'\n\nstring_list[1:4] # start at index '1' and go up to and don't include index '4'\n\n# If we don't know the position of a list item, we can use the 'index()' method to find out.\n# Note that in the case of duplicate list items, this only returns the position of the first one:\n\nstring_list.index('pears')\n\nstring_list.append('oranges')\n\nstring_list\n\nstring_list.index('oranges')\n\n# one more time with lists and dictionaries\nlist_ex1 = my_stuff[0] + my_stuff[1] + int(my_stuff[2])\nprint(list_ex1)\n\n# we can use parentheses to split a continuous group of commands over multiple lines\nlist_ex2 = (\n str(my_stuff[0]) \n + str(my_stuff[1]) \n + my_stuff[2] \n + my_stuff[3][0]\n)\nprint(list_ex2)\n\ndict_ex1 = (\n more_stuff['item1']\n + more_stuff['item2']\n + int(more_stuff['item3'])\n)\nprint(dict_ex1)\n\ndict_ex2 = (\n str(more_stuff['item1'])\n + str(more_stuff['item2'])\n + more_stuff['item3']\n)\nprint(dict_ex2)\n\n\n\n# Now try it yourself ...\n# print out the phrase \"The answer: 42\" using the following \n# variables and one or more of your own and the 'print()' function\n# (remember spaces are characters as well)\n\nstart = \"The\"\nanswer = 42\n", "Operators\nIf objects are the nouns, operators are the verbs of a programming language. We've already seen examples of some operators: assignment with the = operator, arithmetic addition and string concatenation with the + operator, arithmetic division with the / and - operators, and comparison with the &gt; operator. Different object types have different operators that may be used with them. The Python Documentation provides detailed information about the operators and their functions as they relate to the standard object types described above. \nFlow Control and Logical Tests\nFlow control commands allow for the dynamic execution of parts of the program based upon logical conditions, or processing of objects within an iterable object (like a list or dictionary). Some key flow control commands in python include:\n\n\nwhile-else loops that continue to run until the termination test is False or a break command is issued within the loop:\ndone = False\ni = 0\nwhile not done:\n i = i+1\n if i &gt; 5: done = True\n\n\n\nif-elif-else statements defined alternative blocks of code that are executed if a test condition is met:\ndo_something = \"what?\"\nif do_something == \"what?\":\n print(do_something)\nelif do_something == \"where?\":\n print(\"Where are we going?\")\nelse:\n print(\"I guess nothing is going to happen\")\n\n\n\nfor loops allow for repeated execution of a block of code for each item in a python sequence such as a list or dictionary. For example:\nmy_stuff = ['a', 'b', 'c']\nfor item in my_stuff:\n print(item)\n\na\nb\nc" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
Kaggle/learntools
notebooks/computer_vision/raw/tut5.ipynb
apache-2.0
[ "<!--TITLE:Custom Convnets-->\nIntroduction\nNow that you've seen the layers a convnet uses to extract features, it's time to put them together and build a network of your own!\nSimple to Refined\nIn the last three lessons, we saw how convolutional networks perform feature extraction through three operations: filter, detect, and condense. A single round of feature extraction can only extract relatively simple features from an image, things like simple lines or contrasts. These are too simple to solve most classification problems. Instead, convnets will repeat this extraction over and over, so that the features become more complex and refined as they travel deeper into the network.\n<figure>\n<img src=\"https://i.imgur.com/VqmC1rm.png\" alt=\"Features extracted from an image of a car, from simple to refined.\" width=800>\n</figure>\n\nConvolutional Blocks\nIt does this by passing them through long chains of convolutional blocks which perform this extraction.\n<figure>\n<img src=\"https://i.imgur.com/pr8VwCZ.png\" width=\"400\" alt=\"Extraction as a sequence of blocks.\">\n</figure>\n\nThese convolutional blocks are stacks of Conv2D and MaxPool2D layers, whose role in feature extraction we learned about in the last few lessons.\n<figure>\n<!-- <img src=\"./images/2-block-crp.png\" width=\"400\" alt=\"A kind of extraction block: convolution, ReLU, pooling.\"> -->\n<img src=\"https://i.imgur.com/8D6IhEw.png\" width=\"400\" alt=\"A kind of extraction block: convolution, ReLU, pooling.\">\n</figure>\n\nEach block represents a round of extraction, and by composing these blocks the convnet can combine and recombine the features produced, growing them and shaping them to better fit the problem at hand. The deep structure of modern convnets is what allows this sophisticated feature engineering and has been largely responsible for their superior performance.\nExample - Design a Convnet\nLet's see how to define a deep convolutional network capable of engineering complex features. In this example, we'll create a Keras Sequence model and then train it on our Cars dataset.\nStep 1 - Load Data\nThis hidden cell loads the data.", "#$HIDE_INPUT$\n# Imports\nimport os, warnings\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing import image_dataset_from_directory\n\n# Reproducability\ndef set_seed(seed=31415):\n np.random.seed(seed)\n tf.random.set_seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n os.environ['TF_DETERMINISTIC_OPS'] = '1'\nset_seed()\n\n# Set Matplotlib defaults\nplt.rc('figure', autolayout=True)\nplt.rc('axes', labelweight='bold', labelsize='large',\n titleweight='bold', titlesize=18, titlepad=10)\nplt.rc('image', cmap='magma')\nwarnings.filterwarnings(\"ignore\") # to clean up output cells\n\n\n# Load training and validation sets\nds_train_ = image_dataset_from_directory(\n '../input/car-or-truck/train',\n labels='inferred',\n label_mode='binary',\n image_size=[128, 128],\n interpolation='nearest',\n batch_size=64,\n shuffle=True,\n)\nds_valid_ = image_dataset_from_directory(\n '../input/car-or-truck/valid',\n labels='inferred',\n label_mode='binary',\n image_size=[128, 128],\n interpolation='nearest',\n batch_size=64,\n shuffle=False,\n)\n\n# Data Pipeline\ndef convert_to_float(image, label):\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n return image, label\n\nAUTOTUNE = tf.data.experimental.AUTOTUNE\nds_train = (\n ds_train_\n .map(convert_to_float)\n .cache()\n .prefetch(buffer_size=AUTOTUNE)\n)\nds_valid = (\n ds_valid_\n .map(convert_to_float)\n .cache()\n .prefetch(buffer_size=AUTOTUNE)\n)\n", "Step 2 - Define Model\nHere is a diagram of the model we'll use:\n<figure>\n<!-- <img src=\"./images/2-convmodel-1.png\" width=\"200\" alt=\"Diagram of a convolutional model.\"> -->\n<img src=\"https://i.imgur.com/U1VdoDJ.png\" width=\"250\" alt=\"Diagram of a convolutional model.\">\n</figure>\n\nNow we'll define the model. See how our model consists of three blocks of Conv2D and MaxPool2D layers (the base) followed by a head of Dense layers. We can translate this diagram more or less directly into a Keras Sequential model just by filling in the appropriate parameters.", "from tensorflow import keras\nfrom tensorflow.keras import layers\n\nmodel = keras.Sequential([\n\n # First Convolutional Block\n layers.Conv2D(filters=32, kernel_size=5, activation=\"relu\", padding='same',\n # give the input dimensions in the first layer\n # [height, width, color channels(RGB)]\n input_shape=[128, 128, 3]),\n layers.MaxPool2D(),\n\n # Second Convolutional Block\n layers.Conv2D(filters=64, kernel_size=3, activation=\"relu\", padding='same'),\n layers.MaxPool2D(),\n\n # Third Convolutional Block\n layers.Conv2D(filters=128, kernel_size=3, activation=\"relu\", padding='same'),\n layers.MaxPool2D(),\n\n # Classifier Head\n layers.Flatten(),\n layers.Dense(units=6, activation=\"relu\"),\n layers.Dense(units=1, activation=\"sigmoid\"),\n])\nmodel.summary()", "Notice in this definition is how the number of filters doubled block-by-block: 64, 128, 256. This is a common pattern. Since the MaxPool2D layer is reducing the size of the feature maps, we can afford to increase the quantity we create.\nStep 3 - Train\nWe can train this model just like the model from Lesson 1: compile it with an optimizer along with a loss and metric appropriate for binary classification.", "model.compile(\n optimizer=tf.keras.optimizers.Adam(epsilon=0.01),\n loss='binary_crossentropy',\n metrics=['binary_accuracy']\n)\n\nhistory = model.fit(\n ds_train,\n validation_data=ds_valid,\n epochs=40,\n verbose=0,\n)\n\n\nimport pandas as pd\n\nhistory_frame = pd.DataFrame(history.history)\nhistory_frame.loc[:, ['loss', 'val_loss']].plot()\nhistory_frame.loc[:, ['binary_accuracy', 'val_binary_accuracy']].plot();", "This model is much smaller than the VGG16 model from Lesson 1 -- only 3 convolutional layers versus the 16 of VGG16. It was nevertheless able to fit this dataset fairly well. We might still be able to improve this simple model by adding more convolutional layers, hoping to create features better adapted to the dataset. This is what we'll try in the exercises.\nConclusion\nIn this tutorial, you saw how to build a custom convnet composed of many convolutional blocks and capable of complex feature engineering. \nYour Turn\nIn the exercises, you'll create a convnet that performs as well on this problem as VGG16 does -- without pretraining! Try it now!" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
GoogleCloudPlatform/python-docs-samples
people-and-planet-ai/image-classification/README.ipynb
apache-2.0
[ "#@title ###### Licensed to the Apache Software Foundation (ASF), Version 2.0 (the \"License\")\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.", "Monitor wildlife health via image classification\n🦜🦧 🐘🦩🦋 🦇 🦀 🦔 🐇 🦫 🦏 🐆 🐗 🦙 🦥 🦎 🦃\n\nTime estimate: 2 hours 15 minutes\nCost estimate: less than \\$30.00 (free if you use \\$300 Cloud credits)\n\n\nWatch the video in YouTube<br> \n📜 Read more about this sample in the blog post.\n\nThis is an interactive notebook that contains all of the code necessary to train an ML model for image classification.\nThis model is trained to recognize animal species from\ncamera trap\npictures.\n🙈 Using this interactive notebook\nClick the run icons ▶️ of each section within this notebook. \nThis notebook code lets you train and deploy an ML model, as well as test its accuracy, from end-to-end. When you run a code cell, the code runs in the notebook's runtime, so you're not making any changes to your personal computer.\n\n🛎️ To avoid any errors, wait for each section to finish in their order before clicking the next “run” icon.\n\nThis sample must be connected to a Google Cloud project, but nothing else is needed other than your Google Cloud project.\nYou can use an existing project and the cost will be less than \\$30. Alternatively, you can create a new Cloud project with cloud credits for free\n🚴‍♀️ Steps included\nThe notebook leverages camera trap images dataset from the\nWCS Camera Traps dataset\nfrom the Labeled Information Library of Alexandria: Biology and Conservation (LILA) organization.\nHere's a quick summary of what you’ll go through:\n\n\nCreate a database of image metadata (~5 minutes to complete, costs a few cents):\n in a\n BigQuery\n table with all the image file names along with their respective category. \n\n\nTrain an image classifier (~2 hours to complete, costs ~$25.00):\n With some desired criteria, a\n Dataflow\n pipeline creates a balanced dataset from the metadata database.\n It then physically downloads the necessary images from LILA into\n Cloud Storage,\n imports the data into\n AI Platform Unified,\n and starts the model training job.\n\n\nDeploy an ML model (costs $1.25 for every hour the model is deployed online… so complete the “delete model” step soon):\n After the model finishes training, we look at the results and deploy it into a Cloud endpoint in AI Platform Unified.\n\n\nClassify images with the model:\n We send some images to the model and get back the model's classification predictions.\n\n\n(Optional) Delete the project to avoid ongoing costs.\n\n\n✨ Before you begin, you need to…\n\nDecide on creating a new\n free project\n (recommended) or using an existing one.\n Then copy the project ID and paste it in the google_cloud_project field in the \"Entering project details” section below.\n\n\n💡 If you don't plan to keep the resources that you create via this sample, we recommend creating a new project instead of selecting an existing project.\nAfter you finish these steps, you can delete the project, removing all the resources associated in bulk.\n\n\n\nClick here\n to enable the following APIs in your Google Cloud project:\n Dataflow and AI Platform.\n\n\nMake sure that billing is enabled for your Google Cloud project,\n click here\n to learn how to confirm that billing is enabled.\n\n\nClick here\n to create a Cloud Storage bucket.\n Then copy the bucket’s name and paste it in the cloud_storage_bucket field in the “Entering project details” section below.\n\n\n\n🛎️ Make sure it's a regional bucket in a location where\nAI Platform is available.\n\n\nCreate a BigQuery dataset.\n Then copy the dataset ID and paste it in the bigquery_dataset field in the “Entering project details” section below.\n\n\n💡 You can use the name samples for your dataset.\n\n⛏️ Preparing the project environment\nClick run ▶️ for the following cells to download and install the necessary libraries and resources for this solution.\n\n💡 You can optionally view the entire\ncode in GitHub.", "# We need libffi-dev to launch the Dataflow pipeline.\n!apt-get -qq install libffi-dev\n\n# Clone the python-docs-samples respository.\n!git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git\n\n# Navigate to the sample code directory.\n%cd python-docs-samples/people-and-planet-ai/image-classification\n\n# Install the sample requirements.\n!pip install --quiet -U pip\n!pip install -r requirements.txt", "🛎️ [DON’T PANIC] It’s safe to ignore the warnings.\nWhen we pip install the requirements, there might be some warnings about conflicting dependency versions.\nFor the scope of this sample, that’s ok.\n⚠️ Restart the runtime: Running the previous cell just updated some libraries and requires to restart the runtime to load those libraries correctly.\nIn the top-left menu, click \"Runtime\" > \"Restart runtime\".", "# After restarting the runtime, navigate back to the sample code directory.\n%cd python-docs-samples/people-and-planet-ai/image-classification", "✏️ Entering project details\nFill these in with the Google Cloud project resources you just created.", "google_cloud_project = \"\" #@param {type:\"string\"}\ncloud_storage_bucket = \"\" #@param {type:\"string\"}\nbigquery_dataset = \"samples\" #@param {type:\"string\"}\n\n# Validate inputs.\nif not google_cloud_project:\n raise ValueError('Please provide your google_cloud_project')\nif not cloud_storage_bucket:\n raise ValueError('Please provide your cloud_storage_bucket')\n\n# Authenticate to use the Google Cloud resources.\ntry:\n from google.colab import auth\n auth.authenticate_user()\n print('Authenticated')\nexcept ModuleNotFoundError:\n import os\n if os.environ.get('GOOGLE_APPLICATION_CREDENTIALS') is None:\n raise ValueError('Please set your GOOGLE_APPLICATION_CREDENTIALS environment variable to your service account JSON file path.')\n print(f\"GOOGLE_APPLICATION_CREDENTIALS: {service_account_file}\")\n\n%env GOOGLE_CLOUD_PROJECT={google_cloud_project}", "Click the run button ▶️ for the cells above.\nPaste the \"verification code\" that is presented, and press [ENTER] to authenticate.\n\nRun the following cell, you can leave them with these values or change them if you prefer.", "cloud_storage_directory = \"samples/wildlife-insights\" #@param {type:\"string\"}\nbigquery_table = \"wildlife_images_metadata\" #@param {type:\"string\"}\nai_platform_name_prefix = \"wildlife_classifier\" #@param {type:\"string\"}\nregion = \"us-central1\" #@param {type:\"string\"}", "🛎 Make sure the region matches the region you chose for your Cloud Storage bucket.\n\n🐻 Creating the database of images metadata\nTo build our model we need data, so we create a database table from the metadata of all the images.\nThis is a one-time only process.\nClick run on the first Dataflow pipeline to create the images metadata table in BigQuery, which contains 2 fields of information from each image from the JSON file in WCS Camera Traps database:\n\ncategory: The species we want to predict, this is our label.\nfile_name: The file path where the image file is located.\n\nWe do some very basic data cleaning like discarding rows with categories that are note useful like #ref!, empty, unidentifiable, unidentified, unknown.\n\n💡 As you collect new images from the field via your own camera traps, you continue to store the new image’s category and file name into the BigQuery table.\nYou could extend this sample to collect more pertinent data for reporting purposes such as location, date, etc.", "# [One time only] Create the images metadata table.\n!python create_images_metadata_table.py \\\n --bigquery-dataset \"{bigquery_dataset}\" \\\n --bigquery-table \"{bigquery_table}\" \\\n --runner \"DataflowRunner\" \\\n --job_name \"wildlife-images-metadata-`date +%Y%m%d-%H%M%S`\" \\\n --project \"{google_cloud_project}\" \\\n --temp_location \"gs://{cloud_storage_bucket}/{cloud_storage_directory}/temp\" \\\n --region \"{region}\" \\\n --worker_machine_type \"n1-standard-2\"", "<button>\n\nView create_images_metadata_table.py\n</button>\n\n🛎️ We need at least n1-standard-2 worker machines due to large RAM usage when parsing the metadata JSON file.\n\nYou can look up the job details in the Dataflow jobs page:\n\nconsole.cloud.google.com/dataflow/jobs\n\n👟 Training the image classifier\nOne of the challenges of a camera trap dataset is that it usually contains a different number of images per species, making it very unbalanced.\nFor example, there are tens of thousands of pictures of some species like tayassu pecari, while only a handful of pictures of other species like tolypeutes matacus.\nIn emojis, the data looks skewed like this: \n\n🦜🦜🦜🦜🦜 (5 Green Macaws)\n🦧 (1 Bornean orangutan)\n🐘🐘🐘 (3 Sumatran elephant)\n🐗🐗🐗🐗🐗🐗🐗🐗🐗🐗🐗🐗 (12 wild boars)\n\nThis could introduce a\nbias\ninto your model which can lead to it predicting a species just because it's more common rather than identifying it by it’s actual features.\nSo instead of using the entire database of images, we leverage Dataflow to create a balanced dataset by specifying the minimum and maximum number of images we want for every category.\nFor categories with too many images, it chooses at most max_images_per_class randomly selected images.\nAnd categories with less than min_images_per_class are discarded as \"too little information to teach our model to classify this species\".\n\n💡 For this sample, we defaulted to using between 50 and 100 images per species/class to keep the training dataset small. This reduces the training time and the potential cost of prediction accuracy.\nFeel free to play around with other numbers.\n\nOnce Dataflow chooses what images meet our criteria by counting the number of species per categories in BigQuery, it\nlazily\ndownloads the actual JPEG images into Cloud Storage from the Lila Science database using it’s file name.\nThis means we are only preprocessing the images we need for training rather than processing the entire dataset of JPEG images.\nWhen retraining in the future, if an image already exists in Cloud Storage, there's nothing else to do for that image, as we have created a cache for images that have already been processed in our prior run.\nAfter all the images are stored in Cloud Storage, Dataflow creates a\nCSV file for AI Platform.\nEach row includes the Cloud Storage path of an image, alongside with the category, our label.\nNext, Dataflow tells AI Platform to import the CSV file and create a dataset from it. This is where the Dataflow job stops and AI Platform begins to train the model.\nWe let AI Platform do the data splitting automatically for us. By default, it uses 80% of the data for training, 10% for validation, and 10% for testing. See About data splits for AI Platform models for more information.\n\n🛎️ For simplicity, in this sample we are training a CLOUD model.\nThis allows us to deploy it to an HTTP endpoint and get predictions via the browser.\nSee Train an Edge model\nfor information on how to train a model for a microcontroller.", "min_images_per_class = 50 #@param {type:\"integer\"}\nmax_images_per_class = 100 #@param {type:\"integer\"}\n\n# Create a balanced dataset and signal AI Platform to train a model.\n!python train_model.py \\\n --cloud-storage-path \"gs://{cloud_storage_bucket}/{cloud_storage_directory}\" \\\n --bigquery-dataset \"{bigquery_dataset}\" \\\n --bigquery-table \"{bigquery_table}\" \\\n --ai-platform-name-prefix \"{ai_platform_name_prefix}\" \\\n --min-images-per-class \"{min_images_per_class}\" \\\n --max-images-per-class \"{max_images_per_class}\" \\\n --runner \"DataflowRunner\" \\\n --job_name \"wildlife-train-model-`date +%Y%m%d-%H%M%S`\" \\\n --project \"{google_cloud_project}\" \\\n --temp_location \"gs://{cloud_storage_bucket}/{cloud_storage_directory}/temp\" \\\n --requirements_file \"requirements.txt\" \\\n --region \"{region}\"", "<button>\n\nView train_model.py\n</button>\n\n🛎️ It can take several minutes for the job to show up in the\nDataflow jobs page.\nSee [ARROW-8983] for more information.\n\nTraining the AI Platform model can take a while, depending on the dataset size and the training budget you allow.\n\n💡 You can adjust the training budget using the --budget-milli-node-hours flag. We default to 8000 which is the minimum.\nSee the pricing page and\ntrain_budget_milli_node_hours\nfor more information.\n\n🐣 Deploying the model\n\n🛎 Make sure your model has finished training.\nYou can look at the training progress on the\nAI Platform training jobs page.\n💡 If you were disconnected from the session due to inactivity, please make sure to re-run the cells at the \"Before you begin\" section at the beginning of the notebook.\n\nWe need to deploy the trained model into an endpoint to get predictions from it.\nSince we don't have a micro controller readily available, let’s deploy it in the cloud as an HTTP endpoint.\nYou can deploy it through the Cloud Console: console.cloud.google.com/ai/platform/models\nOr alternatively, you can deploy it through the API by running the following cells:", "# First we need the model path, we can get it with gcloud.\n# 💡 If you get an error here, please make sure your model has finished training.\ncmd_output = !gcloud beta ai models list \\\n --project {google_cloud_project} \\\n --region {region} \\\n --filter \"display_name:{ai_platform_name_prefix}*\" \\\n --format \"table[no-heading](display_name,name)\" 2>/dev/null\nmodels = sorted([line.split() for line in cmd_output])\nmodel_path = models[0][1]\n\nprint(f\"model_path: {model_path}\")\n\n# Create an endpoint and deploy the model to it.\n!python deploy_model.py \\\n --project {google_cloud_project} \\\n --region {region} \\\n --model-path {model_path} \\\n --model-endpoint-name {ai_platform_name_prefix}", "<button>\n\nView deploy_model.py\n</button>\n📺 Visualizing classification of images online\nNow that we have a deployed model, we can classify images using it.\nFirst, lets define some functions to help us visualize and navigate the images, click run:", "import io\nimport requests\nfrom PIL import Image\nfrom IPython.display import display\n\nfrom google.cloud import bigquery\n\n\ndef display_image(image_file, width=400):\n base_url = 'https://lilablobssc.blob.core.windows.net/wcs-unzipped'\n image_bytes = requests.get(f\"{base_url}/{image_file}\").content\n if b'<Error>' in image_bytes:\n raise ValueError(f\"Error requesting image: {base_url}/{image_file}\\n{image_bytes.decode('utf-8')}\")\n image = Image.open(io.BytesIO(image_bytes))\n display(image.resize((int(width), int(width / image.size[0] * image.size[1]))))\n\n\ndef display_samples_for_category(category, num_samples=3, width=400):\n client = bigquery.Client()\n query_job = client.query(f\"\"\"\n SELECT file_name\n FROM `{google_cloud_project}.{bigquery_dataset}.{bigquery_table}`\n WHERE category = '{category}'\n LIMIT {num_samples}\n \"\"\")\n\n for row in query_job:\n image_file = row['file_name']\n print(f\"{category}: {image_file}\")\n display_image(image_file, width)", "Now run the following cell to get the model endpoint ID, which we need to make predictions.", "# First we need the endpoint ID, we can get it with gcloud.\nstdout = !gcloud beta ai endpoints list \\\n --project {google_cloud_project} \\\n --region {region} \\\n --filter \"display_name={ai_platform_name_prefix}\" \\\n --format \"table[no-heading](ENDPOINT_ID)\" 2>/dev/null\nmodel_endpoint_id = stdout[0]\n\nprint(f\"model_endpoint_id: {model_endpoint_id}\")\n\ndef predict(image_file):\n # First, display the image, and then we run our prediction script.\n display_image(image_file)\n !python predict.py \\\n --project \"{google_cloud_project}\" \\\n --region \"{region}\" \\\n --model-endpoint-id \"{model_endpoint_id}\" \\\n --image-file \"{image_file}\"", "<button>\n\nView predict.py\n</button>\nNow, run the following cells to see what our model thinks about each of the following images.\nThe model gives us a list of species it predicts it is, alongside with the confidence score for each prediction.", "# Species: dicerorhinus sumatrensis\npredict('animals/0325/1529.jpg')\n\n# Species: didelphis imperfecta\npredict('animals/0667/1214.jpg')\n\n# Species: tapirus indicus\npredict('animals/0036/0072.jpg')\n\n# Species: leopardus wiedii\npredict('animals/0000/1705.jpg')\n\n# Species: hemigalus derbyanus\npredict('animals/0036/0566.jpg')\n\n# Species: dasypus novemcinctus\npredict('animals/0000/0425.jpg')", "🕵️ While analyzing the model’s evaluation, you may notice that many species of the same family are very similar and it may be confusing the model. This means it might be worth trying to classify the image to a family instead of a specific species, or get more images from different angles/proximity to detect it better.\n🧹 Cleaning up to avoid additional costs\nTo avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.\nIf you wish to delete the project you created for this tutorial (it’s the easiest way to eliminate billing), here are the steps:\nDeleting the project\nThe easiest way to eliminate billing is to delete the project that you created for the tutorial.\nTo delete the project:\n\n⚠️ Caution: Deleting a project has the following effects:\n\nEverything in the project is deleted. If you used an existing project for this tutorial, when you delete it, you also delete any other work you've done in the project.\nCustom project IDs are lost. When you created this project, you might have created a custom project ID that you want to use in the future. To preserve the URLs that use the project ID, such as an appspot.com URL, delete selected resources inside the project instead of deleting the whole project.\n\nIf you plan to explore multiple tutorials and quickstarts, reusing projects can help you avoid exceeding project quota limits.\n\n\nIn the Cloud Console, go to the Manage resources page.\n\n<button>\nGo to Manage resources\n</button>\n\n\nIn the project list, select the project that you want to delete, and then click Delete.\n\n\nIn the dialog, type the project ID, and then click Shut down to delete the project.\n\n\n🎉 Congratulations, you have successfully completed this code lab!\n🙌 You made it this far, congrats.\nDive deeper by visiting the\ncode on GitHub.\n\n🛎️ Was this a meaningful project for you? If so you can you share your experience in\nthese 2 quick questions here." ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
sdpython/ensae_teaching_cs
_doc/notebooks/td2a/td2a_some_nlp.ipynb
mit
[ "2A.ml - Texte et machine learning\nRevue de méthodes de word embedding statistiques (~ NLP) ou comment transformer une information textuelle en vecteurs dans un espace vectoriel (features) ? Deux exercices sont ajoutés à la fin.", "from jyquickhelper import add_notebook_menu\nadd_notebook_menu()", "Données\nNous allons travailler sur des données twitter collectées avec le mot-clé macron : tweets_macron_sijetaispresident_201609.zip.", "from ensae_teaching_cs.data import twitter_zip\ndf = twitter_zip(as_df=True)\ndf.head(n=2).T\n\ndf.shape", "5000 tweets n'est pas assez pour tirer des conclusions mais cela donne une idée. On supprime les valeurs manquantes.", "data = df[[\"retweet_count\", \"text\"]].dropna()\ndata.shape", "Construire une pondération\nLe texte est toujours délicat à traiter. Il n'est pas toujours évident de sortir d'une information binaire : un mot est-il présent ou pas. Les mots n'ont aucun sens numérique. Une liste de tweets n'a pas beaucoup de sens à part les trier par une autre colonne : les retweet par exemple.", "data.sort_values(\"retweet_count\", ascending=False).head()", "Sans cette colonne qui mesure la popularité, il faut trouver un moyen d'extraire de l'information. On découpe alors en mots et on constuire un modèle de langage : les n-grammes. Si un tweet est constitué de la séquence de mots $(m_1, m_2, ..., m_k)$. On définit sa probabilité comme :\n$$P(tweet) = P(w_1, w_2) P(w_3 | w_2, w_1) P(w_4 | w_3, w_2) ... P(w_k | w_{k-1}, w_{k-2})$$\nDans ce cas, $n=3$ car on suppose que la probabilité d'apparition d'un mot ne dépend que des deux précédents. On estime chaque n-grammes comme suit :\n$$P(c | a, b) = \\frac{ # (a, b, c)}{ # (a, b)}$$\nC'est le nombre de fois où on observe la séquence $(a,b,c)$ divisé par le nombre de fois où on observe la séquence $(a,b)$.\nTokenisation\nDécouper en mots paraît simple tweet.split() et puis il y a toujours des surprises avec le texte, la prise en compte des tirets, les majuscules, les espaces en trop. On utilse un tokenizer dédié : TweetTokenizer ou un tokenizer qui prend en compte le langage.", "from nltk.tokenize import TweetTokenizer\ntknzr = TweetTokenizer(preserve_case=False)\ntokens = tknzr.tokenize(data.loc[0, \"text\"])\ntokens", "n-grammes\n\nN-Gram-Based Text Categorization: Categorizing Text With Python", "from nltk.util import ngrams\ngenerated_ngrams = ngrams(tokens, 4, pad_left=True, pad_right=True)\nlist(generated_ngrams)", "Exercice 1 : calculer des n-grammes sur les tweets\nNettoyage\nTous les modèles sont plus stables sans les stop-words, c'est-à-dire tous les mots présents dans n'importe quel documents et qui n'apporte pas de sens (à, de, le, la, ...). Souvent, on enlève les accents, la ponctuation... Moins de variabilité signifie des statistiques plus fiable.\nExercice 2 : nettoyer les tweets\nVoir stem.\nStructure de graphe\nOn cherche cette fois-ci à construire des coordonnées pour chaque tweet.\nmatrice d'adjacence\nUne option courante est de découper chaque expression en mots puis de créer une matrice expression x mot ou chaque case indique la présence d'un mot dans une expression.", "from sklearn.feature_extraction.text import CountVectorizer\ncount_vect = CountVectorizer()\ncounts = count_vect.fit_transform(data[\"text\"])\ncounts.shape", "On aboutit à une matrice sparse ou chaque expression est représentée à une vecteur ou chaque 1 représente l'appartenance d'un mot à l'ensemble.", "type(counts)\n\ncounts[:5,:5].toarray()\n\ndata.loc[0,\"text\"]\n\ncounts[0,:].sum()", "td-idf\nCe genre de technique produit des matrices de très grande dimension qu'il faut réduire. On peut enlever les mots rares ou les mots très fréquents. td-idf est une technique qui vient des moteurs de recherche. Elle construit le même type de matrice (même dimension) mais associe à chaque couple (document - mot) un poids qui dépend de la fréquence d'un mot globalement et du nombre de documents contenant ce mot.\n$$idf(t) = \\log \\frac{# D}{#{d \\; | \\; t \\in d }}$$\nOù :\n\n$#D$ est le nombre de tweets\n$#{d \\; | \\; t \\in d }$ est le nombre de tweets contenant le mot $t$\n\n$f(t,d)$ est le nombre d'occurences d'un mot $t$ dans un document $d$.\n$$tf(t,d) = \\frac{1}{2} + \\frac{1}{2} \\frac{f(t,d)}{\\max_{t' \\in d} f(t',d)}$$\nOn construit le nombre $tfidf(t,f)$\n$$tdidf(t,d) = tf(t,d) idf(t)$$\nLe terme $idf(t)$ favorise les mots présent dans peu de documents, le terme $tf(t,f)$ favorise les termes répétés un grand nombre de fois dans le même document. On applique à la matrice précédente.", "from sklearn.feature_extraction.text import TfidfTransformer\ntfidf = TfidfTransformer()\nres = tfidf.fit_transform(counts)\nres.shape\n\nres[0,:].sum()", "Exercice 3 : tf-idf sans mot-clés\nLa matrice ainsi créée est de grande dimension. Il faut trouver un moyen de la réduire avec TfidfVectorizer.\nword2vec\n\nword2vec From theory to practice\nEfficient Estimation of Word Representations in Vector Space\nword2vec\n\nCet algorithme part d'une répresentation des mots sous forme de vecteur en un espace de dimension N = le nombre de mots distinct. Un mot est représenté par $(0,0, ..., 0, 1, 0, ..., 0)$. L'astuce consiste à réduire le nombre de dimensions en compressant avec une ACP, un réseau de neurones non linéaires.", "sentences = [tknzr.tokenize(_) for _ in data[\"text\"]]\nsentences[0]\n\nimport gensim, logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\nmodel = gensim.models.Word2Vec(sentences, min_count=1)\n\nmodel.wv.similar_by_word(\"fin\")\n\nmodel.wv[\"fin\"].shape\n\nmodel.wv[\"fin\"]", "Tagging\nL'objectif est de tagger les mots comme déterminer si un mot est un verbe, un adjectif ...\ngrammar\nVoir html.grammar.\nCRF\nVoir CRF\nHMM\nVoir HMM.\nClustering\nUne fois qu'on a des coordonnées, on peut faire plein de choses.\nLDA\n\nLatent Dirichlet Application\nLatentDirichletAllocation", "from sklearn.feature_extraction.text import TfidfVectorizer\n\ntfidf_vectorizer = TfidfVectorizer(max_df=0.95, min_df=2,\n max_features=1000)\ntfidf = tfidf_vectorizer.fit_transform(data[\"text\"])\n\ntfidf.shape\n\nfrom sklearn.decomposition import NMF, LatentDirichletAllocation\nlda = LatentDirichletAllocation(n_components=10, max_iter=5,\n learning_method='online',\n learning_offset=50.,\n random_state=0)\n\nlda.fit(tfidf)\n\ntf_feature_names = tfidf_vectorizer.get_feature_names()\ntf_feature_names[100:103]\n\ndef print_top_words(model, feature_names, n_top_words):\n for topic_idx, topic in enumerate(model.components_):\n print(\"Topic #%d:\" % topic_idx)\n print(\" \".join([feature_names[i]\n for i in topic.argsort()[- n_top_words - 1:][::-1]]))\n print()\n\nprint_top_words(lda, tf_feature_names, 10)\n\ntr = lda.transform(tfidf)\ntr[:5]\n\ntr.shape\n\nimport pyLDAvis\nimport pyLDAvis.sklearn\npyLDAvis.enable_notebook()\n\npyLDAvis.sklearn.prepare(lda, tfidf, tfidf_vectorizer)", "Exercice 4 : LDA\nRecommencer en supprimant les stop-words pour avoir des résultats plus propres." ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
CUBoulder-ASTR2600/lectures
lecture_12_differentiation.ipynb
isc
[ "Numerical Differentiation", "%matplotlib inline\n\nimport numpy as np\nimport matplotlib.pyplot as pl", "Applications:\n\nDerivative difficult to compute analytically\nRate of change in a dataset\nYou have position data but you want to know velocity\nFinding extrema\nImportant for fitting models to data (ASTR 3800)\nMaximum likelihood methods\nTopology: finding peaks and valleys (place where slope is zero)\n\nTopology Example: South Pole Aitken Basin (lunar farside)\nInteresting:\n\nOldest impact basin in the solar system\nImportant for studies of solar system formation\nPermananently shadowed craters\nHigh concentration of hydrogen (e.g., LCROSS mission)!\nGood place for an observatory (e.g., the Lunar Radio Array concept)!", "from IPython.display import Image\n\nImage(url='http://wordlesstech.com/wp-content/uploads/2011/11/New-Map-of-the-Moon-2.jpg')", "Question\n\nImage you're planning a mission to the South Pole Aitken Basin and want to explore some permanently shadowed craters. What factors might you consider in planning out your rover's landing site and route?\n\nMost rovers can tolerate grades up to about 20%, For reference, the grade on I-70 near Eisenhower Tunnel is about 6%.\nDifferentiation Review\nNumerical Derivatives on a Grid (Text Appendix B.2)", "def forwardDifference(f, x, h):\n \"\"\"\n A first order differentiation technique.\n \n Parameters\n ----------\n f : function to be differentiated\n x : point of interest\n h : step-size to use in approximation\n \"\"\"\n return (f(x + h) - f(x)) / h # From our notes\n\ndef centralDifference(f, x, h):\n \"\"\"\n A second order differentiation technique.\n \n Also known as `symmetric difference quotient.\n \n Parameters\n ----------\n f : function to be differentiated\n x : point of interest\n h : step-size to use in approximation\n\n \"\"\"\n return (f(x + h) - f(x - h)) / (2.0 * h) # From our notes\n\nnp.linspace(1,10,100).shape\n\ndef derivative(formula, func, xLower, xUpper, n): \n \"\"\"\n Differentiate func(x) at all points from xLower\n to xUpper with n *equally spaced* points.\n \n The differentiation formula is given by \n formula(func, x, h).\n \"\"\"\n h = (xUpper - xLower) / float(n) # Calculate the derivative step size\n xArray = np.linspace(xLower, xUpper, n) # Create an array of x values\n derivArray = np.zeros(n) # Create an empty array for the derivative values\n \n for index in range(1, n - 1): # xrange(start, stop, [step])\n derivArray[index] = formula(func, xArray[index], h) # Calculate the derivative for the current\n # x value using the formula passed in\n\n return (xArray[1:-1], derivArray[1:-1]) # This returns TWO things:\n # x values and the derivative values", "Notice that we don't calculate the derivative at the end points because there are no points beyond them to difference with.\nQ. So, what would happen without the [1:-1] in the return statement?", "def derivative2(formula, func, xLower, xUpper, n): \n \"\"\"\n Differentiate func(x) at all points from xLower\n to xUpper with n+1 *equally spaced* points.\n The differentiation formula is given by \n formula(func, x, h).\n \"\"\"\n h = (xUpper - xLower) / float(n) # Calculate the derivative step size\n xArray = np.linspace(xLower, xUpper, n) # Create an array of x values\n derivArray = np.zeros(n) # Create an empty array for the derivative values\n \n for index in range(0, n): # xrange(start, stop, [step])\n derivArray[index] = formula(func, xArray[index], h) # Calculate the derivative for the current\n # x value using the formula passed in\n\n return (xArray, derivArray) # This returns TWO things:\n # x values and the derivative values", "Example: Differentiate $\\sin(x)$\nWe know the answer:\n$$\\frac{d}{dx} \\left[\\sin(x)\\right] = \\cos(x)$$", "tau = 2*np.pi\n\nx = np.linspace(0, tau, 100)\n\n# Plot sin and cos\npl.plot(x, np.sin(x), color='k');\npl.plot(x, np.cos(x), color='b');\n\n# Compute derivative using central difference formula\nxder, yder = derivative2(centralDifference, np.sin, 0, tau, 10) \n\n# Plot numerical derivative as scatter plot\npl.scatter(xder, yder, color='g', s=100, marker='+', lw=2);\n# s controls marker size (experiment with it)\n# lw = \"linewidth\" in pixels", "Notice that the points miss the curve.\nQ. How can we improve the accuracy of our numerical derivative?", "# Plot sin and cos\npl.plot(x, np.sin(x), color='k')\npl.plot(x, np.cos(x), color='b')\n\n# Compute derivative using central difference formula\nxder, yder = derivative2(centralDifference, np.sin, 0, tau, 100) \n\n# Plot numerical derivative as scatter plot\npl.scatter(xder, yder, color='g', s=100, marker='*', lw=2) ", "Example: Traversing A 1-D landscape\nGaussian Equation: \n$$f(x)=A * e^{-\\frac{(x-\\mu)^2}{2*\\sigma}}$$", "numCraters = 5 # number of craters\nwidthMax = 1.0 # maximal width of Gaussian crater\nheightMin = -1.0 # maximal depth of craters / valleys\nheightMax = 2.0 # maximal height of hills / mountains\n\n# 1-D Gaussian\ndef gaussian(x, A, mu, sigma):\n return A * np.exp(-(x - mu)**2 / 2.0 / sigma**2)\n\n# 1-D Gaussian (same thing using lambda)\n#gaussian = lambda x, A, mu, sigma: A * np.exp(-(x - mu)**2 / 2. / sigma**2) \n\n# Create an array of linearly spaced x values\nxArray = np.linspace(0, 10, 500) # km\n\n# Create an array of initially flat landscape (aka filled with 0's)\nyArray = np.zeros_like(xArray)\n\n# Add craters / mountains to landscape\nfor _ in range(numCraters): # '_' is the so called dummy variable\n \n # Amplitude between heightMin and heightMax\n A = np.random.rand() * (heightMax - heightMin) + heightMin\n \n # Center location of the crater\n center = np.random.rand() * xArray.max()\n \n # Width of the crater\n sigma = np.random.rand() * widthMax\n \n # Add crater to landscape!\n yArray += gaussian(xArray, A=A, mu=center, sigma=sigma)\n\npl.plot(xArray, yArray, color='k')\npl.xlabel('position [km]')\npl.ylabel('altitutde [km]')", "Q. Where should our spacecraft land? What areas seem accessible?\nQ. How do we find the lowest point? Highest? How could we determine how many \"mountains\" and \"craters\" there are?", "dydx = np.diff(yArray) / np.diff(xArray)", "Q. What do you think \"diff\" does?", "arr = np.array([1,4,10, 12,5, 7])\n\nnp.diff(arr)", "Q. What type of differentiation scheme does this formula represent? How is this different than our \"derivative\" function from earlier?", "pl.plot(xArray[0:-1], dydx, color='r', label='slope')\npl.plot(xArray, yArray, color='k', label='data')\n\npl.xlabel('position [km]')\npl.ylabel('slope')\npl.plot([xArray.min(), xArray.max()], [0,0], color='k', ls=':')\n#pl.ylim(-4, 4)\npl.legend(loc='best')", "Q. How many hills and craters are there?\nQ. Why did we use x[0:-1] in the above plot instead of x?", "slopeTolerance = 0.5", "Q. Using the slope, how could we determine which places we could reach and which we couldn't?", "myArray = np.array([0, 1, 2, 3, 4]) # Create an array\n\ntfArray = np.logical_and(myArray < 2, myArray != 0) # Use boolean logic on array\n\nprint (myArray) # Print original array\nprint (tfArray) # Print the True/False array (from boolean logic)\nprint (myArray[tfArray]) # Print the original array using True/False array to limit values\n\nreachable = np.logical_and(dydx < slopeTolerance, dydx > -slopeTolerance)\nunreachable = np.logical_not(reachable)\n\npl.plot(xArray, yArray, color='k')\npl.scatter(xArray[:-1][unreachable], yArray[:-1][unreachable], color='r', label='bad')\npl.scatter(xArray[:-1][reachable], yArray[:-1][reachable], color='g', label='good')\n\npl.legend(loc='best')\npl.xlabel('position [km]')\npl.ylabel('altitude [km]')", "Summary" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
khrapovs/metrix
notebooks/ci_for_proportion.ipynb
mit
[ "Confidence intervals for proportion estimator\nWe are interested in estimating the proportion of the population whose incomes are below the poverty line. Let $Y$ be the income, $c$ - the poverty line, so the parameter of interest is $\\theta=P\\left[Y\\leq c\\right]$. Suppose we have collected $n$ independent observations $\\left{ Y_{i}\\right}_{i=1}^{n}$.\nThe Analogy Principle estimator is the fraction of individuals below the poverty line in sample: $\\hat{\\theta}{n}=\\frac{1}{n}\\sum{i=1}^{n}\\mathbf{1}\\left(Y_{i}\\leq c\\right)$.\nIt can be shown that the confidence interval for the estimator is\n$$\nP\\left[\\frac{\\hat{\\theta}{n}}{n}-\\frac{1.96}{\\sqrt{n}}\\sqrt{\\hat{\\theta}{n}\\left(n-\\hat{\\theta}{n}\\right)}<\\theta<\\frac{\\hat{\\theta}{n}}{n}+\\frac{1.96}{\\sqrt{n}}\\sqrt{\\hat{\\theta}{n}\\left(n-\\hat{\\theta}{n}\\right)}\\right]\\approx0.95.\n$$\nAlternatively, using variance stabilization method, we can derive another confidence interval,\n$$\nP\\left[f\\left(\\sin^{-1}\\left(\\sqrt{\\hat{\\theta}{n}}\\right)-\\frac{0.98}{\\sqrt{n}}\\right)<\\theta<f\\left(\\sin^{-1}\\left(\\sqrt{\\hat{\\theta}{n}}\\right)+\\frac{0.98}{\\sqrt{n}}\\right)\\right]\\approx0.95.\n$$\nwith\n$$\nf\\left(x\\right)=\\begin{cases}\n0, & x\\leq0,\\\n\\sin^{2}\\left(x\\right), & 0<x\\leq\\pi/2,\\\\\n1, & x>\\pi/2.\n\\end{cases}\n$$\nEvaluate the two confidence intervals above numerically for all combinations of $n\\in\\left{ 10,100,1000\\right}$ and $\\theta\\in\\left{ .1,.3,.5\\right}$ as follows. For 1000 realizations of $n\\hat{\\theta}_{n}\\sim\\text{Bin}\\left(n,\\theta\\right)$, construct both 95% confidence intervals and keep track of how many times (out of 1000) that the confidence intervals does not contain $\\theta$. Report the observed proportion of rejections for each $\\left(n,\\theta\\right)$ combination. Does your study reveal any differences in the performance of these two competing methods?\nSet up the environment", "import numpy as np\nimport itertools\nimport pandas as pd\n# In Python 2.7 the division of integers is not float. Do this to have 1 / 2 = .5\nfrom __future__ import division", "Define parameters of the simulation", "# Number of simulations\nS = 1000\n# Number of observations in each sample\nN = [10, 100, 1000]\n# True parameter values\ntheta = [.1, .3, .5]", "Define the function that returns rejection probabilities", "def rejections(n, p, s):\n \"\"\"Compute rejection probabilties.\n \n Parameters\n ----------\n n : int\n Number of draws\n p : float\n Success probability\n s : int\n Number of simulations\n \n Returns\n -------\n r1, r2 : float\n Rejection probabilities for two CI\n \n \"\"\"\n # Generate the data\n X = np.random.binomial(n, p, s)\n # Compute the estimator of success probability\n theta_hat = X / n\n # Compute two statistics in CI\n W1 = np.abs(n**.5 * (theta_hat - p) / (theta_hat * (1 - theta_hat))**.5)\n W2 = np.abs(2 * n**.5 * (np.arcsin(theta_hat**.5) - np.arcsin(p**.5)))\n # Compute the fraction of rejections\n r1 = np.mean(W1 > 1.96)\n r2 = np.mean(W2 > 1.96)\n return r1, r2", "Run simulation study", "# Initialyze containers for the labels and data\nindex, df = [], []\n\n# To avoid multiple loops, use cartesian product of all options to check\nfor (n, p) in itertools.product(N, theta):\n r = rejections(n, p, S)\n # Append results to labels and data\n df.append(r)\n index.append([n, p])\n\n# Construct multi-level index\nindex = pd.MultiIndex.from_tuples(index, names=['n', 'p'])\n# Construct pandas DataFrame for nice output\ntable = pd.DataFrame(df, columns=['r1', 'r2'], index=index)\n\nprint(table.unstack('p'))" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
beardeer/prediction-wrapper
run_example.ipynb
mit
[ "0. Introduction\nThe following notebook is going to demonstrate the usage of prediction-wrapper, a set of utility classes that makes it much easier to run sklearn machine learning experiments. \nThis demo shows the procedure of setting up a classification wrapper to run 5-fold cross-validations on 3 different classification models with 3 performance metrics by only using a few lines of code.", "import pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\n\nfrom binary_classifier_wrappers import KfoldBinaryClassifierWrapper\nfrom metric_wrappers import RSquare, AUC, RMSE", "1. Load and perpare data\nLoad Titanic data from local. Downloaded from https://www.kaggle.com/c/titanic/data.\nSince this is only a demo, I only used training data.", "titanic = pd.read_csv(\"./data/train.csv\")", "Display some meta info from the data file.", "titanic.info()", "We see that 'Age' feature has some missing data, so fill them with the current median.", "titanic[\"Age\"].fillna(titanic[\"Age\"].median(), inplace=True)", "Drop useless featurs from data frame.", "titanic = titanic.drop(['PassengerId','Name','Ticket', 'Cabin', 'Embarked'], axis=1)", "2. Set up model inputs\nBuild a list of feature names from data frame. Note that we need to drop the 'Survived' column from input features.", "all_feature_names = titanic.columns.tolist()\nall_feature_names.remove('Survived')\nall_feature_names", "Build a list of categorical feature names.", "categorical_feature_names = ['Pclass', 'Sex']", "And set the name of label in the data frame.", "label_name = 'Survived'", "Initialize 3 classification models.", "lr_model = LogisticRegression()\nsvn_model = SVC(probability = True)\nrf_model = RandomForestClassifier()\n\nmodel_dict = {'Logistic Regression': lr_model,\n 'SVM': svn_model,\n 'Random Forest': rf_model}", "3. Run a classification wrapper with multiple models and multiple metrics\nInitialize the classification wrapper with 5-fold cross-validation, this is where magic happens.", "k_fold_binary = KfoldBinaryClassifierWrapper(titanic, label_name, \\\n all_feature_names, categorical_feature_names, k=5)", "Build a table to store results.", "model_performance_table = pd.DataFrame(index=range(len(model_dict)), \\\n columns=['Model', 'AUC', 'r^2', 'RMSE'])", "Run the classification wrapper with 3 models, and compute their results with 3 performance metrics.", "for n, name in enumerate(model_dict.keys()):\n k_fold_binary.set_model(model_dict[name])\n pred_result = k_fold_binary.run()\n \n model_performance_table.ix[n,'Model'] = name\n model_performance_table.ix[n,'AUC'] = AUC.measure(pred_result.label, pred_result.pred_prob)\n model_performance_table.ix[n,'r^2'] = RSquare.measure(pred_result.label, pred_result.pred_prob)\n model_performance_table.ix[n,'RMSE'] = RMSE.measure(pred_result.label, pred_result.pred_prob)", "Display results.", "model_performance_table = model_performance_table.sort_values(by='AUC', ascending=False).reset_index(drop=True)\nmodel_performance_table" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
aje/POT
docs/source/auto_examples/plot_otda_classes.ipynb
mit
[ "%matplotlib inline", "OT for domain adaptation\nThis example introduces a domain adaptation in a 2D setting and the 4 OTDA\napproaches currently supported in POT.", "# Authors: Remi Flamary <remi.flamary@unice.fr>\n# Stanislas Chambon <stan.chambon@gmail.com>\n#\n# License: MIT License\n\nimport matplotlib.pylab as pl\nimport ot", "Generate data", "n_source_samples = 150\nn_target_samples = 150\n\nXs, ys = ot.datasets.get_data_classif('3gauss', n_source_samples)\nXt, yt = ot.datasets.get_data_classif('3gauss2', n_target_samples)", "Instantiate the different transport algorithms and fit them", "# EMD Transport\not_emd = ot.da.EMDTransport()\not_emd.fit(Xs=Xs, Xt=Xt)\n\n# Sinkhorn Transport\not_sinkhorn = ot.da.SinkhornTransport(reg_e=1e-1)\not_sinkhorn.fit(Xs=Xs, Xt=Xt)\n\n# Sinkhorn Transport with Group lasso regularization\not_lpl1 = ot.da.SinkhornLpl1Transport(reg_e=1e-1, reg_cl=1e0)\not_lpl1.fit(Xs=Xs, ys=ys, Xt=Xt)\n\n# Sinkhorn Transport with Group lasso regularization l1l2\not_l1l2 = ot.da.SinkhornL1l2Transport(reg_e=1e-1, reg_cl=2e0, max_iter=20,\n verbose=True)\not_l1l2.fit(Xs=Xs, ys=ys, Xt=Xt)\n\n# transport source samples onto target samples\ntransp_Xs_emd = ot_emd.transform(Xs=Xs)\ntransp_Xs_sinkhorn = ot_sinkhorn.transform(Xs=Xs)\ntransp_Xs_lpl1 = ot_lpl1.transform(Xs=Xs)\ntransp_Xs_l1l2 = ot_l1l2.transform(Xs=Xs)", "Fig 1 : plots source and target samples", "pl.figure(1, figsize=(10, 5))\npl.subplot(1, 2, 1)\npl.scatter(Xs[:, 0], Xs[:, 1], c=ys, marker='+', label='Source samples')\npl.xticks([])\npl.yticks([])\npl.legend(loc=0)\npl.title('Source samples')\n\npl.subplot(1, 2, 2)\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o', label='Target samples')\npl.xticks([])\npl.yticks([])\npl.legend(loc=0)\npl.title('Target samples')\npl.tight_layout()", "Fig 2 : plot optimal couplings and transported samples", "param_img = {'interpolation': 'nearest', 'cmap': 'spectral'}\n\npl.figure(2, figsize=(15, 8))\npl.subplot(2, 4, 1)\npl.imshow(ot_emd.coupling_, **param_img)\npl.xticks([])\npl.yticks([])\npl.title('Optimal coupling\\nEMDTransport')\n\npl.subplot(2, 4, 2)\npl.imshow(ot_sinkhorn.coupling_, **param_img)\npl.xticks([])\npl.yticks([])\npl.title('Optimal coupling\\nSinkhornTransport')\n\npl.subplot(2, 4, 3)\npl.imshow(ot_lpl1.coupling_, **param_img)\npl.xticks([])\npl.yticks([])\npl.title('Optimal coupling\\nSinkhornLpl1Transport')\n\npl.subplot(2, 4, 4)\npl.imshow(ot_l1l2.coupling_, **param_img)\npl.xticks([])\npl.yticks([])\npl.title('Optimal coupling\\nSinkhornL1l2Transport')\n\npl.subplot(2, 4, 5)\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o',\n label='Target samples', alpha=0.3)\npl.scatter(transp_Xs_emd[:, 0], transp_Xs_emd[:, 1], c=ys,\n marker='+', label='Transp samples', s=30)\npl.xticks([])\npl.yticks([])\npl.title('Transported samples\\nEmdTransport')\npl.legend(loc=\"lower left\")\n\npl.subplot(2, 4, 6)\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o',\n label='Target samples', alpha=0.3)\npl.scatter(transp_Xs_sinkhorn[:, 0], transp_Xs_sinkhorn[:, 1], c=ys,\n marker='+', label='Transp samples', s=30)\npl.xticks([])\npl.yticks([])\npl.title('Transported samples\\nSinkhornTransport')\n\npl.subplot(2, 4, 7)\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o',\n label='Target samples', alpha=0.3)\npl.scatter(transp_Xs_lpl1[:, 0], transp_Xs_lpl1[:, 1], c=ys,\n marker='+', label='Transp samples', s=30)\npl.xticks([])\npl.yticks([])\npl.title('Transported samples\\nSinkhornLpl1Transport')\n\npl.subplot(2, 4, 8)\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o',\n label='Target samples', alpha=0.3)\npl.scatter(transp_Xs_l1l2[:, 0], transp_Xs_l1l2[:, 1], c=ys,\n marker='+', label='Transp samples', s=30)\npl.xticks([])\npl.yticks([])\npl.title('Transported samples\\nSinkhornL1l2Transport')\npl.tight_layout()\n\npl.show()" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
openfisca/openfisca-france-indirect-taxation
openfisca_france_indirect_taxation/examples/notebooks/montants_accises_ticpe.ipynb
agpl-3.0
[ "L'objectif est de décrire l'évolution des montants des accises de la TICPE depuis 1993\nImport de modules généraux", "import seaborn\n\nseaborn.set_palette(seaborn.color_palette(\"Set2\", 12))\n\n%matplotlib inline", "Import de fonctions spécifiques à Openfisca Indirect Taxation", "\n\nfrom openfisca_france_indirect_taxation.examples.utils_example import graph_builder_bar_list\nfrom openfisca_france_indirect_taxation.examples.dataframes_from_legislation.get_accises import \\\n get_accise_ticpe_majoree\n", "Recherche des paramètres de la législation", "liste = ['ticpe_gazole', 'ticpe_super9598', 'super_plombe_ticpe']\ndf_accises = get_accise_ticpe_majoree()\n", "Réalisation des graphiques", "graph_builder_bar_list(df_accises['accise majoree sans plomb'], 1, 1)\ngraph_builder_bar_list(df_accises['accise majoree diesel'], 1, 1)\ngraph_builder_bar_list(df_accises['accise majoree super plombe'], 1, 1)\n" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
PmagPy/2017_MagIC_Workshop_PmagPy_Tutorial
Example_PmagPy_Notebook.ipynb
bsd-3-clause
[ "Jupyter notebook illustrating the use of PmagPy for analysis of paleomagnetic data\nBefore you begin\nYou may be viewing this notebook as a rendered html webpage (which can be seen at this link: http://pmagpy.github.io/Example_PmagPy_Notebook.html) or PDF in which case you can go ahead and simply have a look at it. However, if you wish to execute the code within a downloaded version of this notebook (which can be found here: https://github.com/PmagPy/2016_Tauxe-et-al_PmagPy_Notebooks), it is necessary to have an installed distribution of Python and to have installed the PmagPy software distribution. The instructions in the PmagPy Cookbook can help get you started in this regard:\nhttp://earthref.org/PmagPy/cookbook\nThe user may also benefit from perusing the 'Survival computer skills' and 'Introduction to Python Programming' chapters of the cookbook if they are new to programming in Python.\nIntroduction\nThis notebook was created by Nicholas Swanson-Hysell, Lisa Tauxe and Luke Fairchild. It accompanies a paper entitled: \nPmagPy: Software package for paleomagnetic data analysis and a bridge to the Magnetics Information Consortium (MagIC) Database\nL. Tauxe, R. Shaar, L. Jonestrask, N.L. Swanson-Hysell, R. Minnett, A.A.P., Koppers, C.G. Constable, N. Jarboe, K. Gaastra, and L. Fairchild\nThe analysis in this notebook uses data from two contributions within the MagIC database:\nHalls, H. (1974), A paleomagnetic reversal in the Osler Volcanic Group, \nnorthern Lake Superior, Can. J. Earth Sci., 11, 1200–1207, \ndoi:10.1139/e74-113. Link to MagIC contribution:\n http://earthref.org/MAGIC/doi/10.1139/e74-113\nand\nSwanson-Hysell, N. L., A. A. Vaughan, M. R. Mustain, and K. E. Asp (2014), Confirmation of progressive plate motion during the Midcontinent Rift’s early magmatic stage from the Osler Volcanic Group, Ontario, Canada, Geochem. Geophys. Geosyst., 15, 2039–2047, doi:10.1002/2013GC005180. Link to MagIC contribution:\nhttp://earthref.org/MAGIC/doi/10.1002/2013GC005180\nTo explore the use of Jupyter notebooks, follow each of these links and click on the text file icon in the Data column. Move each of the files from your download directory into a 'Project Directory' on your hard drive. In the example below, the project directory for the Halls data set is Halls1974 and for the Swanson-Hysell data set, Swanson-Hysell2014 within a subdirectory with the notebook code in it. If you cloned the notebook repository or downloaded a zip copy of it, you will already have these data files. Fire up a command line prompt (cmd on PCs and `terminal' in the Applications/Utilities folder on a Mac) and type jupyter notebook or ipython notebook to launch a notebook environment within your default web browser. \nIn this notebook, we will use PmagPy to:\n\nUnpack data downloaded from the MagIC database.\nPlot directions and VGPs.\nCalculate and plot Fisher means for directions and VGPs.\nConduct a bootstrap fold test on the data.\nConduct a common mean test between the data from the two contributions.\n\nImport necessary function libraries for data analysis\nThe code block below imports the pmagpy module from PmagPy that provides functions that will be used in the data analysis. At present, the most straight-forward way to do so is to install the pmagpy module using the pip package manager by executing this command at the command line:\npip install pmagpy\nApproachs not using pip can also work. One way would be to download the pmagpy folder from the main PmagPy repository and either put it in the same directory as the notebook or put it anywhere on your local machine and add a statement such as export PYTHONPATH=$PYTHONPATH:~/PmagPy in your .profile or .bash_profile file that points to where PmagPy is on your local machine (in this example in the home directory). \nWith PmagPy available in this way, the function modules from PmagPy can be imported: pmag, a module with ~160 (and growing) functions for analyzing paleomagnetic and rock magnetic data and ipmag, a module with functions that combine and extend pmag functions and exposes pmagplotlib functions in order to generate output that works well within the Jupyter notebook environment. \nTo execute the code, click on play button in the menu bar, choose run under the 'cell' menu at the top of the notebook, or type shift+enter.", "import pmagpy.ipmag as ipmag\nimport pmagpy.pmag as pmag", "There are three other important Python libraries (which are bundled with the Canopy and Anaconda installations of Python) that come in quite handy and are used within this notebook: numpy for data analysis using arrays, pandas for data manipulation within dataframes and matplotlib for plotting. The call %matplotlib inline results in the plots being shown within this notebook rather than coming up in external windows.", "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\n%config InlineBackend.figure_formats = {'svg',}", "Background on the Osler Volcanic Group\nThe data being analyzed in this notebook come from lava flows of the Osler Volcanic Group which is a sequence of Midcontinent Rift lava flows exposed on Black Bay Peninsula and the Lake Superior Archipelago in northern Lake Superior. Halls (1974; doi:10.1139/e74-113) conducted the first paleomagnetic study of these flows and determined that they were of dominantly reversed polarity with a paleomagnetic reversal very near to the top of the exposed stratigraphy. This reversal is associated with the deposition of a conglomerate unit and an angular unconformity. The data presented in Halls (1974) from the reversed polarity lavas were from flows high in the succession in close stratigraphic proximity to a sequence of felsic flows at Agate Point---one of which was dated by Davis and Green (1997; doi:10.1139/e17-039) with a resulting $^{207}$Pb/$^{206}$Pb date on zircon of 1105.3 ± 2.1 Ma. Swanson-Hysell et al. (2014; doi:10.1002/2013GC005180) conducted a paleomagnetic study that spanned more of the Osler Group flows from their base up to the upper portions of the exposed reversed polarity flows. The analysis of these data determined that there was a significant change in direction between the data from flows in the lower third of the reversed polarity stratigraphy and those in the upper third stratigraphy. This change was interpreted to be caused by a progression along the apparent polar wander path associated with equatorward motion of Laurentia.\nImport data into the notebook\nUnpack files downloaded from the MagIC database\nData within the MagIC database can be downloaded as a single .txt file. This file can be split into its constituent EarthRef and pmag tables either within the Pmag GUI, using a command line PmagPy program or using the function ipmag.download_magic within the notebook as is done here. The code block below uses this function by giving the file name, specifying where it is and telling it where to unpack the data set into the magic tables. Once these tables are unpacked, we can use them for subsequent data analysis. The %%capture line blocks annoying messages printed by the ipmag.download_magic function.", "%%capture\nipmag.download_magic('magic_contribution_11087.txt',\n dir_path='./Data/Halls1974',\n input_dir_path='./Data/Halls1974',\n overwrite=True,print_progress=False)\nipmag.download_magic('magic_contribution_11088.txt',\n dir_path='./Data/Swanson-Hysell2014',\n input_dir_path='./Data/Swanson-Hysell2014',\n overwrite=True,print_progress=False)", "Loading the unpacked data into Pandas Dataframes\nWith the results unpacked from MagIC, the data can now be analyzed within the notebook. The data from the Halls1974/pmag_sites.txt table can be imported in order to look at the directions from each site. A nice way to deal with data within Python is using the dataframe structure of the pandas package. The code block below uses the pd.read_csv function to create a dataframe from the pmag_sites.txt file. All MagIC formatted files are tab delimited (sep='\\t') with two header lines, one with the type of delimiter and MagIC table and one with the MagIC database column names. To see the formats for MagIC tables, go to http://earthref.org/MAGIC/metadata.htm.\nTo skip the first header line in a particular file when importing it to a DataFrame, set skiprows=1. The data_frame_name.head(X) function allows us to inspect the first X rows of the dataframe (in this case 4).", "Halls1974_sites = pd.read_csv('./Data/Halls1974/pmag_sites.txt',\n sep='\\t',skiprows=1)\nHalls1974_sites.head(4)", "Filtering by polarity and tilt-correction\nLet's start our analysis on the reversed polarity sites that are below an angular unconformity in the Halls (1974) data set. A nice thing about dataframes is that there is built-in functionality to filter them based on column values. The code block below creates a new dataframe of sites that have the site_polarity value of 'r' in the pmag_sites table. It then creates one dataframe for tilt-corrected sites (value of 100 in site_tilt_correction) and sites that have not been tilt-corrected (value of 0 in site_tilt_correction).", "Halls1974_sites_r = Halls1974_sites.ix[Halls1974_sites.site_polarity=='r']\nHalls1974_sites_r_tc = Halls1974_sites_r.ix[Halls1974_sites_r.site_tilt_correction==100]\nHalls1974_sites_r_tc.reset_index(inplace=True)\nHalls1974_sites_r_is = Halls1974_sites_r.ix[Halls1974_sites_r.site_tilt_correction==0]\nHalls1974_sites_r_is.reset_index(inplace=True)", "Data analysis and visualization\nThe data can be analyzed and visualized using PmagPy functions. We will first create a directory called 'Example_Notebook_Output' from within the notebook (using the initial ! before the command invokes a command as if typed on the command line from within a notebook) so that we have a place to put saved figures. You can do this outside of the notebook if you prefer.", "!mkdir 'Output_files'", "Calculating Fisher means\nFisher means for the data can be calculated with the function ipmag.fisher_mean. This function takes in a list of declination values, a list of inclination values and returns a dictionary that gives the Fisher mean and associated statistical parameters. This dictionary is printed out for the mean of the tilt-corrected data within the first code block. These dictionary objects are given names such that we can subsequently access the values. The second code block uses the ipmag.print_direction_mean to print out a formatted version of these same results.", "Halls1974_r_is_mean = ipmag.fisher_mean(Halls1974_sites_r_is.site_dec.tolist(),\n Halls1974_sites_r_is.site_inc.tolist())\nHalls1974_r_tc_mean = ipmag.fisher_mean(Halls1974_sites_r_tc.site_dec.tolist(),\n Halls1974_sites_r_tc.site_inc.tolist())\nprint Halls1974_r_tc_mean\n\nprint 'The mean for the tilt-corrected Halls (1974) Osler directions is:'\nipmag.print_direction_mean(Halls1974_r_tc_mean)", "Plotting the Halls (1974) results\nThe code block below creates a figure with an equal area stereonet and uses the ipmag.plot_di function to plot the data both in tilt-corrected and in situ coordinates. The figure can be saved out of the notebook using the plt.savefig() function. The saved figure file type can be .png, .eps, .svg among others. Saved figures can be used as is for publication or, if necessary, exported vector graphics (e.g. .eps and .svg files) can be edited with software such as Adobe Illustrator or Inkscape.", "plt.figure(num=1,figsize=(4,4))\nipmag.plot_net(fignum=1)\nipmag.plot_di(Halls1974_sites_r_is.site_dec.tolist(),\n Halls1974_sites_r_is.site_inc.tolist(),color='r',\n label='Halls (1974) site means (in situ)')\nipmag.plot_di(Halls1974_sites_r_tc.site_dec.tolist(),\n Halls1974_sites_r_tc.site_inc.tolist(),color='b',\n label='Halls (1974) site means (tilt-corrected)')\nplt.legend(loc=9)\nplt.savefig('Output_files/Halls_1974_sites.svg')", "A similar plot showing the Fisher means of the site means calculated above and their associated $\\alpha_{95}$ confidence ellipses can be generated using the ipmag.plot_di_mean function.", "plt.figure(num=1,figsize=(4,4))\nipmag.plot_net(fignum=1)\nipmag.plot_di_mean(Halls1974_r_tc_mean['dec'],\n Halls1974_r_tc_mean['inc'],\n Halls1974_r_tc_mean['alpha95'],'b',\n label='Halls (1974) tilt-corrected mean')\nipmag.plot_di_mean(Halls1974_r_is_mean['dec'],\n Halls1974_r_is_mean['inc'],\n Halls1974_r_is_mean['alpha95'],'r',\n label='Halls (1974) insitu mean')\nplt.legend(loc=9)\nplt.show()", "The means that have been calculated are now dictionaries that can be made into a new dataframe to present the results. A table like this can be exported into a variety of formats (e.g. LaTeX, html, csv) for inclusion in a publication.", "Halls1974_r_is_mean = ipmag.fisher_mean(Halls1974_sites_r_is.site_dec.tolist(),\n Halls1974_sites_r_is.site_inc.tolist())\nHalls1974_r_tc_mean = ipmag.fisher_mean(Halls1974_sites_r_tc.site_dec.tolist(),\n Halls1974_sites_r_tc.site_inc.tolist())\nmeans = pd.DataFrame([Halls1974_r_is_mean,Halls1974_r_tc_mean],\n index=['Halls 1974 Osler R (insitu)','Halls 1974 Osler R (tilt-corrected)'])\nmeans", "Alternatively, one can export the MagIC data table pmag_results.txt into a tab delimited or latex file using the PmagPy program: pmag_results_extract.py which can be run at the command line as:\npmag_results_extract.py -f Halls1974/pmag_results.txt\npmag_results_extract.py -f Halls1974/pmag_results.txt -tex\nor executed as shell command within the notebook by using the ! prefix as is done in the cell block below.", "!pmag_results_extract.py -f Data/Halls1974/pmag_results.txt", "Combining and plotting the Halls (1974) and Swanson-Hysell et al. (2014) data\nFirst, let's read in the data from the pmag_results.txt table from the Swanson-Hysell et al., (2014) study into a Pandas dataframe.", "SH2014_sites = pd.read_csv('./Data/Swanson-Hysell2014/pmag_results.txt',\n sep='\\t',skiprows=1)\nSH2014_sites.head(1)", "Swanson-Hysell et al. (2014) argued that data from the upper third of the Simpson Island stratigraphy should be compared with the reverse data from the Halls (1974) Nipigon Strait region study. The dataframe can be filtered using the average_height value from the pmag_results table.", "SH2014_OslerR_upper = SH2014_sites.ix[SH2014_sites.average_height>2082]\nSH2014_OslerR_upper.reset_index(inplace=True)\nSH2014_OslerR_upper.head()", "Let's fish out the declinations and inclinations in geographic (in situ) coordinates (is) and those in tilt-corrected coordinates (tc) from the pmag_results table from the Swanson-Hysell2014 dataset and convert them from a dataframe object to a python list object. We can see what happened with a print command.", "SH2014_upperR_dec_is = SH2014_OslerR_upper['tilt_dec_uncorr'].tolist()\nSH2014_upperR_inc_is = SH2014_OslerR_upper['tilt_inc_uncorr'].tolist()\nSH2014_upperR_dec_tc = SH2014_OslerR_upper['tilt_dec_corr'].tolist()\nSH2014_upperR_inc_tc = SH2014_OslerR_upper['tilt_inc_corr'].tolist()\nprint SH2014_upperR_inc_tc", "And now the same for the Halls1974 data table.", "Halls1974_upperR_dec_is = Halls1974_sites_r_is['site_dec'].tolist()\nHalls1974_upperR_inc_is = Halls1974_sites_r_is['site_inc'].tolist()\nHalls1974_upperR_dec_tc = Halls1974_sites_r_tc['site_dec'].tolist()\nHalls1974_upperR_inc_tc = Halls1974_sites_r_tc['site_inc'].tolist()", "We can combine the data from the two papers using the numpy (np) concatenate function:", "combined_upperR_dec_is = np.concatenate((SH2014_upperR_dec_is,\n Halls1974_upperR_dec_is), axis=0)\ncombined_upperR_inc_is = np.concatenate((SH2014_upperR_inc_is,\n Halls1974_upperR_inc_is), axis=0)\n\ncombined_upperR_dec_tc = np.concatenate((SH2014_upperR_dec_tc,\n Halls1974_upperR_dec_tc), axis=0)\ncombined_upperR_inc_tc = np.concatenate((SH2014_upperR_inc_tc,\n Halls1974_upperR_inc_tc), axis=0)", "Now we can plot the data!", "plt.figure(num=1,figsize=(4,4))\nipmag.plot_net(fignum=1)\nipmag.plot_di(combined_upperR_dec_is,\n combined_upperR_inc_is,color='r', label='insitu directions')\nipmag.plot_di(combined_upperR_dec_tc,\n combined_upperR_inc_tc,color='b', label='tilt-corrected directions')\nplt.legend()\nplt.show()", "The combined means can be calculated with the ipmag.fisher_mean function and printed out with some formatting with the ipmag.print_direction_mean function.", "OslerUpper_is_mean = ipmag.fisher_mean(combined_upperR_dec_is,\n combined_upperR_inc_is)\nprint \"The Fisher mean of the insitu upper Osler R directions:\"\nipmag.print_direction_mean(OslerUpper_is_mean)\nprint ''\nOslerUpper_tc_mean = ipmag.fisher_mean(combined_upperR_dec_tc,\n combined_upperR_inc_tc)\nprint \"The Fisher mean of the tilt-corrected upper Osler R directions:\"\nipmag.print_direction_mean(OslerUpper_tc_mean)\nprint ''\nprint 'The k_2/k_1 ratio is:'\nprint OslerUpper_tc_mean['k']/OslerUpper_is_mean['k']", "Fold test on the site mean directions\nIn the above plot, the blue directions that have been corrected for tilting have a higher precision than the red values that are uncorrected for tilting. The ratio of the precision parameter from before and after tilt-correction ($k_2$/$k_1$) is 2.2 (see output of code above). Calculating this ratio provides a way to qualitatively assess whether there is improvement in the precision of the data such that the magnetization was likely acquired prior to tilting. This ratio was at the heart of the McElhinny (1964; doi:10.1111/j.1365-246X.1964.tb06300.x) fold test (in which this would constitute of a positive test). However, that test has been shown to not be meaningful as summarized by McFadden (1990; doi:10.1111/j.1365-246X.1990.tb01761.x). \nHalls (1974) noted that the precision increases with structural correction in the Osler dataset, but did not report the values of a statistical fold test. Swanson-Hysell et al. (2014) included all of these data, but did not report the results of the fold test. Here we conduct a Tauxe and Watson (1994; doi:10.1016/0012-821X(94)90006-X) bootstrap fold test on these data that reveals that the tightest grouping of vectors is achieved upon correction for bedding tilt thereby constituting a positive fold test.\nBefore we can do that, we must wrangle the data into the format expected by the fold test program. We can start with the in situ directions from the pmag_results.txt files and pair them with the bedding orientations in the er_sites.txt files for each of the studies. \nThe in situ (geographic coordinates) for the reverse sites from Halls (1974) were read in from the pmag_sites table into Halls1974_sites_r_is. We read the data from the Swanson-Hysell 2014 data from pmag_results table, so the column headers are different. Both of these data sets must be paired with the bedding information in the er_sites tables for each study and put into the format expected by the function ipmag.bootstrap_fold_test which expects an array of declination, inclination, dip direction and dip for all the sites where the directional data are in geographic coordinates. \nThe first step is to make a container for the directions and orientations. In this case, we make an empty list OslerR_upper_diddd.", "OslerR_upper_diddd=[]", "Let's start with the Halls (1974) data set in Halls1974_sites_r_is. It is handier for the MagIC data tables in this exercise to have a list of dictionaries instead of a Pandas data frame. So let's convert the Halls 1974 filtered dataframe to a list of dictionaries called Halls1974.", "Halls1974=Halls1974_sites_r_is.T.to_dict().values()", "Now we can read in the data from the er_sites.txt table (with the bedding attitudes) using the function pmag.magic_read which reads in magic tables into a list of dictionaries. Then we will step through the records and pair each site with its bedding orientations using a handy function get_dict_item from the pmag module that will find correct site record. The function expects a list of dictionaries (Halls1974_sites), a key to filter on ('er_site_name'), the value of the key (pmag.magic_read reads things in as strings but because the names are numbers, pandas converted them to integers, hence the str(site['er_site_name']), and whether the two must be equal ('T'), not equal ('F'), contain ('has') or not contain ('not'). After finding the correct orientation record for the site, we can put the directions and bedding orientations together into the list OslerR_upper_diddd.", "Halls1974_sites,filetype=pmag.magic_read('./Data/Halls1974/er_sites.txt') # reads in the data\nfor site in Halls1974:\n orientations=pmag.get_dictitem(Halls1974_sites,'er_site_name',\n str(site['er_site_name']),'T')\n if len(orientations)>0: # record found\n OslerR_upper_diddd.append([site['site_dec'],site['site_inc'], \n float(orientations[0]['site_bed_dip_direction']),\n float(orientations[0]['site_bed_dip'])])\n else:\n print 'no orientations found for site, ',site['er_site_name']", "We can do the same for the filtered upper Osler sequence of Swanson-Hysell et al. (2014). These have slightly different keys, but the general idea is the same. In the cell below, we convert the dataframe to a list of dictionaries, fish out the bedding orientations and attach them to the same list as before (OslerR_upper_diddd).", "SH2014=SH2014_OslerR_upper.T.to_dict().values()\nSH2014_sites,filetype=pmag.magic_read('./Data/Swanson-Hysell2014/er_sites.txt')\nfor site in SH2014:\n orientations=pmag.get_dictitem(SH2014_sites,'er_site_name', \n str(site['er_site_names']),'T')\n if len(orientations)>0: # record found\n OslerR_upper_diddd.append([site['tilt_dec_uncorr'],site['tilt_inc_uncorr'], \n float(orientations[0]['site_bed_dip_direction']),\n float(orientations[0]['site_bed_dip'])])\n else:\n print 'no orientations found for site, ',site['er_site_names']", "Now all we have to do is make a numpy array out of the OslerR_upper_diddd and send it to the ipmag.bootstrap_fold_test function.", "diddd=np.array(OslerR_upper_diddd)\nipmag.bootstrap_fold_test(diddd,num_sims=100, min_untilt=0, max_untilt=140)", "Developing a mean paleomagnetic pole\nThe virtual geomagnetic poles (VGPs) calculated from the Halls (1974) and Swanson-Hysell (2014) site means can be combined into a single paleomagnetic pole for the upper portion of the reversed polarity Osler Volcanic Group flows. Developing such a combined pole makes sense from a stratigraphic perspective given that the data come from a similar portion of the Osler Volcanic Group stratigraphy. We can test whether or not this combination makes sense from the data themselves by posing the question: are the data sets consistent with being drawn from a common mean? \nFirst, the VGP longitudes and latitudes for the Halls (1974) data can be accessed from the pmag_results table. The results need to be filtered so that individual VGPs are being used (rather than mean poles) and that the reversed poles are being used (rather than the normal ones).", "Halls1974_results = pd.read_csv('./Data/Halls1974/pmag_results.txt',sep='\\t',skiprows=1)\n\n#filter so that individual results are shown filtering out mean poles\nHalls1974_results_i = Halls1974_results.ix[Halls1974_results['data_type']=='i']\n\n#filter so that reversed poles are included rather than normal poles\nHalls1974_results_r = Halls1974_results_i.ix[Halls1974_results['er_location_names']=='Osler Volcanics, Nipigon Strait, Lower Reversed']\n\nHalls1974_results_r.head()", "The data can be made into a list of [vgp_lon, vgp_lat] values using the ipmag.make_di_block function.", "SH_vgps = ipmag.make_di_block(SH2014_OslerR_upper['vgp_lon'].tolist(),\n SH2014_OslerR_upper['vgp_lat'].tolist())\nHalls_vgps = ipmag.make_di_block(Halls1974_results_r['vgp_lon'].tolist(),\n Halls1974_results_r['vgp_lat'].tolist())", "Conducting a common mean test\nThe question \"are the data sets consistent with being drawn from a common mean?\" can be addressed utilizing the ipmag.watson_common_mean function. This function calculates Watson's V statistic from input data through Monte Carlo simulation in order to test whether two populations of directional data could have been drawn from a common mean. The critical angle between the two sample mean directions and the corresponding McFadden and McElhinny (1990) classification is also printed. A plot can be shown of the cumulative distribution of the Watson V statistic as calculated during the Monte Carlo simulations, as suggested by Tauxe et al. (2010).", "ipmag.common_mean_watson(SH_vgps,Halls_vgps,NumSims=1000,plot='yes')", "Calculating a mean paleomagnetic pole\nWe can go ahead and calculate a mean paleomagnetic pole combining the VGPs from both studies. This mean pole was published in Swanson-Hysell et al. (2014).", "Osler_upperR_pole = pmag.fisher_mean(SH_vgps+Halls_vgps)\nipmag.print_pole_mean(Osler_upperR_pole)", "Plotting VGPs and the mean pole\nThe code below uses the ipmag.plot_vgp function to plot the virtual geomagnetic poles and the ipmag.plot_pole function to plot the calculated mean pole along with its $A_{95}$ confidence ellipse.\nThe plot is developed using the Basemap package which enables the plotting of data on a variety of geographic projections. Basemap is not a standard part of most scientific python distributions so you may need to take extra steps to install it. If using the Anaconda distribution, you can type conda install basemap at the command line. The Enthought Canopy distribution has a GUI package manager that you can use for installing the package although a Canopy subscription (free for academic users) may be necessary for installation.\nThe plot is saved to the Output_files folder as an .svg file.", "from mpl_toolkits.basemap import Basemap\n\nm = Basemap(projection='ortho',lat_0=35,lon_0=200,resolution='c',area_thresh=50000)\nplt.figure(figsize=(6, 6))\nm.drawcoastlines(linewidth=0.25)\nm.fillcontinents(color='bisque',zorder=1)\nm.drawmeridians(np.arange(0,360,30))\nm.drawparallels(np.arange(-90,90,30))\n\nipmag.plot_vgp(m,SH2014_OslerR_upper['vgp_lon'].tolist(),\n SH2014_OslerR_upper['vgp_lat'].tolist(),\n marker='o')\n\nipmag.plot_vgp(m,Halls1974_results_r['vgp_lon'].tolist(),\n Halls1974_results_r['vgp_lat'].tolist(),\n marker='o',label='Osler upper reversed VGPs')\n \nipmag.plot_pole(m,Osler_upperR_pole['dec'],\n Osler_upperR_pole['inc'],\n Osler_upperR_pole['alpha95'],\n marker='s',label='Osler upper reversed pole')\n\nplt.legend()\nplt.savefig('Output_files/pole_plot.svg')\nplt.show()", "Concluding thoughts\nThis notebook is intended to be an illustrative case study of some of the types of data analysis that can be accomplished using PmagPy within a Jupyter notebook. All the capabilities of PmagPy can be utilized within notebooks, although continued work is needed for the functionality within some of the command line programs to be made into functions that work well within the environment.\nAn advantage of this type of workflow is that it is well-documented and reproducible. The decisions that went into the data analysis and the implementation of the statistical tests are fully transparent (as is the underlying code). Additionally, if one were to seek to add more data to the mean pole, all of the data analysis could be quickly redone by executing all of the code in the notebook.\nSmaller snippets of code that demonstrate additional PmagPy functionality within the notebook environment can be seen in this notebook: \nhttp://pmagpy.github.io/Additional_PmagPy_Examples.html\nWorks cited\nDavis, D., and J. Green (1997), Geochronology of the North American Midcontinent rift in western Lake Superior and implications for its geodynamic evolution, Can. J. Earth Sci., 34, 476–488, doi:10.1139/e17–039.\nHalls, H. (1974), A paleomagnetic reversal in the Osler Volcanic Group, northern Lake Superior, Can. J. Earth Sci., 11, 1200–1207, doi:10.1139/e74–113.\nMcElhinny, M. W. (1964), Statistical Significance of the Fold Test in Palaeomagnetism. Geophysical Journal of the Royal Astronomical Society, 8: 338–340. doi: 10.1111/j.1365-246X.1964.tb06300.x\nMcFadden, P. L. and McElhinny, M. W. (1990), Classification of the reversal test in palaeomagnetism. Geophysical Journal International, 103: 725–729. doi: 10.1111/j.1365-246X.1990.tb05683.x\nMcFadden, P. L. (1990), A new fold test for palaeomagnetic studies. Geophysical Journal International, 103: 163–169. doi: 10.1111/j.1365-246X.1990.tb01761.x\nSwanson-Hysell, N. L., A. A. Vaughan, M. R. Mustain, and K. E. Asp (2014), Confirmation of progressive plate motion during the Midcontinent Rift’s early magmatic stage from the Osler Volcanic Group, Ontario, Canada, Geochemistry Geophysics Geosystems, 15, 2039–2047, doi:10.1002/2013GC005180.\nTauxe, L., and G. S. Watson (1994), The fold test: an eigen analysis approach, Earth Planet. Sci. Lett., 122, 331–341, doi:10.1016/0012-821X(94)90006-X.\nTauxe, L. with contributions from Subir K. Banerjee, Robert F. Butler and Rob van der Voo, Essentials of Paleomagnetism, Univ. California Press, 2010. Current online version: https://earthref.org/MagIC/books/Tauxe/Essentials/" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
molgor/spystats
notebooks/Sandboxes/Sketches_for_geopystats.ipynb
bsd-2-clause
[ "# Load Biospytial modules and etc.\n%matplotlib inline\nimport sys\nsys.path.append('/apps')\nimport django\ndjango.setup()\nimport pandas as pd\nimport numpy as np\n", "Sketches for automating spatial models\nThis notebook is for designing the tool box and methods for fitting spatial data.\nI´m using the library Geopystats (before spystats)\nRequirements\n\nGiven a dataset in Geopandas dataframe, create the Variogram object.\nAnd read from the file the variogram data", "from external_plugins.spystats import tools\n%run ../HEC_runs/fit_fia_logbiomass_logspp_GLS.py\n\nfrom external_plugins.spystats import tools\nhx = np.linspace(0,800000,100)\n", "The object new_data has been reprojected to Alberts and a linear model have been fitted with residuals stored as residuals", "new_data.residuals[:10]", "The empirical variogram\nThe empirical variogram has been calculated already using the HEC. A variogram object has been created which takes the values from the previously calculated in HEC", "gvg.plot(refresh=False,legend=False,percentage_trunked=20)\nplt.title(\"Semivariogram of residuals $log(Biomass) ~ log(SppR)$\")\n## HERE we can cast a model (Whittle) and fit it inside the global variogram\nwhittle_model = tools.WhittleVariogram(sill=0.345,range_a=100000,nugget=0.33,alpha=1.0)\ntt = gvg.fitVariogramModel(whittle_model)\nplt.plot(hx,gvg.model.f(hx),'--',lw=4,c='black')\nprint(whittle_model)\n\n## This section is an example for calculating GLS. Using a small section because of computing intensity\n\nminx = -85\nmaxx = -80\nminy = 30\nmaxy = 35\n\nsection = tools._subselectDataFrameByCoordinates(new_data,'LON','LAT',minx,maxx,miny,maxy)\nsecvg = tools.Variogram(section,'logBiomass',model=whittle_model)\nMMdist = secvg.distance_coordinates.flatten()\nCovMat = secvg.model.corr_f(MMdist).reshape(len(section),len(section))\nplt.imshow(CovMat)\n\nimport statsmodels.regression.linear_model as lm\nimport statsmodels.api as sm\nmodel1 = lm.GLS.from_formula(formula='logBiomass ~ logSppN',data=section,sigma=CovMat)\nresults = model1.fit()\nresum = results.summary()\n\n\nk = resum.as_csv()\n\n## Without spatial structure\nId = np.identity(len(section))\nmodel2 = lm.GLS.from_formula(formula='logBiomass ~ logSppN',data=section,sigma=Id)\nresults = model2.fit()\nsmm =results.summary()\n\n## Without spatial structure\nimport statsmodels.formula.api as smf\n\nmodel3 = smf.ols(formula='logBiomass ~ logSppN',data=section)\nresults = model3.fit()\nresults.summary()\n\n", "Bonus! simulation of the random processs", "from scipy.stats import multivariate_normal as mvn\nfrom scipy.spatial import distance_matrix\n\nn = 50\nnx = np.linspace(0,100,n)\nxx, yy = np.meshgrid(nx,nx)\n\npoints = np.vstack([ xx.ravel(), yy.ravel()]).transpose()## Generate dist matrix\nMdist = distance_matrix(points,points)\n\n\nplt.imshow(Mdist)\n\nMdist.shape\ncovmat = secvg.model.corr_f(Mdist.flatten()).reshape(Mdist.shape)\n\n\n\nplt.imshow(covmat)\n\n\nmeanx = np.zeros(n*n)\nsim1 = mvn.rvs(mean=meanx,cov=covmat)\n\nplt.imshow(sim1.reshape(n,n),interpolation=None)\n\n%time sim2 = mvn.rvs(mean=meanx,cov=covmat)\nplt.imshow(sim2.reshape(n,n))", "Bonus!\nFitting the model to the empirical variogram\nIt´s included as a method in the VariogramModel class.", "matm = tools.MaternVariogram(sill=0.34,range_a=100000,nugget=0.33,kappa=0.5)\nexpmm = tools.ExponentialVariogram(sill=0.34,range_a=100000,nugget=0.33)\ngausms = tools.GaussianVariogram(sill=0.34,range_a=100000,nugget=0.33)\nsphmm = tools.SphericalVariogram(sill=0.34,range_a=100000,nugget=0.33)\nwm = tools.WhittleVariogram(sill=0.34,range_a=100000,nugget=0.33,alpha=1)\nmap(lambda l : l.fit(gvg), [matm,expmm,gausms,sphmm,wm])\n\nprint(matm)\nprint(expmm)\nprint(gausms)\nprint(sphmm)\nprint(wm)" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
icane/intro-opendata
demo-uni.ipynb
mit
[ "Ejemplo de procesado y visualización de datos estadísticos de Cantabria usando la web del ICANE\nEn el siguiente cuaderno se muestran tres ejemplos sencillos de manipulación y representación de datos obtenidos a través de las interfaces web del ICANE. Para ello se ha utilizado Pandas, la biblioteca de análisis de datos por excelencia en Python; pyicane, una biblioteca desarrollada por personal del ICANE para facilitar la extracción automática de datos a partir del formato JSON y Vincent, una librería de visualización que abstrae la complejidad de Vega (JSON), a su vez abstracción de D3.js en Javascript.\nEjemplo de obtención de datos\nEn primer lugar, se mostrará una forma sencilla de extraer datos de forma automatizada usando la API de datos del ICANE.\nPara ello, se tomará como ejemplo la serie de Revisiones Anuales del Padrón Municipal de Habitantes.", "from pyicane import pyicane\nfrom collections import OrderedDict\n\n#Obtención de datos de Revisión Anual del PMH desde la web del ICANE\nrapmh = pyicane.TimeSeries.get('municipal-register-annual-review-municipality')\n\n#Conversión a dataframe\ndata = rapmh.data_as_dataframe()\n\n#Filtrado de variables y año\nvarint = data[(data['Variables'] == \n 'Variación interanual') & (data.index == '2014')]\n\n#Filtrado del total Cantabria\nvarint = varint.ix[:-1]\n\n#Obtención de código INE y nombre de municipio en columnas separadas\ncod_ine = [item.split(' - ')[0].lstrip() for item in varint['Municipios']]\nnombres = [item.split(' - ')[1].lstrip() for item in varint['Municipios']]\nvarint['cod_ine'] = cod_ine\nvarint['nombres'] = nombres\n\n#Conversión automática de tipos de datos\nvarint = varint.convert_objects(convert_numeric=True)\nvarint.head()", "Mapa de coropletas\nA continuación, se mostrará un ejemplo de representación de datos en mapas en forma de coropletas.\nPara este ejemplo, se ha utilizado un mapa en formato GeoJSON realizado con datos del Gobierno de Cantabria-IGN-CNIG, límites inscritos en el Registro Central de Cartografía a fecha 13 de Diciembre de 2012 y proporcionado por la Consejería de Medio Ambiente, Ordenación del Territorio y Urbanismo.\nCon objeto de obtener una representación más manejable, previamente se convirtió el mapa a formato TopoJSON, utilizado posteriormente para dibujarlo. Para servirlo, se ha subido este archivo a la nube S3 de Amazon.\nConcretamente lo que se pretende representar es la tasa de variación anual de población según la serie anterior.", "import vincent\nfrom vincent.values import ValueRef\nfrom IPython.display import display\nimport requests\n\nvincent.core.initialize_notebook()\n\n#Obtención de los datos del mapa municipal en topojson\ncantabria_topo = r'http://d1jbhcb2qvxl2c.cloudfront.net/cantabria.topo.json'\ngeo_data = [{'name': 'cantabria',\n 'url': cantabria_topo,\n 'feature': 'cantabria'}]\n\n#Creación del gráfico y asociación de los datos al mapa\nvis = vincent.Map(geo_data=geo_data, data=varint, scale=20000, \n projection = 'mercator', center = [-4.00, 43.13],\n data_bind='Valor', data_key='cod_ine',\n map_key={'cantabria': 'properties.COD_INE'})\nvis.marks[0].properties.enter.stroke_opacity = ValueRef(value=0.5)\nvis.legend(title=\"Revisión anual PMH: variación interanual de población\")\ndisplay(vis)", "Operaciones con datos\nEn las siguientes secciones se observará cómo trabajar con datos ya extraídos automáticamente. En concreto, se realizarán operaciones de filtrado, limpieza, pivotaje y manipulación de datos en general.\nPara estos ejemplos se utilizará la serie de Precios corrientes de la Contabilidad trimestral de Cantabria, Base 2008 y CNAE 2009.", "import datetime as dt\nimport calendar\nimport time\n\n#Obtención de datos de CTC desde la web del ICANE\ncontrim_raw = pyicane.TimeSeries.get('quarterly-accounting-cantabria-base-2008-current-prices')\ncontrim_df = contrim_raw.data_as_dataframe()\n\n#Filtrado de datos para conseguir:\n# Tasa de variación interanual\n# Ajustada de estacionalidad y efecto calendario\n# PIB total\ntvarint = contrim_df[(contrim_df['Variables'] == \n 'Tasa de variación interanual') & (contrim_df['Tipo de ajuste'] == \n 'Ajustada de estacionalidad y efecto calendario')& (contrim_df['Sector'] == \n '1 PIB total')]\n\n#Filtrado de filas con valor desconocido\ntvarint = tvarint[tvarint['Valor']!='..'] \ntvarint.head()", "Una vez extraídos y filtrados los datos, será necesario crear un índice temporal a partir de los datos de año y trimestre:", "#Extracción del año y el trimestre y generación de fechas\nanyo, trimestre = zip(*(s.split(\" - \") for s in list(tvarint.index)))\nfechas = [dt.datetime(int(y) , int(q)*3, int(calendar.monthrange(int(y), int(q)*3)[1])) for q,y in zip(trimestre,anyo)]\n\n#Adición de columna de fechas a la serie\ntvarint['fechas'] = fechas\n\n#Pivotaje para obtener una columna por categoría\ntvarint = tvarint.pivot(index='fechas',columns='Sector', values='Valor')\ntvarint.head()", "Gráfico de línea\nEs posible utilizar los datos obtenidos para representar gráficamente la serie temporal a través de un gráfico de línea y utilizando un etiquetado sencillo:", "#Generación del gráfico de serie temporal\nlineas = vincent.Line(tvarint)\nlineas.scales[0].type = 'time'\nlineas.axis_titles(x='Tiempo', y='Valor')\nlineas.legend(title='PIB total')\ndisplay(lineas)", "Gráfico multilínea\nFinalmente, se generará un nuevo conjunto de datos seleccionando los sectores de Industria y energía, construcción y servicios. A partir de dicho conjunto, realizando operaciones similares a las detalladas anteriormente, es posible obtener una representación multilínea de la serie temporal categorizada según dichos sectores:", "import datetime as dt\nimport calendar\nimport time\n\n#Filtrado de datos para conseguir:\n# Tasa de variación interanual\n# Ajustada de estacionalidad y efecto calendario\n# Sectores Industria, construcción y servicios\ntvarint_multi = contrim_df[(contrim_df['Variables'] == \n 'Tasa de variación interanual') & (contrim_df['Tipo de ajuste'] == \n 'Ajustada de estacionalidad y efecto calendario')& ((contrim_df['Sector'] == \n '3 Industria y energía') | (contrim_df['Sector'] == \n '4 Construcción') | (contrim_df['Sector'] == \n '5 Servicios'))]\n\n#Filtrado de filas con valor desconocido\ntvarint_multi = tvarint_multi[tvarint_multi['Valor']!='..'] \ntvarint_multi.head()\n\n#Extracción del año y el trimestre y generación de fechas\nanyo, trimestre = zip(*(s.split(\" - \") for s in list(tvarint_multi.index)))\nfechas = [dt.datetime(int(y) , int(q)*3, int(calendar.monthrange(int(y), int(q)*3)[1])) for q,y in zip(trimestre,anyo)]\n\n#Adición de columna de fechas a la serie\ntvarint_multi['fechas'] = fechas\n\n#Pivotaje para obtener una columna por categoría\ntvarint_multi = tvarint_multi.pivot(index='fechas',columns='Sector', values='Valor')\ntvarint.head()\n\n#Generación de gráfico multi-línea\nmulti = vincent.Line(tvarint_multi)\nmulti.scales[0].type = 'time'\nmulti.axis_titles(x='Tiempo', y='Valor')\nmulti.legend(title='Tasa de variación interanual')\ndisplay(multi)", "Con estos ejemplos se ha pretendido ofrecer un marco introductorio para la obtención, tratamiento y representación de datos estadísticos de Cantabria utilizando el lenguaje de programación Python conjuntamente con sus bibliotecas más comunes, así como una bilioteca propia para la extracción automática de datos desde la web del ICANE." ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
landlab/landlab
notebooks/teaching/geomorphology_exercises/channels_streampower_notebooks/stream_power_channels_class_notebook.ipynb
mit
[ "<a href=\"http://landlab.github.io\"><img style=\"float: left\" src=\"../../../landlab_header.png\"></a>\nQuantifying river channel evolution with Landlab\nThese exercises are based on a project orginally designed by Kelin Whipple at Arizona State University. This notebook was created by Nicole Gasparini at Tulane University.\n<hr>\n<small>For tutorials on learning Landlab, click here: <a href=\"https://github.com/landlab/landlab/wiki/Tutorials\">https://github.com/landlab/landlab/wiki/Tutorials</a></small>\n<hr>\n\nWhat is this notebook?\nThis notebook illustrates the evolution of detachment-limited channels in an actively uplifting landscape. The landscape evolves according to the equation:\n\\begin{equation}\n \\frac{d z}{d t} = -K_\\text{sp} A^{m_{sp}} S^{n_{sp}} + U\n\\end{equation}\nHere, $K_{sp}$ is the erodibility coefficient on fluvial incision, which is thought to be positively correlated with climate wetness, or storminess (this is hard to quantify) and to be negatively correlated with rock strength (again, rock strength is hard to quantify). $m_{sp}$ and $n_{sp}$ are positive exponents, usually thought to have a ratio, $m_{sp}/n_{sp} \\approx 0.5$. $A$ is drainage area and $S$ is the slope of steepest descent ($-\\frac{dz}{dx}$) where $x$ is horizontal distance (positive in the downslope direction) and $z$ is elevation. (If slope is negative there is no fluvial erosion.) $U$ is an externally-applied rock uplift field.\nThe fluvial erosion term is also known as the stream power equation. Before using this notebook you should be familiar with this equation from class lectures and reading. \nFor a great overview of the stream power equation, see: \n\nWhipple and Tucker, 1999, Dynamics of the stream-power river incision model: Implications for height limits of mountain ranges, landscape response timescales, and research needs, Journal of Geophysical Research.\n\nFor some great illustrations of modeling with the sream power equation, see:\n\nTucker and Whipple, 2002, Topographic outcomes predicted by stream erosion models: Sensitivity analysis and intermodel comparison, Journal of Geophysical Research.\n\nHelpful background on landscape sensitivity to rock uplift rates and patterns can be found here:\n\nKirby and Whipple, 2012, Expression of active tectonics in erosional landscapes, Journal of Structural Geology.\n\nWhat will you do?\nIn this exercise you will modify the code to get a better understanding of how rock uplift rates and patterns and the erodibility coefficient control fluvial channel form.\nStart at the top by reading each block of text and sequentially running each code block (shift - enter OR got to the Cell pulldown menu at the top and choose Run Cells). \nIf you just change one code block and rerun only that code block, only the parts of the code in that code block will be updated. (E.g. if you change parameters but don't reset the code blocks that initialize run time or topography, then these values will not be reset.) \nSTUDENTS: Questions to answer before starting this assignment.\nAnswer these questions before running the notebook.\n\nWhat do you think will happen to total relief (defined as the maximum minus the minimum elevation, here area is fixed) and channel slope at steady state if $K_{sp}$ is uniformly increased?\nWhat do you think will happen to total relief and channel slope at steady state if $U$ is uniformly increased?\nHow do you think a steady-state landscape with a uniform low rock uplift rate will respond if rock uplift is uniformly increased (relative to a steady base level)? How will channel slopes change through time?\n\nNow on to the code...\nFirst we have to import the parts of Python and Landlab that are needed to run this code. You should not have to change this first code block.", "# Code block 1\n\nimport copy\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom landlab import RasterModelGrid, imshow_grid\nfrom landlab.components import (\n ChannelProfiler,\n ChiFinder,\n FlowAccumulator,\n SteepnessFinder,\n StreamPowerEroder,\n)\nfrom landlab.io import write_esri_ascii", "Make a grid and set boundary conditions.", "# Code Block 2\n\nnumber_of_rows = 50 # number of raster cells in vertical direction (y)\nnumber_of_columns = 100 # number of raster cells in horizontal direction (x)\ndxy = 200 # side length of a raster model cell, or resolution [m]\n\n# Below is a raster (square cells) grid, with equal width and height\nmg1 = RasterModelGrid((number_of_rows, number_of_columns), dxy)\n\n# Set boundary conditions - only the south side of the grid is open.\n# Boolean parameters are sent to function in order of\n# east, north, west, south.\nmg1.set_closed_boundaries_at_grid_edges(True, True, True, False)", "Here we make the initial grid of elevation of zeros with a very small amount of noise to make a more pleasing network.", "# Code Block 3\n\nnp.random.seed(35) # seed set so our figures are reproducible\nmg1_noise = (\n np.random.rand(mg1.number_of_nodes) / 1000.0\n) # intial noise on elevation gri\n\n# set up the elevation on the grid\nz1 = mg1.add_zeros(\"topographic__elevation\", at=\"node\")\nz1 += mg1_noise", "Set parameters related to time.", "# Code Block 4\n\ntmax = 5e5 # time for the model to run [yr] (Original value was 5E5 yr)\ndt = 1000 # time step [yr] (Original value was 100 yr)\ntotal_time = 0 # amount of time the landscape has evolved [yr]\n# total_time will increase as you keep running the code.\n\nt = np.arange(0, tmax, dt) # each of the time steps that the code will run", "Set parameters for incision and intializing all of the process components that do the work. We also initialize tools for quantifying the landscape.", "# Code Block 5\n\n# Original K_sp value is 1e-5\nK_sp = 1.0e-5 # units vary depending on m_sp and n_sp\nm_sp = 0.5 # exponent on drainage area in stream power equation\nn_sp = 1.0 # exponent on slope in stream power equation\n\nfrr = FlowAccumulator(mg1, flow_director=\"FlowDirectorD8\") # intializing flow routing\nspr = StreamPowerEroder(\n mg1, K_sp=K_sp, m_sp=m_sp, n_sp=n_sp, threshold_sp=0.0\n) # initializing stream power incision\n\ntheta = m_sp / n_sp\n# initialize the component that will calculate channel steepness\nsf = SteepnessFinder(mg1, reference_concavity=theta, min_drainage_area=1000.0)\n# initialize the component that will calculate the chi index\ncf = ChiFinder(\n mg1, min_drainage_area=1000.0, reference_concavity=theta, use_true_dx=True\n)", "Initialize rock uplift rate. This will need to be changed later.", "# Code Block 6\n\n# uplift_rate [m/yr] (Original value is 0.0001 m/yr)\nuplift_rate = np.ones(mg1.number_of_nodes) * 0.0001", "Now for the code loop. \nNote that you can rerun Code Block 7 many times, and as long as you don't reset the elevation field (Code Block 3), it will take the already evolved landscape and evolve it even more. If you want to change parameters in other code blocks (e.g. Code Block 5 or 6), you can do that too, and as long as you don't reset the elevation field (Code Block 3) the new parameters will apply on the already evolved topography.", "# Code Block 7\n\nfor ti in t:\n z1[mg1.core_nodes] += uplift_rate[mg1.core_nodes] * dt # uplift the landscape\n frr.run_one_step() # route flow\n spr.run_one_step(dt) # fluvial incision\n total_time += dt # update time keeper\n print(total_time)", "Plot the topography.", "# Code Block 8\n\nimshow_grid(\n mg1, \"topographic__elevation\", grid_units=(\"m\", \"m\"), var_name=\"Elevation (m)\"\n)\ntitle_text = f\"$K_{{sp}}$={K_sp}; $time$={total_time} yr; $dx$={dxy} m\"\nplt.title(title_text)\n\nmax_elev = np.max(z1)\nprint(\"Maximum elevation is \", np.max(z1))", "Plot the slope and area data at each point on the landscape (in log-log space). We will only plot the core nodes because the boundary nodes have slopes that are influenced by the boundary conditions.", "# Code Block 9\n\nplt.loglog(\n mg1.at_node[\"drainage_area\"][mg1.core_nodes],\n mg1.at_node[\"topographic__steepest_slope\"][mg1.core_nodes],\n \"b.\",\n)\nplt.ylabel(\"Topographic slope\")\nplt.xlabel(\"Drainage area (m^2)\")\ntitle_text = f\"$K_{{sp}}$={K_sp}; $time$={total_time} yr; $dx$={dxy} m\"\n\nplt.title(title_text)", "It is slightly easier to interpret slope-area data when we look at a single channel, rather than the entire landscape. Below we plot the profile and slope-area data for the three largest channels on the landscape.", "# Code Block 10\n\n# profile the largest channels, set initially to find the mainstem channel in the three biggest watersheds\n# you can change the number of watersheds, or choose to plot all the channel segments in the watershed that\n# have drainage area below the threshold (here we have set the threshold to the area of a grid cell).\nprf = ChannelProfiler(\n mg1,\n number_of_watersheds=3,\n main_channel_only=True,\n minimum_channel_threshold=dxy ** 2,\n)\nprf.run_one_step()\n\n# plot the elevation as a function of distance upstream\nplt.figure(1)\ntitle_text = f\"$K_{{sp}}$={K_sp}; $time$={total_time} yr; $dx$={dxy} m\"\nprf.plot_profiles(\n xlabel=\"distance upstream (m)\", ylabel=\"elevation (m)\", title=title_text\n)\n\n# plot the location of the channels in map view\nplt.figure(2)\nprf.plot_profiles_in_map_view()\n\n# slope-area data in just the profiled channels\nplt.figure(3)\nfor i, outlet_id in enumerate(prf.data_structure):\n for j, segment_id in enumerate(prf.data_structure[outlet_id]):\n if j == 0:\n label = \"channel {i}\".format(i=i + 1)\n else:\n label = \"_nolegend_\"\n segment = prf.data_structure[outlet_id][segment_id]\n profile_ids = segment[\"ids\"]\n color = segment[\"color\"]\n plt.loglog(\n mg1.at_node[\"drainage_area\"][profile_ids],\n mg1.at_node[\"topographic__steepest_slope\"][profile_ids],\n \".\",\n color=color,\n label=label,\n )\n\nplt.legend(loc=\"lower left\")\nplt.xlabel(\"drainage area (m^2)\")\nplt.ylabel(\"channel slope [m/m]\")\ntitle_text = f\"$K_{{sp}}$={K_sp}; $time$={total_time} yr; $dx$={dxy} m\"\nplt.title(title_text)", "The chi index is a useful way to quantitatively interpret fluvial channels. Below we plot the chi index in the three largest channels and also a chi map across the entire landscape.", "# Code Block 11\n\n# calculate the chi index\ncf.calculate_chi()\n\n# chi-elevation plots in the profiled channels\nplt.figure(4)\n\nfor i, outlet_id in enumerate(prf.data_structure):\n for j, segment_id in enumerate(prf.data_structure[outlet_id]):\n if j == 0:\n label = \"channel {i}\".format(i=i + 1)\n else:\n label = \"_nolegend_\"\n segment = prf.data_structure[outlet_id][segment_id]\n profile_ids = segment[\"ids\"]\n color = segment[\"color\"]\n plt.plot(\n mg1.at_node[\"channel__chi_index\"][profile_ids],\n mg1.at_node[\"topographic__elevation\"][profile_ids],\n color=color,\n label=label,\n )\n\nplt.xlabel(\"chi index (m)\")\nplt.ylabel(\"elevation (m)\")\nplt.legend(loc=\"lower right\")\ntitle_text = (\n f\"$K_{{sp}}$={K_sp}; $time$={total_time} yr; $dx$={dxy} m; concavity={theta}\"\n)\nplt.title(title_text)\n\n# chi map\nplt.figure(5)\nimshow_grid(\n mg1,\n \"channel__chi_index\",\n grid_units=(\"m\", \"m\"),\n var_name=\"Chi index (m)\",\n cmap=\"jet\",\n)\ntitle_text = (\n f\"$K_{{sp}}$={K_sp}; $time$={total_time} yr; $dx$={dxy} m; concavity={theta}\"\n)\nplt.title(title_text)", "The channel steepness index is another useful index to quantify fluvial channels. Below we plot the steepness index in the same three largest channels, and also plot steepness index across the grid.", "# Code Block 12\n\n# calculate channel steepness\nsf.calculate_steepnesses()\n\n# plots of steepnes vs. distance upstream in the profiled channels\nplt.figure(6)\n\nfor i, outlet_id in enumerate(prf.data_structure):\n for j, segment_id in enumerate(prf.data_structure[outlet_id]):\n if j == 0:\n label = \"channel {i}\".format(i=i + 1)\n else:\n label = \"_nolegend_\"\n segment = prf.data_structure[outlet_id][segment_id]\n profile_ids = segment[\"ids\"]\n distance_upstream = segment[\"distances\"]\n color = segment[\"color\"]\n plt.plot(\n distance_upstream,\n mg1.at_node[\"channel__steepness_index\"][profile_ids],\n \"x\",\n color=color,\n label=label,\n )\n\nplt.xlabel(\"distance upstream (m)\")\nplt.ylabel(\"steepness index\")\nplt.legend(loc=\"upper left\")\nplt.title(f\"$K_{{sp}}$={K_sp}; $time$={total_time} yr; $dx$={dxy} m; concavity={theta}\")\n\n# channel steepness map\nplt.figure(7)\nimshow_grid(\n mg1,\n \"channel__steepness_index\",\n grid_units=(\"m\", \"m\"),\n var_name=\"Steepness index \",\n cmap=\"jet\",\n)\ntitle_text = (\n \"$K_{sp}$=\"\n + str(K_sp)\n + \"; $time$=\"\n + str(total_time)\n + \"yr; $dx$=\"\n + str(dxy)\n + \"m\"\n + \"; concavity=\"\n + str(theta)\n)\nplt.title(f\"$K_{{sp}}$={K_sp}; $time$={total_time} yr; $dx$={dxy} m; concavity={theta}\")", "If you have a grid that you want to export, uncomment and edit the appropriate lines below and run the code block.", "# Code Block 13\n\n## Below has the name of the file that data will be written to.\n## You need to change the name of the file every time that you want\n## to write data, otherwise you will get an error.\n## This will write to the directory that you are running the code in.\n# write_file_name = 'data_file.txt'\n## Below is writing elevation data in the ESRI ascii format so that it can\n## easily be read into Arc GIS or back into Landlab.\n# write_esri_ascii(write_file_name, mg1, 'topographic__elevation')", "After running every code block once, has the landscape reached steady state? Answer: NO! How do you know? After you think about this, you are ready to complete this project.\nAnswer the following questions using the code above and below. All answers should be typed, and supporting figures (produced using the code) should be embedded in one document that you hand in. Code Blocks 8-12 and 18-21 produce different figures that you may find useful. You can use any or all of these different figures to help you with the questions below. (Download or screenshoot the figures.) \nAnything with a question mark should be answered in the document that you hand in. Make sure your write in full sentences and proofread the document that you hand in.\n\nSteady state with low uplift rate. Using the parameters provided in the initial notebook, run the landscape to steady state. (Note that you can keep running the main evolution loop - Code Block 7 - and the different plotting blocks without running the code blocks above them. You may also want to change $tmax$ in Code Block 4.) How did you know that the landscape reached steady state? Note the approximate time that it took to reach steady state for your own reference. (This will be usefull for later questions.) Include appropriate plots. (If you want to analyze these landscapes outside of Landlab or save for later, make sure you save the elevation data to a text file (Code Block 13).)\n\n NOTE, For the rest of the questions you should use Code Blocks 14 - 21. These will allow you to use the steady-state landscape created for question 1 - referred to here as the 'base landscape' - as the initial condition. Start by editing what you need to in Code Blocks 14 - 16. Run these each once, sequentially. You can run Code Block 17, the time loop, as many times as you need to, along with Code Blocks 18-21, which produce plots.\n\n\nTransient landscape responding to an increase in rock uplift. Use the base landscape and increase rock uplift uniformly by a factor of 4 to 0.0004 m/yr. Make sure you update the rock uplift rate (Code Block 16) and ensure that $tmax$ is 1e5 yrs and $dt$ is 500 yrs (Code Block 15). Run this until the maximum elevation in the grid is ~ 170 m and observe how the landscape gets to this elevation, i.e. plot intermediate steps. What patterns do you see in the supporting plots that illustrate this type of transient? Which patterns, if any, are diagnostic of a landscape response to uniform increase in rock uplift rate? (You may need to answer this after completing all of the questions.)\n\n\n Steady-state landscape with increased rock uplift. Now run the landscape from question 2 until it reaches steady state. (I.e. run the time loop, Code Block 17, a bunch of times. You can increase $tmax$ and $dt$ to make this run faster.) Provide a plot that illustrates that the landscape is in steady state. What aspects of the landscape have changed in comparison with the base landscape from question 1?\n\n\n Increase erodibility. Start again from the base landscape, but this time increase $K_{sp}$ to 2E-5 (Code Block 14). Make sure rock uplift rate is set to the original value of 0.0001 m/yr (Code Block 16). Set $tmax$ to 1e5 yrs (Code Block 15). Run for 1e5 yrs and save the plots that you think are diagnostic. Run for another 1e5 yrs and save plots again. Now run for 5e5 yrs and save plots again. Quantitatively describe how the landscape evolves in response to the increase in erodibility and provide supporting plots. What could cause a uniform increase in erodibility?\n\n\n Spatially varible uplift - discrete, massive earthquake. Start again from the base landscape, and make sure that $K_{sp}$ = 1E-5 (Code Block 14). Now add a seismic event to this steady state landscape - a fault that runs horizontally across the landscape at y = 4000 m, and instantaneously uplifts half the landscape by 10 meters (Code Block 16). In this case, we will keep background uplift uniform at 0.0001 m/yr. Set $tmax$ to 1e5 yrs and $dt$ to 500 yrs (Code Block 15) before evolving the landscape after the fault. Now run the time loop four times and look at the different plots after each loop. How does the landscape respond to this fault? What patterns do you see in the supporting plots that illustrate this type of transient? Which patterns, if any, are diagnostic of a channel response to an earthquake? (You may need to answer this after completing all of the questions.)\n\n\n Spatially Varible Rock Uplift - discrete fault with two different uplift rates. Start again from the base landscape, and make sure that $K_{sp}$ = 1E-5 (Code Block 14). Now we will add a fault (at y = 4000 m) to this landscape. In this case the uplift rate on the footwall is higher (0.0004 m/yr) than on the hanging wall (uplift rate = 0.0001 m/yr). (Edit Code Block 16.) Set $tmax$ to 1e5 yrs and $dt$ to 500 yrs (Code Block 15). Now run the time loop four separate times and look at the different plots after each loop. How does the landscape respond to this fault? What patterns do you see in the supporting plots that illustrate this type of transient? Which patterns, if any, are diagnostic of a channel response to a this type of gradient in rock uplift rates? (You may need to answer this after completing all of the questions.)\n\n\n Spatially Varible Rock Uplift - gradient in uplift across the range. Start again from the base landscape, and make sure that $K_{sp}$ = 1E-5 (Code Block 14). Now we will add a linear gradient in uplift rate across the entire range (edit Code Block 16). The maximum uplift rate will be 0.0004 m/yr at the core of the range, and 0.0001 m/yr at the front of the range. Set $tmax$ to 1e5 yrs (Code Block 4) and $dt$ to 500 yrs before you start running the time loop for the fault before you start running the time loop with the rock uplift gradient. Now run the time loop four separate times and look at the different plots after each loop. How does the landscape respond to this gradient in uplift rate? What patterns do you see in the supporting plots that illustrate this type of transient? Which patterns, if any, are diagnostic of a channel response to this type of gradient in rock uplift rates? (You may need to answer this after completing all of the questions.)\n\n\n Final Reflection. Was your initial insight into how parameters would affect the landscape correct? Discuss in 6 sentences or less.", "# Code Block 14\n\nnumber_of_rows = 50 # number of raster cells in vertical direction (y)\nnumber_of_columns = 100 # number of raster cells in horizontal direction (x)\ndxy2 = 200 # side length of a raster model cell, or resolution [m]\n\n# Below is a raster (square cells) grid, with equal width and height\nmg2 = RasterModelGrid((number_of_rows, number_of_columns), dxy2)\n\n# Set boundary conditions - only the south side of the grid is open.\n# Boolean parameters are sent to function in order of\n# east, north, west, south.\nmg2.set_closed_boundaries_at_grid_edges(True, True, True, False)\n\nz2 = copy.copy(z1) # initialize the elevations with the steady state\n# topography produced for question 1\nz2 = mg2.add_field(\"topographic__elevation\", z2, at=\"node\")\n\n# K_sp value for base landscape is 1e-5\nK_sp2 = 1e-5 # units vary depending on m_sp and n_sp\nm_sp2 = 0.5 # exponent on drainage area in stream power equation\nn_sp2 = 1.0 # exponent on slope in stream power equation\n\nfrr2 = FlowAccumulator(mg2, flow_director=\"FlowDirectorD8\") # intializing flow routing\nspr2 = StreamPowerEroder(\n mg2, K_sp=K_sp2, m_sp=m_sp2, n_sp=n_sp2, threshold_sp=0.0\n) # initializing stream power incision\n\ntheta2 = m_sp2 / n_sp2\n# initialize the component that will calculate channel steepness\nsf2 = SteepnessFinder(mg2, reference_concavity=theta2, min_drainage_area=1000.0)\n# initialize the component that will calculate the chi index\ncf2 = ChiFinder(\n mg2, min_drainage_area=1000.0, reference_concavity=theta2, use_true_dx=True\n)\n\n# Code Block 15\n\ntmax = 1e5 # time for the model to run [yr] (Original value was 5E5 yr)\ndt = 500 # time step [yr] (Original value was 500 yr)\ntotal_time = 0 # amount of time the landscape has evolved [yr]\n# total_time will increase as you keep running the code.\n\nt = np.arange(0, tmax, dt) # each of the time steps that the code will run\n\n# Code Block 16\n\n# uplift_rate [m/yr] (value was 0.0001 m/yr for base landscape)\nuplift_rate = np.ones(mg2.number_of_nodes) * 0.0001\n\n## If you want to add a one-time event that uplifts only part of the\n## landscape, uncomment the 3 lines below\n# fault_location = 4000 # [m]\n# uplift_amount = 10 # [m]\n# z2[np.nonzero(mg2.node_y>fault_location)] += uplift_amount\n\n## IMPORTANT! To use the below fault generator, comment the one-time\n## uplift event above if it isn't already commented out.\n## Code below creates a fault horizontally across the grid.\n## Uplift rates are greater where y values > fault location.\n## To use, uncomment the 5 code lines below and edit to your values\n# fault_location = 4000 # [m]\n# low_uplift_rate = 0.0001 # [m/yr]\n# high_uplift_rate = 0.0004 # [m/yr]\n# uplift_rate[np.nonzero(mg2.node_y<fault_location)] = low_uplift_rate\n# uplift_rate[np.nonzero(mg2.node_y>fault_location)] = high_uplift_rate\n\n## IMPORTANT! To use below rock uplift gradient, comment the two\n## uplift options above if they aren't already commented out.\n## If you want a linear gradient in uplift rate\n## (increasing uplift into the range),\n## uncomment the 4 code lines below and edit to your values.\n# low_uplift_rate = 0.0001 # [m/yr]\n# high_uplift_rate = 0.0004 # [m/yr]\n## below is uplift gradient per node row index, NOT row value in meters\n# uplift_rate_gradient = (high_uplift_rate - low_uplift_rate)/(number_of_rows-3)\n# uplift_rate = low_uplift_rate + ((mg2.node_y / dxy)-1) * uplift_rate_gradient\n\n# Code Block 17\n\nfor ti in t:\n z2[mg2.core_nodes] += uplift_rate[mg2.core_nodes] * dt # uplift the landscape\n frr2.run_one_step() # route flow\n spr2.run_one_step(dt) # fluvial incision\n total_time += dt # update time keeper\n print(total_time)\n\n# Code Block 18\n# Plot topography\n\nplt.figure(8)\nimshow_grid(\n mg2, \"topographic__elevation\", grid_units=(\"m\", \"m\"), var_name=\"Elevation (m)\"\n)\nplt.title(f\"$K_{{sp}}$={K_sp2}; $time$={total_time} yr; $dx$={dxy2} m\")\n\nmax_elev = np.max(z2)\nprint(\"Maximum elevation is \", np.max(z2))\n\n# Code Block 19\n# Plot Channel Profiles and slope-area data along the channels\n\nprf2 = ChannelProfiler(\n mg2,\n number_of_watersheds=3,\n main_channel_only=True,\n minimum_channel_threshold=dxy ** 2,\n)\nprf2.run_one_step()\n\n# plot the elevation as a function of distance upstream\nplt.figure(9)\ntitle_text = f\"$K_{{sp}}$={K_sp2}; $time$={total_time} yr; $dx$={dxy} m\"\nprf2.plot_profiles(\n xlabel=\"distance upstream (m)\", ylabel=\"elevation (m)\", title=title_text\n)\n\n# plot the location of the channels in map view\nplt.figure(10)\nprf2.plot_profiles_in_map_view()\n\n# slope-area data in just the profiled channels\nplt.figure(11)\nfor i, outlet_id in enumerate(prf2.data_structure):\n for j, segment_id in enumerate(prf2.data_structure[outlet_id]):\n if j == 0:\n label = \"channel {i}\".format(i=i + 1)\n else:\n label = \"_nolegend_\"\n segment = prf2.data_structure[outlet_id][segment_id]\n profile_ids = segment[\"ids\"]\n color = segment[\"color\"]\n plt.loglog(\n mg2.at_node[\"drainage_area\"][profile_ids],\n mg2.at_node[\"topographic__steepest_slope\"][profile_ids],\n \".\",\n color=color,\n label=label,\n )\n\nplt.legend(loc=\"lower left\")\nplt.xlabel(\"drainage area (m^2)\")\nplt.ylabel(\"channel slope [m/m]\")\ntitle_text = f\"$K_{{sp}}$={K_sp2}; $time$={total_time} yr; $dx$={dxy2} m\"\nplt.title(title_text)\n\n# Code Block 20\n# Chi Plots\n\n# calculate the chi index\ncf2.calculate_chi()\n\n# chi-elevation plots in the profiled channels\nplt.figure(12)\nfor i, outlet_id in enumerate(prf2.data_structure):\n for j, segment_id in enumerate(prf2.data_structure[outlet_id]):\n if j == 0:\n label = \"channel {i}\".format(i=i + 1)\n else:\n label = \"_nolegend_\"\n segment = prf2.data_structure[outlet_id][segment_id]\n profile_ids = segment[\"ids\"]\n color = segment[\"color\"]\n plt.plot(\n mg2.at_node[\"channel__chi_index\"][profile_ids],\n mg2.at_node[\"topographic__elevation\"][profile_ids],\n color=color,\n label=label,\n )\n\nplt.xlabel(\"chi index (m)\")\nplt.ylabel(\"elevation (m)\")\nplt.legend(loc=\"lower right\")\ntitle_text = (\n f\"$K_{{sp}}$={K_sp2}; $time$={total_time} yr; $dx$={dxy2} m; concavity={theta2}\"\n)\nplt.title(title_text)\n\n# chi map\nplt.figure(13)\nimshow_grid(\n mg2,\n \"channel__chi_index\",\n grid_units=(\"m\", \"m\"),\n var_name=\"Chi index (m)\",\n cmap=\"jet\",\n)\nplt.title(\n f\"$K_{{sp}}$={K_sp2}; $time$={total_time} yr; $dx$={dxy2} m; concavity={theta2}\"\n)\n\n# Code Block 21\n# Plot channel steepness along profiles and across the landscape\n\n# calculate channel steepness\nsf2.calculate_steepnesses()\n\n# plots of steepnes vs. distance upstream in the profiled channels\nplt.figure(14)\n\nfor i, outlet_id in enumerate(prf2.data_structure):\n for j, segment_id in enumerate(prf2.data_structure[outlet_id]):\n if j == 0:\n label = \"channel {i}\".format(i=i + 1)\n else:\n label = \"_nolegend_\"\n segment = prf2.data_structure[outlet_id][segment_id]\n profile_ids = segment[\"ids\"]\n distance_upstream = segment[\"distances\"]\n color = segment[\"color\"]\n plt.plot(\n distance_upstream,\n mg2.at_node[\"channel__steepness_index\"][profile_ids],\n \"x\",\n color=color,\n label=label,\n )\n\nplt.xlabel(\"distance upstream (m)\")\nplt.ylabel(\"steepness index\")\nplt.legend(loc=\"upper left\")\nplt.title(\n f\"$K_{{sp}}$={K_sp2}; $time$={total_time} yr; $dx$={dxy2} m; concavity={theta2}\"\n)\n\n# channel steepness map\nplt.figure(15)\nimshow_grid(\n mg2,\n \"channel__steepness_index\",\n grid_units=(\"m\", \"m\"),\n var_name=\"Steepness index \",\n cmap=\"jet\",\n)\nplt.title(\n f\"$K_{{sp}}$={K_sp2}; $time$={total_time} yr; $dx$={dxy2} m; concavity={theta2}\"\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" ]
fastai/fastai
nbs/21_vision.learner.ipynb
apache-2.0
[ "#|hide\n#|skip\n! [ -e /content ] && pip install -Uqq fastai # upgrade fastai on colab\n\n#|export \nfrom __future__ import annotations\nfrom fastai.basics import *\nfrom fastai.vision.core import *\nfrom fastai.vision.data import *\nfrom fastai.vision.augment import *\nfrom fastai.vision import models\n\ntry: import timm\nexcept ModuleNotFoundError: pass\n\n#|default_exp vision.learner\n\n#|hide\nfrom nbdev.showdoc import *", "Learner for the vision applications\n\nAll the functions necessary to build Learner suitable for transfer learning in computer vision\n\nThe most important functions of this module are vision_learner and unet_learner. They will help you define a Learner using a pretrained model. See the vision tutorial for examples of use.\nCut a pretrained model", "#|export\ndef _is_pool_type(l): return re.search(r'Pool[123]d$', l.__class__.__name__)\n\n#|hide\nm = nn.Sequential(nn.AdaptiveAvgPool2d(5), nn.Linear(2,3), nn.Conv2d(2,3,1), nn.MaxPool3d(5))\ntest_eq([bool(_is_pool_type(m_)) for m_ in m.children()], [True,False,False,True])", "By default, the fastai library cuts a pretrained model at the pooling layer. This function helps detecting it.", "#|export\ndef has_pool_type(m):\n \"Return `True` if `m` is a pooling layer or has one in its children\"\n if _is_pool_type(m): return True\n for l in m.children():\n if has_pool_type(l): return True\n return False\n\nm = nn.Sequential(nn.AdaptiveAvgPool2d(5), nn.Linear(2,3), nn.Conv2d(2,3,1), nn.MaxPool3d(5))\nassert has_pool_type(m)\ntest_eq([has_pool_type(m_) for m_ in m.children()], [True,False,False,True])\n\n#|export\ndef _get_first_layer(m):\n \"Access first layer of a model\"\n c,p,n = m,None,None # child, parent, name\n for n in next(m.named_parameters())[0].split('.')[:-1]:\n p,c=c,getattr(c,n)\n return c,p,n\n\n#|export\ndef _load_pretrained_weights(new_layer, previous_layer):\n \"Load pretrained weights based on number of input channels\"\n n_in = getattr(new_layer, 'in_channels')\n if n_in==1:\n # we take the sum\n new_layer.weight.data = previous_layer.weight.data.sum(dim=1, keepdim=True)\n elif n_in==2:\n # we take first 2 channels + 50%\n new_layer.weight.data = previous_layer.weight.data[:,:2] * 1.5\n else:\n # keep 3 channels weights and set others to null\n new_layer.weight.data[:,:3] = previous_layer.weight.data\n new_layer.weight.data[:,3:].zero_()\n\n#|export\ndef _update_first_layer(model, n_in, pretrained):\n \"Change first layer based on number of input channels\"\n if n_in == 3: return\n first_layer, parent, name = _get_first_layer(model)\n assert isinstance(first_layer, nn.Conv2d), f'Change of input channels only supported with Conv2d, found {first_layer.__class__.__name__}'\n assert getattr(first_layer, 'in_channels') == 3, f'Unexpected number of input channels, found {getattr(first_layer, \"in_channels\")} while expecting 3'\n params = {attr:getattr(first_layer, attr) for attr in 'out_channels kernel_size stride padding dilation groups padding_mode'.split()}\n params['bias'] = getattr(first_layer, 'bias') is not None\n params['in_channels'] = n_in\n new_layer = nn.Conv2d(**params)\n if pretrained:\n _load_pretrained_weights(new_layer, first_layer)\n setattr(parent, name, new_layer)\n\n#|export\ndef cut_model(model, cut):\n \"Cut an instantiated model\"\n if isinstance(cut, int): return nn.Sequential(*list(model.children())[:cut])\n elif callable(cut): return cut(model)\n raise NameError(\"cut must be either integer or a function\")\n\n#|export\ndef create_body(arch, n_in=3, pretrained=True, cut=None):\n \"Cut off the body of a typically pretrained `arch` as determined by `cut`\"\n model = arch(pretrained=pretrained)\n _update_first_layer(model, n_in, pretrained)\n if cut is None:\n ll = list(enumerate(model.children()))\n cut = next(i for i,o in reversed(ll) if has_pool_type(o))\n return cut_model(model, cut)", "cut can either be an integer, in which case we cut the model at the corresponding layer, or a function, in which case, this function returns cut(model). It defaults to the first layer that contains some pooling otherwise.", "tst = lambda pretrained : nn.Sequential(nn.Conv2d(3,5,3), nn.BatchNorm2d(5), nn.AvgPool2d(1), nn.Linear(3,4))\nm = create_body(tst)\ntest_eq(len(m), 2)\n\nm = create_body(tst, cut=3)\ntest_eq(len(m), 3)\n\nm = create_body(tst, cut=noop)\ntest_eq(len(m), 4)\n\nfor n in range(1,5): \n m = create_body(tst, n_in=n)\n test_eq(_get_first_layer(m)[0].in_channels, n)", "Head and model", "#|export\ndef create_head(nf, n_out, lin_ftrs=None, ps=0.5, pool=True, concat_pool=True, first_bn=True, bn_final=False,\n lin_first=False, y_range=None):\n \"Model head that takes `nf` features, runs through `lin_ftrs`, and out `n_out` classes.\"\n if pool and concat_pool: nf *= 2\n lin_ftrs = [nf, 512, n_out] if lin_ftrs is None else [nf] + lin_ftrs + [n_out]\n bns = [first_bn] + [True]*len(lin_ftrs[1:])\n ps = L(ps)\n if len(ps) == 1: ps = [ps[0]/2] * (len(lin_ftrs)-2) + ps\n actns = [nn.ReLU(inplace=True)] * (len(lin_ftrs)-2) + [None]\n layers = []\n if pool:\n pool = AdaptiveConcatPool2d() if concat_pool else nn.AdaptiveAvgPool2d(1)\n layers += [pool, Flatten()]\n if lin_first: layers.append(nn.Dropout(ps.pop(0)))\n for ni,no,bn,p,actn in zip(lin_ftrs[:-1], lin_ftrs[1:], bns, ps, actns):\n layers += LinBnDrop(ni, no, bn=bn, p=p, act=actn, lin_first=lin_first)\n if lin_first: layers.append(nn.Linear(lin_ftrs[-2], n_out))\n if bn_final: layers.append(nn.BatchNorm1d(lin_ftrs[-1], momentum=0.01))\n if y_range is not None: layers.append(SigmoidRange(*y_range))\n return nn.Sequential(*layers)", "The head begins with fastai's AdaptiveConcatPool2d if concat_pool=True otherwise, it uses traditional average pooling. Then it uses a Flatten layer before going on blocks of BatchNorm, Dropout and Linear layers (if lin_first=True, those are Linear, BatchNorm, Dropout).\nThose blocks start at nf, then every element of lin_ftrs (defaults to [512]) and end at n_out. ps is a list of probabilities used for the dropouts (if you only pass 1, it will use half the value then that value as many times as necessary).\nIf first_bn=True, a BatchNorm added just after the pooling operations. If bn_final=True, a final BatchNorm layer is added. If y_range is passed, the function adds a SigmoidRange to that range.", "tst = create_head(5, 10)\ntst\n\n#|hide\nmods = list(tst.children())\ntest_eq(len(mods), 9)\nassert isinstance(mods[2], nn.BatchNorm1d)\nassert isinstance(mods[-1], nn.Linear)\n\ntst = create_head(5, 10, lin_first=True)\nmods = list(tst.children())\ntest_eq(len(mods), 8)\nassert isinstance(mods[2], nn.Dropout)\n\ntst = create_head(5, 10, first_bn=False)\nmods = list(tst.children())\ntest_eq(len(mods), 8)\nassert isinstance(mods[2], nn.Dropout)\n\ntst = create_head(5, 10, concat_pool=True)\nmodes = list(tst.children())\ntest_eq(modes[4].in_features, 10)\n\ntst = create_head(5, 10, concat_pool=False)\nmodes = list(tst.children())\ntest_eq(modes[4].in_features, 5)\n\n#|export\nfrom fastai.callback.hook import num_features_model\n\n#TODO: refactor, i.e. something like this?\n# class ModelSplitter():\n# def __init__(self, idx): self.idx = idx\n# def split(self, m): return L(m[:self.idx], m[self.idx:]).map(params)\n# def __call__(self,): return {'cut':self.idx, 'split':self.split}\n\n#|export\ndef default_split(m):\n \"Default split of a model between body and head\"\n return L(m[0], m[1:]).map(params)", "To do transfer learning, you need to pass a splitter to Learner. This should be a function taking the model and returning a collection of parameter groups, e.g. a list of list of parameters.", "#|export\ndef _xresnet_split(m): return L(m[0][:3], m[0][3:], m[1:]).map(params)\ndef _resnet_split(m): return L(m[0][:6], m[0][6:], m[1:]).map(params)\ndef _squeezenet_split(m:nn.Module): return L(m[0][0][:5], m[0][0][5:], m[1:]).map(params)\ndef _densenet_split(m:nn.Module): return L(m[0][0][:7],m[0][0][7:], m[1:]).map(params)\ndef _vgg_split(m:nn.Module): return L(m[0][0][:22], m[0][0][22:], m[1:]).map(params)\ndef _alexnet_split(m:nn.Module): return L(m[0][0][:6], m[0][0][6:], m[1:]).map(params)\n\n_default_meta = {'cut':None, 'split':default_split}\n_xresnet_meta = {'cut':-4, 'split':_xresnet_split, 'stats':imagenet_stats}\n_resnet_meta = {'cut':-2, 'split':_resnet_split, 'stats':imagenet_stats}\n_squeezenet_meta = {'cut':-1, 'split': _squeezenet_split, 'stats':imagenet_stats}\n_densenet_meta = {'cut':-1, 'split':_densenet_split, 'stats':imagenet_stats}\n_vgg_meta = {'cut':-2, 'split':_vgg_split, 'stats':imagenet_stats}\n_alexnet_meta = {'cut':-2, 'split':_alexnet_split, 'stats':imagenet_stats}\n\n#|export\nmodel_meta = {\n models.xresnet.xresnet18 :{**_xresnet_meta}, models.xresnet.xresnet34: {**_xresnet_meta},\n models.xresnet.xresnet50 :{**_xresnet_meta}, models.xresnet.xresnet101:{**_xresnet_meta},\n models.xresnet.xresnet152:{**_xresnet_meta},\n\n models.resnet18 :{**_resnet_meta}, models.resnet34: {**_resnet_meta},\n models.resnet50 :{**_resnet_meta}, models.resnet101:{**_resnet_meta},\n models.resnet152:{**_resnet_meta},\n\n models.squeezenet1_0:{**_squeezenet_meta},\n models.squeezenet1_1:{**_squeezenet_meta},\n\n models.densenet121:{**_densenet_meta}, models.densenet169:{**_densenet_meta},\n models.densenet201:{**_densenet_meta}, models.densenet161:{**_densenet_meta},\n models.vgg11_bn:{**_vgg_meta}, models.vgg13_bn:{**_vgg_meta}, models.vgg16_bn:{**_vgg_meta}, models.vgg19_bn:{**_vgg_meta},\n models.alexnet:{**_alexnet_meta}}\n\n#|export\ndef add_head(body, nf, n_out, init=nn.init.kaiming_normal_, head=None, concat_pool=True, pool=True,\n lin_ftrs=None, ps=0.5, first_bn=True, bn_final=False, lin_first=False, y_range=None):\n \"Add a head to a vision body\"\n if head is None:\n head = create_head(nf, n_out, concat_pool=concat_pool, pool=pool,\n lin_ftrs=lin_ftrs, ps=ps, first_bn=first_bn, bn_final=bn_final, lin_first=lin_first, y_range=y_range)\n model = nn.Sequential(body, head)\n if init is not None: apply_init(model[1], init)\n return model\n\n#export\ndef create_vision_model(arch, n_out, pretrained=True, cut=None, n_in=3, init=nn.init.kaiming_normal_, custom_head=None,\n concat_pool=True, pool=True, lin_ftrs=None, ps=0.5, first_bn=True, bn_final=False, lin_first=False, y_range=None):\n \"Create custom vision architecture\"\n meta = model_meta.get(arch, _default_meta)\n body = create_body(arch, n_in, pretrained, ifnone(cut, meta['cut']))\n nf = num_features_model(nn.Sequential(*body.children())) if custom_head is None else None\n return add_head(body, nf, n_out, init=init, head=custom_head, concat_pool=concat_pool, pool=pool,\n lin_ftrs=lin_ftrs, ps=ps, first_bn=first_bn, bn_final=bn_final, lin_first=lin_first, y_range=y_range)\n\nshow_doc(create_vision_model)", "The model is cut according to cut and it may be pretrained, in which case, the proper set of weights is downloaded then loaded. init is applied to the head of the model, which is either created by create_head (with lin_ftrs, ps, concat_pool, bn_final, lin_first and y_range) or is custom_head.", "tst = create_vision_model(models.resnet18, 10, True)\ntst = create_vision_model(models.resnet18, 10, True, n_in=1)\n\n#export\nclass TimmBody(nn.Module):\n def __init__(self, arch:str, pretrained:bool=True, cut=None, n_in:int=3, **kwargs):\n super().__init__()\n model = timm.create_model(arch, pretrained=pretrained, num_classes=0, in_chans=n_in, **kwargs)\n self.needs_pool = model.default_cfg.get('pool_size', None)\n self.model = model if cut is None else cut_model(model, cut)\n \n def forward(self,x): return self.model.forward_features(x) if self.needs_pool else self.model(x)\n\n#export\ndef create_timm_model(arch:str, n_out, cut=None, pretrained=True, n_in=3, init=nn.init.kaiming_normal_, custom_head=None,\n concat_pool=True, pool=True, lin_ftrs=None, ps=0.5, first_bn=True, bn_final=False, lin_first=False, y_range=None, **kwargs):\n \"Create custom architecture using `arch`, `n_in` and `n_out` from the `timm` library\"\n body = TimmBody(arch, pretrained, None, n_in, **kwargs)\n nf = body.model.num_features\n return add_head(body, nf, n_out, init=init, head=custom_head, concat_pool=concat_pool, pool=body.needs_pool,\n lin_ftrs=lin_ftrs, ps=ps, first_bn=first_bn, bn_final=bn_final, lin_first=lin_first, y_range=y_range)", "Learner convenience functions", "#|export\ndef _add_norm(dls, meta, pretrained):\n if not pretrained: return\n stats = meta.get('stats')\n if stats is None: return\n if not dls.after_batch.fs.filter(risinstance(Normalize)):\n dls.add_tfms([Normalize.from_stats(*stats)],'after_batch')\n\n#|hide\npath = untar_data(URLs.PETS)\ndls = ImageDataLoaders.from_name_re(path, get_image_files(path/\"images\"), r'^(.*)_\\d+.jpg$', item_tfms=Resize(224))\nfor _ in range(5): _add_norm(dls, model_meta[models.resnet34], True)\ntest_eq(len(dls.after_batch.fs), 2)\n\n#|export\n@delegates(create_vision_model)\ndef vision_learner(dls, arch, normalize=True, n_out=None, pretrained=True, \n # learner args\n loss_func=None, opt_func=Adam, lr=defaults.lr, splitter=None, cbs=None, metrics=None, path=None,\n model_dir='models', wd=None, wd_bn_bias=False, train_bn=True, moms=(0.95,0.85,0.95),\n # model & head args\n cut=None, init=nn.init.kaiming_normal_, custom_head=None, concat_pool=True, pool=True,\n lin_ftrs=None, ps=0.5, first_bn=True, bn_final=False, lin_first=False, y_range=None, **kwargs):\n \"Build a vision learner from `dls` and `arch`\"\n if n_out is None: n_out = get_c(dls)\n assert n_out, \"`n_out` is not defined, and could not be inferred from data, set `dls.c` or pass `n_out`\"\n meta = model_meta.get(arch, _default_meta)\n model_args = dict(init=init, custom_head=custom_head, concat_pool=concat_pool, pool=pool, lin_ftrs=lin_ftrs, ps=ps,\n first_bn=first_bn, bn_final=bn_final, lin_first=lin_first, y_range=y_range, **kwargs)\n if normalize: _add_norm(dls, meta, pretrained)\n if isinstance(arch, str): model = create_timm_model(arch, n_out, default_split, pretrained, **model_args)\n else: model = create_vision_model(arch, n_out, pretrained=pretrained, **model_args)\n \n splitter=ifnone(splitter, meta['split'])\n learn = Learner(dls=dls, model=model, loss_func=loss_func, opt_func=opt_func, lr=lr, splitter=splitter, cbs=cbs,\n metrics=metrics, path=path, model_dir=model_dir, wd=wd, wd_bn_bias=wd_bn_bias, train_bn=train_bn, moms=moms)\n if pretrained: learn.freeze()\n # keep track of args for loggers\n store_attr('arch,normalize,n_out,pretrained', self=learn, **kwargs)\n return learn", "The model is built from arch using the number of final activations inferred from dls if possible (otherwise pass a value to n_out). It might be pretrained and the architecture is cut and split using the default metadata of the model architecture (this can be customized by passing a cut or a splitter). \nIf normalize and pretrained are True, this function adds a Normalization transform to the dls (if there is not already one) using the statistics of the pretrained model. That way, you won't ever forget to normalize your data in transfer learning.\nAll other arguments are passed to Learner.", "path = untar_data(URLs.PETS)\nfnames = get_image_files(path/\"images\")\npat = r'^(.*)_\\d+.jpg$'\ndls = ImageDataLoaders.from_name_re(path, fnames, pat, item_tfms=Resize(224))\n\nlearn = vision_learner(dls, models.resnet18, loss_func=CrossEntropyLossFlat(), ps=0.25)\n\n#|hide\nlearn = vision_learner(dls, models.resnet34, loss_func=CrossEntropyLossFlat(), ps=0.25, concat_pool=False)\ntest_ne(learn.cbs, None)\n\n#|hide\ntest_eq(to_cpu(dls.after_batch[1].mean[0].squeeze()), tensor(imagenet_stats[0]))\ntest_eq(to_cpu(dls.valid.after_batch[1].mean[0].squeeze()), tensor(imagenet_stats[0]))", "If you pass a str to arch, then a TIMM model will be created:", "learn = vision_learner(dls, 'vit_tiny_patch16_224', loss_func=CrossEntropyLossFlat(), ps=0.25)\n\n#|export\n@delegates(models.unet.DynamicUnet.__init__)\ndef create_unet_model(arch, n_out, img_size, pretrained=True, cut=None, n_in=3, **kwargs):\n \"Create custom unet architecture\"\n meta = model_meta.get(arch, _default_meta)\n body = create_body(arch, n_in, pretrained, ifnone(cut, meta['cut'])) \n model = models.unet.DynamicUnet(body, n_out, img_size, **kwargs)\n return model\n\nshow_doc(create_unet_model)\n\ntst = create_unet_model(models.resnet18, 10, (24,24), True, n_in=1)\n\n#|export\n@delegates(create_unet_model)\ndef unet_learner(dls, arch, normalize=True, n_out=None, pretrained=True, config=None,\n # learner args\n loss_func=None, opt_func=Adam, lr=defaults.lr, splitter=None, cbs=None, metrics=None, path=None,\n model_dir='models', wd=None, wd_bn_bias=False, train_bn=True, moms=(0.95,0.85,0.95), **kwargs): \n \"Build a unet learner from `dls` and `arch`\"\n \n if config:\n warnings.warn('config param is deprecated. Pass your args directly to unet_learner.')\n kwargs = {**config, **kwargs}\n \n meta = model_meta.get(arch, _default_meta)\n if normalize: _add_norm(dls, meta, pretrained)\n \n n_out = ifnone(n_out, get_c(dls))\n assert n_out, \"`n_out` is not defined, and could not be inferred from data, set `dls.c` or pass `n_out`\"\n img_size = dls.one_batch()[0].shape[-2:]\n assert img_size, \"image size could not be inferred from data\"\n model = create_unet_model(arch, n_out, img_size, pretrained=pretrained, **kwargs)\n\n splitter=ifnone(splitter, meta['split'])\n learn = Learner(dls=dls, model=model, loss_func=loss_func, opt_func=opt_func, lr=lr, splitter=splitter, cbs=cbs,\n metrics=metrics, path=path, model_dir=model_dir, wd=wd, wd_bn_bias=wd_bn_bias, train_bn=train_bn,\n moms=moms)\n if pretrained: learn.freeze()\n # keep track of args for loggers\n store_attr('arch,normalize,n_out,pretrained', self=learn, **kwargs)\n return learn", "The model is built from arch using the number of final filters inferred from dls if possible (otherwise pass a value to n_out). It might be pretrained and the architecture is cut and split using the default metadata of the model architecture (this can be customized by passing a cut or a splitter). \nIf normalize and pretrained are True, this function adds a Normalization transform to the dls (if there is not already one) using the statistics of the pretrained model. That way, you won't ever forget to normalize your data in transfer learning.\nAll other arguments are passed to Learner.", "path = untar_data(URLs.CAMVID_TINY)\nfnames = get_image_files(path/'images')\ndef label_func(x): return path/'labels'/f'{x.stem}_P{x.suffix}'\ncodes = np.loadtxt(path/'codes.txt', dtype=str)\n \ndls = SegmentationDataLoaders.from_label_func(path, fnames, label_func, codes=codes)\n\nlearn = unet_learner(dls, models.resnet34, loss_func=CrossEntropyLossFlat(axis=1), y_range=(0,1))\n\n#|hide\ntest_ne(learn.cbs, None)\n\n#export\ndef create_cnn_model(*args, **kwargs):\n \"Deprecated name for `create_vision_model` -- do not use\"\n warn(\"`create_cnn_model` has been renamed to `create_vision_model` -- please update your code\")\n return create_vision_model(*args, **kwargs)\n\n#export\ndef cnn_learner(*args, **kwargs):\n \"Deprecated name for `vision_learner` -- do not use\"\n warn(\"`cnn_learner` has been renamed to `vision_learner` -- please update your code\")\n return vision_learner(*args, **kwargs)", "Show functions -", "#|export\n@typedispatch\ndef show_results(x:TensorImage, y, samples, outs, ctxs=None, max_n=10, nrows=None, ncols=None, figsize=None, **kwargs):\n if ctxs is None: ctxs = get_grid(min(len(samples), max_n), nrows=nrows, ncols=ncols, figsize=figsize)\n ctxs = show_results[object](x, y, samples, outs, ctxs=ctxs, max_n=max_n, **kwargs)\n return ctxs\n\n#|export\n@typedispatch\ndef show_results(x:TensorImage, y:TensorCategory, samples, outs, ctxs=None, max_n=10, nrows=None, ncols=None, figsize=None, **kwargs):\n if ctxs is None: ctxs = get_grid(min(len(samples), max_n), nrows=nrows, ncols=ncols, figsize=figsize)\n for i in range(2):\n ctxs = [b.show(ctx=c, **kwargs) for b,c,_ in zip(samples.itemgot(i),ctxs,range(max_n))]\n ctxs = [r.show(ctx=c, color='green' if b==r else 'red', **kwargs)\n for b,r,c,_ in zip(samples.itemgot(1),outs.itemgot(0),ctxs,range(max_n))]\n return ctxs\n\n#|export\n@typedispatch\ndef show_results(x:TensorImage, y:(TensorMask, TensorPoint, TensorBBox), samples, outs, ctxs=None, max_n=6,\n nrows=None, ncols=1, figsize=None, **kwargs):\n if ctxs is None: ctxs = get_grid(min(len(samples), max_n), nrows=nrows, ncols=ncols, figsize=figsize, double=True,\n title='Target/Prediction')\n for i in range(2):\n ctxs[::2] = [b.show(ctx=c, **kwargs) for b,c,_ in zip(samples.itemgot(i),ctxs[::2],range(2*max_n))]\n for o in [samples,outs]:\n ctxs[1::2] = [b.show(ctx=c, **kwargs) for b,c,_ in zip(o.itemgot(0),ctxs[1::2],range(2*max_n))]\n return ctxs\n\n#|export\n@typedispatch\ndef show_results(x:TensorImage, y:TensorImage, samples, outs, ctxs=None, max_n=10, figsize=None, **kwargs):\n if ctxs is None: ctxs = get_grid(3*min(len(samples), max_n), ncols=3, figsize=figsize, title='Input/Target/Prediction')\n for i in range(2):\n ctxs[i::3] = [b.show(ctx=c, **kwargs) for b,c,_ in zip(samples.itemgot(i),ctxs[i::3],range(max_n))]\n ctxs[2::3] = [b.show(ctx=c, **kwargs) for b,c,_ in zip(outs.itemgot(0),ctxs[2::3],range(max_n))]\n return ctxs\n\n#|export\n@typedispatch\ndef plot_top_losses(x: TensorImage, y:TensorCategory, samples, outs, raws, losses, nrows=None, ncols=None, figsize=None, **kwargs):\n axs = get_grid(len(samples), nrows=nrows, ncols=ncols, figsize=figsize, title='Prediction/Actual/Loss/Probability')\n for ax,s,o,r,l in zip(axs, samples, outs, raws, losses):\n s[0].show(ctx=ax, **kwargs)\n ax.set_title(f'{o[0]}/{s[1]} / {l.item():.2f} / {r.max().item():.2f}')\n\n#|export\n@typedispatch\ndef plot_top_losses(x: TensorImage, y:TensorMultiCategory, samples, outs, raws, losses, nrows=None, ncols=None, figsize=None, **kwargs):\n axs = get_grid(len(samples), nrows=nrows, ncols=ncols, figsize=figsize)\n for i,(ax,s) in enumerate(zip(axs, samples)): s[0].show(ctx=ax, title=f'Image {i}', **kwargs)\n rows = get_empty_df(len(samples))\n outs = L(s[1:] + o + (TitledStr(r), TitledFloat(l.item())) for s,o,r,l in zip(samples, outs, raws, losses))\n for i,l in enumerate([\"target\", \"predicted\", \"probabilities\", \"loss\"]):\n rows = [b.show(ctx=r, label=l, **kwargs) for b,r in zip(outs.itemgot(i),rows)]\n display_df(pd.DataFrame(rows))\n\n#|export\n@typedispatch\ndef plot_top_losses(x:TensorImage, y:TensorMask, samples, outs, raws, losses, nrows=None, ncols=None, figsize=None, **kwargs):\n axes = get_grid(len(samples)*3, nrows=len(samples), ncols=3, figsize=figsize, flatten=False, title=\"Input | Target | Prediction\")\n if axes.ndim == 1: axes = (axes,)\n titles = [\"input\", \"target\", \"pred\"]\n for axs,s,o,l in zip(axes, samples, outs, losses):\n imgs = (s[0], s[1], o[0])\n for ax,im,title in zip(axs, imgs, titles):\n if title==\"pred\": title += f\"; loss = {l:.4f}\"\n im.show(ctx=ax, **kwargs)\n ax.set_title(title)", "Export -", "#|hide\nfrom nbdev.export import notebook2script\nnotebook2script()" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
matmodlab/matmodlab2
notebooks/UserMaterials.ipynb
bsd-3-clause
[ "User Defined Materials\nOverview\nMaterials are implemented by subclassing the matmodlab.core.Material base class. The user material is called at each frame of every step. It is provided with the material state at the start of the increment (stress, solution-dependent state variables, temperature, etc) and with the increments in temperature, deformation, and time.\nThe implementation of a material model will be demonstrated with a standard isotropic linear elastic model. \n<a name='contents'></a>\nContents\n\n<a href='#linelast'>Isotropic Linear Elasticity</a>\n<a href='#umat.std'>Model Implementation</a>\n<a href='#umat.compare'>Model Comparison</a>\n<a href='#conc'>Conclusion</a>\n\n<a name='linelast'></a>\nIsotropic Linear Elasticity\nThe mechanical response of a linear elastic material is defined by\n$$\n\\boldsymbol{\\sigma} = \\mathbb{C}{:}\\boldsymbol{\\epsilon} = 3K\\boldsymbol{\\epsilon}^{\\rm iso} + 2G\\boldsymbol{\\epsilon}^{\\rm dev}\n$$\nwhere $K$ is the bulk modulus and $G$ is the shear modulus. The strain $\\boldsymbol{\\epsilon}$ can be determined from the deformation gradient $\\pmb{F}$ as\n$$\n\\boldsymbol{\\epsilon} = \\frac{1}{2\\kappa}\\left[\\left(\\boldsymbol{F}^{\\rm T}{\\cdot}\\boldsymbol{F}\\right)^{2\\kappa} - \\boldsymbol{I}\\right]\n$$\nwhere $\\kappa$ is the generalized Seth-Hill strain parameter. Defined as such, several well known finite strain measures are emitted:\n\n$\\kappa=1$: Green-Lagrange reference strain\n$\\kappa=-1$: Alamansi spatial strain\n$\\kappa=0$: Logarithmic, or true, strain\n\nThe implementations of linear elasticity to follow will take as input Young's modulus E, Poisson's ratio Nu, and the Seth-Hill parameter k for changing the strain definition.\n<a name='umat.std'></a>\nModel Implementation\nThe easiest way to implement a material model is to subclass the matmodlab2.core.material.Material class and define:\n\nname: class attribute\n\nUsed for referencing the material model in the MaterialPointSimulator.\n\neval: instance method\n\nUpdates the material stress, stiffness (optional), and state dependent variables. If the stiffness is returned as None, Matmodlab will determine it numerically.\nOther optional attributes and methods include:\n\nnum_sdv: instance attribute\n\nThe number of state dependent variables. Default is None.\n\nsdv_names: instance attribute\n\nList of state dependent variable names. Default is SDV_N for the N$^{\\rm th}$ state dependent variable.\n\nsdvini: instance method [optional]\n\nInitializes solution dependent state variables (otherwise assumed to be 0).\nIn the example below, in addition to some standard functions imported from numpy, several helper functions are imported from various locations in Matmodlab:\n\n\nmatmodlab2.core.tensor\n\n\nlogm, powm: computes the matrix logarithm and power\n\narray_rep: converts a symmetric tensor stored as a 3x3 matrix to an array of length 6\npolar_decomp: computes the polar decomposition of the deformation gradient $\\pmb{F}$\nisotropic_part, deviatoric_part: computes the isotropic and deviatoric parts of a second-order symmetric tensor stored as an array of length 6\nVOIGT: mulitplier for converting tensor strain components to engineering strain components\n\nThe relevant input parameters to the material's eval method from Matmodlab are:\n\nF: the deformation gradient at the end of the step\n\nThe isotropic elastic material described above is implemented as ElasticMaterialTotal in the file matmodlab/materials/elastic3.py. The implementation can be viewed by executing the following cell.", "%pycat ../matmodlab2/materials/elastic3.py\n\n%pylab inline\nfrom matmodlab2 import *", "Verification Test\nExercising the elastic model through a path of uniaxial stress should result in the slope of axial stress vs. axial strain being equal to the input parameter E.\nNote: it is the responsibility of the model developer to define the material's instantiation. In the case of ElasticMaterialTotal, the interface takes the elastic parameters as keywords. Parameters not specified are initialized to a value of zero.", "mps1 = MaterialPointSimulator('uelastic-std')\nmps1.material = ElasticMaterialTotal(E=10e6, Nu=.333)\nmps1.run_step('ESS', (.1, 0, 0), frames=50)\ni = where(mps1.df['E.XX'] > 0.)\nE = mps1.df['S.XX'].iloc[i] / mps1.df['E.XX'].iloc[i]\nassert allclose(E, 10e6, atol=1e-3, rtol=1e-3)", "<a name='conc'></a>\nConclusion\nA method for defining user materials was outlined in this notebook." ]
[ "markdown", "code", "markdown", "code", "markdown" ]
BrentDorsey/pipeline
gpu.ml/notebooks/06a_Train_Model_XLA_GPU.ipynb
apache-2.0
[ "Train Model with XLA_GPU (and CPU*)\nSome operations do not have XLA_GPU equivalents, so we still need to use CPU.\nIMPORTANT: You Must STOP All Kernels and Terminal Session\nThe GPU is wedged at this point. We need to set it free!!", "import tensorflow as tf\nfrom tensorflow.python.client import timeline\nimport pylab\nimport numpy as np\nimport os\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\ntf.logging.set_verbosity(tf.logging.INFO)", "Reset TensorFlow Graph\nUseful in Jupyter Notebooks", "tf.reset_default_graph()", "Create TensorFlow Session", "config = tf.ConfigProto(\n log_device_placement=True,\n)\n\nconfig.gpu_options.allow_growth=True\nconfig.graph_options.optimizer_options.global_jit_level \\\n = tf.OptimizerOptions.ON_1\n\nprint(config)\n\nsess = tf.Session(config=config)\nprint(sess)", "Generate Model Version (current timestamp)", "from datetime import datetime \n\nversion = int(datetime.now().strftime(\"%s\"))", "Load Model Training and Test/Validation Data", "num_samples = 100000\n\nimport numpy as np\nimport pylab\n\nx_train = np.random.rand(num_samples).astype(np.float32)\nprint(x_train)\n\nnoise = np.random.normal(scale=0.01, size=len(x_train))\n\ny_train = x_train * 0.1 + 0.3 + noise\nprint(y_train)\n\npylab.plot(x_train, y_train, '.')\n\nx_test = np.random.rand(len(x_train)).astype(np.float32)\nprint(x_test)\n\nnoise = np.random.normal(scale=.01, size=len(x_train))\n\ny_test = x_test * 0.1 + 0.3 + noise\nprint(y_test)\n\npylab.plot(x_test, y_test, '.')\n\nwith tf.device(\"/cpu:0\"):\n W = tf.get_variable(shape=[], name='weights')\n print(W)\n\n b = tf.get_variable(shape=[], name='bias')\n print(b)\n\nwith tf.device(\"/device:XLA_GPU:0\"): \n x_observed = tf.placeholder(shape=[None], \n dtype=tf.float32, \n name='x_observed')\n print(x_observed)\n\n y_pred = W * x_observed + b\n print(y_pred)\n\nlearning_rate = 0.025\n\nwith tf.device(\"/device:XLA_GPU:0\"):\n y_observed = tf.placeholder(shape=[None], dtype=tf.float32, name='y_observed')\n print(y_observed)\n\n loss_op = tf.reduce_mean(tf.square(y_pred - y_observed))\n optimizer_op = tf.train.GradientDescentOptimizer(learning_rate)\n train_op = optimizer_op.minimize(loss_op) \n\n print(\"Loss Scalar: \", loss_op)\n print(\"Optimizer Op: \", optimizer_op)\n print(\"Train Op: \", train_op)", "Randomly Initialize Variables (Weights and Bias)\nThe goal is to learn more accurate Weights and Bias during training.", "with tf.device(\"/cpu:0\"):\n init_op = tf.global_variables_initializer()\n print(init_op)\n\nsess.run(init_op)\nprint(\"Initial random W: %f\" % sess.run(W))\nprint(\"Initial random b: %f\" % sess.run(b))", "View Accuracy of Pre-Training, Initial Random Variables\nWe want this to be close to 0, but it's relatively far away. This is why we train!", "def test(x, y):\n return sess.run(loss_op, feed_dict={x_observed: x, y_observed: y})\n\ntest(x_train, y_train)", "Setup Loss Summary Operations for Tensorboard", "loss_summary_scalar_op = tf.summary.scalar('loss', loss_op)\nloss_summary_merge_all_op = tf.summary.merge_all()\n\ntrain_summary_writer = tf.summary.FileWriter('/root/tensorboard/linear/xla_gpu/%s/train' % version, \n graph=tf.get_default_graph())\n\ntest_summary_writer = tf.summary.FileWriter('/root/tensorboard/linear/xla_gpu/%s/test' % version,\n graph=tf.get_default_graph())", "Train Model", "%%time\n\nfrom tensorflow.python.client import timeline\n\nwith tf.device(\"/device:XLA_GPU:0\"):\n run_metadata = tf.RunMetadata()\n max_steps = 401\n for step in range(max_steps):\n if (step < max_steps - 1):\n test_summary_log, _ = sess.run([loss_summary_merge_all_op, loss_op], feed_dict={x_observed: x_test, y_observed: y_test})\n train_summary_log, _ = sess.run([loss_summary_merge_all_op, train_op], feed_dict={x_observed: x_train, y_observed: y_train})\n else: \n test_summary_log, _ = sess.run([loss_summary_merge_all_op, loss_op], feed_dict={x_observed: x_test, y_observed: y_test})\n train_summary_log, _ = sess.run([loss_summary_merge_all_op, train_op], feed_dict={x_observed: x_train, y_observed: y_train}, \n options=tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE), \n run_metadata=run_metadata)\n\n trace = timeline.Timeline(step_stats=run_metadata.step_stats) \n with open('timeline-xla-gpu.json', 'w') as trace_file:\n trace_file.write(trace.generate_chrome_trace_format(show_memory=True))\n\n if step % 10 == 0:\n print(step, sess.run([W, b]))\n train_summary_writer.add_summary(train_summary_log, step)\n train_summary_writer.flush()\n test_summary_writer.add_summary(test_summary_log, step)\n test_summary_writer.flush()\n\npylab.plot(x_train, y_train, '.', label=\"target\")\npylab.plot(x_train, sess.run(y_pred, \n feed_dict={x_observed: x_train, \n y_observed: y_train}), \n \".\", \n label=\"predicted\")\npylab.legend()\npylab.ylim(0, 1.0)", "View Loss Summaries in Tensorboard\nNavigate to the Scalars and Graphs tab at this URL:\nhttp://[ip-address]:6006\nSave Graph For Optimization\nWe will use this later.", "import os\noptimize_me_parent_path = '/root/models/optimize_me/linear/xla_gpu'\n\nsaver = tf.train.Saver()\n\nos.system('rm -rf %s' % optimize_me_parent_path)\nos.makedirs(optimize_me_parent_path)\n\nunoptimized_model_graph_path = '%s/unoptimized_xla_gpu.pb' % optimize_me_parent_path\ntf.train.write_graph(sess.graph_def, \n '.', \n unoptimized_model_graph_path,\n as_text=False) \nprint(unoptimized_model_graph_path)\n\nmodel_checkpoint_path = '%s/model.ckpt' % optimize_me_parent_path\nsaver.save(sess, \n save_path=model_checkpoint_path)\nprint(model_checkpoint_path)\n\nprint(optimize_me_parent_path)\nos.listdir(optimize_me_parent_path)\n\nsess.close()", "Show Graph", "%%bash\n\nsummarize_graph --in_graph=/root/models/optimize_me/linear/xla_gpu/unoptimized_xla_gpu.pb\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport re\nfrom google.protobuf import text_format\nfrom tensorflow.core.framework import graph_pb2\n\ndef convert_graph_to_dot(input_graph, output_dot, is_input_graph_binary):\n graph = graph_pb2.GraphDef()\n with open(input_graph, \"rb\") as fh:\n if is_input_graph_binary:\n graph.ParseFromString(fh.read())\n else:\n text_format.Merge(fh.read(), graph)\n with open(output_dot, \"wt\") as fh:\n print(\"digraph graphname {\", file=fh)\n for node in graph.node:\n output_name = node.name\n print(\" \\\"\" + output_name + \"\\\" [label=\\\"\" + node.op + \"\\\"];\", file=fh)\n for input_full_name in node.input:\n parts = input_full_name.split(\":\")\n input_name = re.sub(r\"^\\^\", \"\", parts[0])\n print(\" \\\"\" + input_name + \"\\\" -> \\\"\" + output_name + \"\\\";\", file=fh)\n print(\"}\", file=fh)\n print(\"Created dot file '%s' for graph '%s'.\" % (output_dot, input_graph))\n \n\ninput_graph='/root/models/optimize_me/linear/xla_gpu/unoptimized_xla_gpu.pb'\noutput_dot='/root/notebooks/unoptimized_xla_gpu.dot'\nconvert_graph_to_dot(input_graph=input_graph, output_dot=output_dot, is_input_graph_binary=True)\n\n%%bash\n\ndot -T png /root/notebooks/unoptimized_xla_gpu.dot \\\n -o /root/notebooks/unoptimized_xla_gpu.png > /tmp/a.out\n\nfrom IPython.display import Image\n\nImage('/root/notebooks/unoptimized_xla_gpu.png', width=1024, height=768)", "XLA JIT Visualizations", "%%bash\n\ndot -T png /tmp/hlo_graph_1.*.dot -o /root/notebooks/hlo_graph_1.png &>/dev/null\ndot -T png /tmp/hlo_graph_10.*.dot -o /root/notebooks/hlo_graph_10.png &>/dev/null\ndot -T png /tmp/hlo_graph_50.*.dot -o /root/notebooks/hlo_graph_50.png &>/dev/null\ndot -T png /tmp/hlo_graph_75.*.dot -o /root/notebooks/hlo_graph_75.png &>/dev/null" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
DB2-Samples/db2jupyter
v1/Db2 11 Regular Expressions.ipynb
apache-2.0
[ "<a id='top'></a>\nDb2 11 Regular Expressions\nDb2 11.1 introduced extended support for regular\nexpressions. Regular expressions allow you to do very complex\npattern matching in character strings. Normal SQL LIKE\nsearches are limited to very specific patterns, but Regular\nexpression have a rich syntax that gives you much more\nflexibility in searching.\nSet up the connection to the database and Db2 command extensions.", "%run db2.ipynb", "Table of Contents\n\nSample Table Setup\nRegular Expression Commands\nRegular Expression Flags\nRegular Expression Search Patterns\nAnchoring Patterns in a Search\nMatching Patterns Across Lines\nLogical OR Operator\nCombining Patterns\nMatching Character Types\nSpecial Patterns\nNegating Patterns\nCapturing Parenthesis\nPerformance Considerations\n\nBack to Top\n<a id='sample'></a>\nSample Table Setup\nThe following SQL will create a new table in the SAMPLE\ndatabase (or whatever database you are currently connected\nto). This table represents all of the stations of the London\nUnderground Central line (existing stations only, not\nhistorical ones!). This table will be used for all of the\nexamples within this section.", "%%sql -q\nDROP TABLE CENTRAL_LINE;\n\nCREATE TABLE CENTRAL_LINE\n (\n STATION_NO INTEGER GENERATED ALWAYS AS IDENTITY,\n STATION VARCHAR(31),\n UPPER_STATION VARCHAR(31) GENERATED ALWAYS AS (UCASE(STATION))\n )\n;\n\nINSERT INTO CENTRAL_LINE(STATION)\n VALUES 'West Ruislip','Ruislip Gardens','South Ruislip','Northolt','Greenford',\n 'Perivale','Hanger Lane','Ealing Broadway','West Acton','North Acton',\n 'East Acton','White City','Shepherd''s Bush','Holland Park','Notting Hill Gate',\n 'Queensway','Lancaster Gate','Marble Arch','Bond Street','Oxford Circus',\n 'Tottenham Court Road','Holborn','Chancery Lane','St. Paul''s','Bank',\n 'Liverpool Street','Bethnal Green','Mile End','Stratford','Leyton',\n 'Leytonstone','Wanstead','Redbridge','Gants Hill','Newbury Park',\n 'Barkingside','Fairlop','Hainault','Grange Hill','Chigwell',\n 'Roding Valley','Snaresbrook','South Woodford','Woodford','Buckhurst Hill',\n 'Loughton','Debden','Theydon Bois','Epping'\n;", "Back to Top\n<a id='regular'></a>\nRegular Expression Commands\nThere are six regular expression functions within DB2\nincluding:\n\nREGEXP_COUNT - Returns a count of the number of times that a regular expression pattern is matched in a string.\nREGEXP_EXTRACT - Returns one occurrence of a substring of a string that matches the regular expression pattern.\nREGEXP_INSTR - Returns the starting or ending position of the matched substring, depending on the value of the return option argument.\nREGEXP_LIKE - Returns a Boolean value indicating if the regular expression pattern is found in a string. The function can be used only where a predicate is supported.\nREGEXP_MATCH_COUNT - Returns a count of the number of times that a regular expression pattern is matched in a string.\nREGEXP_REPLACE - Returns a modified version of the source string where occurrences of the regular expression pattern found in the source string are replaced with the specified replacement string.\nREGEXP_SUBSTR - Returns one occurrence of a substring of a string that matches the regular expression pattern.\n\nEach one of these functions follows a similar calling\nsequence:\n<pre> \n REGEXP_FUNCTION(source, pattern, flags, start_pos, codeunits)\n</pre>\n\nThe arguments to the function are:\n\nSource - string to be searched\nPattern - the regular expression that contains what we are searching for\nFlag - settings that control how matching is done\nStart_pos - where to start in the string\nCodeunits - which type unit of measurement start_pos refers to (for Unicode)\n\nThe source can be any valid Db2 string including CHAR,\nVARCHAR, CLOB, etc. Start_pos is the location in the source\nstring that you want to start searching from, and codeunits\ntells Db2 whether to treat the start_pos as an absolute\nlocation (think byte location) or a character location which\ntakes into account the unicode size of the character string.\nCodeunits can be specified as CODEUNITS16, CODEUNITS32, or\nOCTETS. CODEUNITS16 specifies that start is expressed in\n16-bit UTF-16 code units. CODEUNITS32 specifies that start\nis expressed in 32-bit UTF-32 code units. OCTETS specifies\nthat start is expressed in bytes.\nPattern and flag values are complex and so are discussed in\nthe following sections.\nBack to Top\n<a id='flags'></a>\nRegular Express Flag Values\nRegular expression functions have a flag specification that\ncan be used to change the behavior of the search. There are\nsix possible flags that can be specified as part of the\nREGEXP command:\n|Flag |Purpose\n|:----:|:--------------------\n|c | Specifies that matching is case-sensitive (the default value)\n|i | Specifies that matching is case insensitive\n|m | Specifies that the input data can contain more than one line. By default, the '^' in a pattern matches only the start of the input string; the '\\$' in a pattern matches only the end of the input string. If this flag is set, \"^\" and \"\\$\" also matches at the start and end of each line within the input string.\n|n | Specifies that the '.' character in a pattern matches a line terminator in the input string. By default, the '.' character in a pattern does not match a line terminator. A carriage-return and line-feed pair in the input string behaves as a single-line terminator, and matches a single \".\" in a pattern.\n|s | Specifies that the '.' character in a pattern matches a line terminator in the input string. This value is a synonym for the 'n' value.\n|x | Specifies that white space characters in a pattern are ignored, unless escaped.\nBack to Top\n<a id='patterns'></a>\nRegular Expression Search Patterns\nRegular expressions use certain characters to represent what\nis matched in a string. The simplest pattern is a string by\nitself.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'Ruislip')", "The pattern 'Ruislip' will look for a match of Ruislip\nwithin the STATION column. Note that this pattern will also\nmatch 'West Ruislip' or 'Ruislip Gardens' since we placed no\nrestriction on where the pattern can be found in the string.\nThe match will also be exact (case matters). This type of\nsearch would be equivalent to using the SQL LIKE statement:", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE STATION LIKE '%Ruislip%'", "If you didn't place the % at the beginning of the LIKE\nstring, only the stations that start with Ruislip would be\nfound.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE STATION LIKE 'Ruislip%'", "If you want to match Ruislip with upper or lower case being\nignored, you would add the 'i' flag as part of the\nREGEXP_LIKE (or any REGEXP function).", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'RUISLIP','i')", "Back to Top\n<a id='anchor'></a>\nAnchoring Patterns in a Search\nBy default a pattern will be matched anywhere in a string.\nOur previous example showed how Ruislip could be found\nanywhere in a string. To force a match to start at the\nbeginning of a string, the carat symbol ^ can be used to\nforce the match to occur at the beginning of a string.", "%%sql\n SELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'^Ruislip')", "To match a pattern at the end of the string, the dollar sign\n\\$ can be used.", "%%sql\n SELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'Ruislip$')", "To force an exact match with a string you would use both the\nbeginning and end anchors.", "%%sql \n SELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'^Leyton$')", "Note that if we didn't use the end anchor, we are going to\nget more than one result.", "%%sql \n SELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'^Leyton');", "Back to Top\n<a id='multiple'></a>\nMatching patterns across multiple lines\nSo far the examples have dealt with strings that do not\ncontain newline characters (or carriage feeds). In some\napplications, data from an input panel may include multiple\nlines which may contain hard line feeds. What this means is\nthat there are actually multiple lines in the data, but from\na database perspective, there is only one line in the\nVARCHAR field. You can modify the behavior of the Regular\nExpression search by instructing it to honor the CRLF\ncharacters as line delimiters.\nThe following SQL will insert a single line with multiple\nCRLF characters in it to simulate a multi-line text string.", "%%sql -q\nDROP TABLE LONGLINE;\n\nCREATE TABLE LONGLINE (NAME VARCHAR(255));\n\nINSERT INTO LONGLINE\n VALUES 'George' || CHR(10) || 'Katrina';", "Searching for Katrina at the beginning and end of string\ndoesn't work.", "%%sql\nSELECT COUNT(*) FROM LONGLINE\n WHERE REGEXP_LIKE(NAME,'^Katrina$')", "We can override the regular expression search by telling it\nto treat each NL/CRLF as the end of a string within a\nstring.", "%%sql\nSELECT COUNT(*) FROM LONGLINE\n WHERE REGEXP_LIKE(NAME,'^Katrina$','m')", "Back to Top\n<a id='or'></a>\nLogical OR Operator\nRegular expressions can match more than one pattern. The OR\noperator (|) is used to define alternative patterns that can\nmatch in a string. The following example searches for\nstations that have \"ing\" in their name as well as \"hill\".", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'way|ing')", "Some things to be aware of when creating the search pattern.\nSpaces in the patterns themselves are significant. If the\nprevious search pattern had a space in one of the words, it\nwould not find it (unless of course there was a space in the\nstation name).", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'way| ing') ", "Using the \"x\" flag will ignore blanks in your pattern, so\nthis would fix issues that we have in the previous example.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'way| ing','x')", "Brackets can be used to make it clear what the pattern is\nthat you are searching for and avoid the problem of having\nblanks in the expression. Brackets do have a specific usage\nin regular expressions, but here we are using it only to\nseparate the two search strings.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'(way)|(ing)')", "Back to Top\n<a id='combine'></a>\nCombining Patterns\nAs we found out in the previous section, there is an OR\noperator that you can use to select between two patterns.\nHow do you request that multiple patterns be present? First\nwe must understand how matching occurs when we have multiple\nstrings that need to be matched that have an unknown number\nof characters between them.\nFor instance, how do we create a pattern that looks for\n\"ing\" followed by \"way\" somewhere in the string? Regular\nexpression recognize the \".\" (period) character as matching\nanything. Following the pattern you can add a modifier that\nspecifies how many times you want the pattern matched:\n\n* - Match zero or more times\n? - Match zero or one times\n+ - Match one or more times\n{m} - Match exactly m times\n{m,} - Match as least a minimum of m times\n{m,n} - Match at least a minimum of m times and no more than n times\n\nThe following regular expression searches for a pattern with\n\"ing\" followed by any characters and then \"way\".", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'(ing)*.(way)')", "The previous answer gave you two results (Ealing Broadway\nand Queensway). Why two? The reason is that we used the * in\nthe wrong place (a single character in a wrong place can\nresult in very different results!). What we really needed to\ndo was place a .* after the (ing) to match \"ing\" and then\nany characters, before matching \"way\". What our query did\nabove was match 0 or more occurences of \"ing\", followed by\nany character, and then match \"way\". Here is the correct\nquery.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'(ing).*(way)')", "Finding at least one occurrence of a pattern requires the\nuse of the + operator, or the bracket operators. This\nexample locates at least one occurrence of the \"an\" string\nin station names.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'(an)+') ", "If we want to find an exact number of occurrences, we need\nto use the {} notation to tell the regular expression\nmatcher how many we want to find. The syntax of the {}\nmatch is:\n\n{m} - Match exactly m times\n{m,} - Match as least a minimum of m times\n{m,n} - Match at least a minimum of m times and no more than n times\n\nSo the \"+\" symbol is equivalent to the following regular\nexpression using the {} syntax.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'(an){1,}')", "If we want to match exactly 2 'an' patterns in a string, we\nwould think that changing the expression to {2} would work.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'(an){2}')", "Sadly, we get no results! This would appear to be the wrong\nresult, but it's because we got lucky with our first search!\nThe best way to figure out what we matched in the original\nquery is to use the REGEXP_EXTRACT and REGEXP_INSTR\nfunctions.\n\nREGEXP_EXTRACT - Returns one occurrence of a substring of a string that matches the regular expression pattern.\nREGEXP_INSTR - Returns the starting or ending position of the matched substring, depending on the value of the return option argument.\n\nThe following SQL gives us a clue to what was found with the\n(an) pattern.", "%%sql\nSELECT STATION,\n REGEXP_INSTR(STATION,'(an)') AS LOCATION,\n REGEXP_EXTRACT(STATION,'(an)') AS EXTRACT\nFROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'(an)')", "What you should see in the previous result is the location\nwhere the \"an\" pattern was found in the string. Note that\nall we matched was the \"an\" pattern, nothing else. So why\ncan't I find two \"an\" patterns in the string? The reason is\nthat (an){2} means \"an\" followed by another \"an\"! We didn't\ntell the pattern to match anything else! What we need to do\nis modify the pattern to say that it can match \"an\" followed\nby anything else. The pattern needs to be modifed to (an).\nwhere the \".\" means any character following the \"an\".\nIn order to tell the regular expression function to use this\nentire pattern (an).* twice, we need to place brackets\naround it as well. The final pattern is ((an).*){2}.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'((an).*){2}')", "You should find that two stations match the pattern. The\nfollowing SQL shows which pattern is matched first in the\nSTATIONS names.", "%%sql\nSELECT STATION,\n REGEXP_INSTR(STATION,'((an).*){2}') AS LOCATION,\n REGEXP_EXTRACT(STATION,'((an).*){2}') AS EXTRACT\nFROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'((an).*){2}')", "Back to Top\n<a id='chars'></a>\nMatching character types\nAside from matching entire strings, you can also use regular\nexpression to look for patterns of characters. The simplest\nmatching pattern is the period (.) which matches any\ncharacter. Matching a string of arbitrary length is the\npattern \".*\". The \"+\" and \"?\" characters can also be used to\nmodify how many characters you want matched.\nWhat about situations where you want to check for certain\npatterns or characters in a string? A good example would be\na social security number, or credit card number. There are\ncertain patterns that you would find for these objects.\nAssume we have a social security number in the format\nxxx-xx-xxxx. It is possible to create a regular expression\nthat would return true if the SSN matched the pattern above\n(it doesn't tell you if the SSN itself is valid, only that\nit has the proper format).\nRegular expressions allow you to create a list of characters\nthat need to be matched in something called a bracket\nexpression. A bracket expression has the format:\n<pre> \n[a-z] [A-Z] [0-9] [a-zA-z]\n</pre>\n\nThe examples above represent the following search patterns:\n\n[a-z] - match any series of lowercase characters between a and z\n[A-Z] - match any series of uppercase characters between A and Z\n[0-9] - match any valid digits\n[a-zA-Z] - match any lower- or uppercase letters\n\nYou can also enumerate all of the characters you want to\nmatch by listing them between the brackets like\n[abcdefghikjlmnopqrstuvwxyz]. The short form a-z is easier\nto read and less prone to typing errors!\nThe following example checks for station names that start\nwith the letter P-R.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'^[P-R]')", "If you wanted to include all stations that have the letter\nP-R or p-e, you could add the condition within the brackets.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'[p-rP-R]')", "Back to our SSN question. Can a regular expression pattern\nbe used to determine whether or not the string is in the\ncorrect format? The data will be in the format XXX-XX-XXXX\nso the regular expression needs to find the three numeric\nvalues separated by dashes.\nThe number pattern can be represented with the bracket\nexpression [0-9]. To specify the number of characters that\nneed to be found, we use the braces {} to specify the exact\nnumber required.\nFor the three numbers in the pattern we can use [0-9]{3},\n[0-9]{2}, and [0-9]{4}. Adding in the dashes gives us the\nfinal pattern. The SQL below checks to see if a SSN is\ncorrect.", "%%sql\nVALUES\n CASE \n WHEN REGEXP_LIKE('123-34-1422','[0-9]{3}-[0-9]{2}-[0-9]{4}') THEN 'Valid'\n ELSE 'Invalid'\n END", "The SSN is valid in the example above. Here are some other\nexamples to show whether or not the regular expression picks\nup all of the errors.", "%%sql\nWITH SSNS(SSN) AS (\n VALUES \n '123-34-1322',\n 'ABC-34-9999',\n 'X123-44-0001',\n '123X-Y44-Z0001',\n '111-222-111'\n )\nSELECT SSN,\n CASE \n WHEN REGEXP_LIKE(SSN,'[0-9]{3}-[0-9]{2}-[0-9]{4}') THEN 'Valid'\n ELSE 'Invalid'\n END\nFROM SSNS", "If you check closely, one of the strings was marked as\nvalid, although it is not correct (X123-44-0001). The reason\nthis occurred is that the pattern was found after the \"X\"\nand it was correct. To prevent this from happening, we need\nto anchor the pattern at the beginning to avoid this\nsituation. A better pattern would be to anchor both ends of\nthe pattern so there is no possibility of other characters\nbeing at the beginning or end of the pattern.", "%%sql\nWITH SSNS(SSN) AS (\n VALUES \n '123-34-1322',\n 'ABC-34-9999',\n 'X123-44-0001',\n '123X-Y44-Z0001',\n '111-222-111'\n )\nSELECT SSN,\n CASE \n WHEN REGEXP_LIKE(SSN,'^[0-9]{3}-[0-9]{2}-[0-9]{4}$') THEN 'Valid'\n ELSE 'Invalid'\n END\nFROM SSNS", "Back to Top\n<a id='special'></a>\nSpecial Patterns\nThe previous example used the [0-9] syntax to request that\nonly numbers be found in the pattern. There are some\npredefined patterns that define these common patterns. The\nfirst argument is Posix format (if it exists), the second is\nthe escape character equivalent, and the final one is the\nraw pattern it represents.\n|Posix | Escape | Pattern | Meaning\n|:----------| :--------| :---------------|:------------------------\n|[:alnum:] | | [A-Za-z0-9] | Alphanumeric characters\n| | \\w | [A-Za-z0-9_] | Alphanumeric characters plus \"_\"\n| | \\W | [^A-Za-z0-9_] | Non-word characters\n|[:alpha:] | \\a | [A-Za-z] | Alphabetic characters\n|[:blank:] | \\s, \\t | | Space and tab\n| | \\b | | Word boundaries\n|[:cntrl:] | | [\\x00-\\x1F\\x7F] | Control characters\n|[:digit:] | \\d | [0-9] | Digits\n| | \\D | [^0-9] | Non-digits\n|[:graph:] | | [\\x21-\\x7E] | Visible characters\n|[:lower:] | \\l | [a-z] | Lowercase letters\n|[:print:] | \\p | [\\x20-\\x7E] | Visible characters and the space character\n|[:punct:] | | [][!\"#\\$%&'()*+,./:;<=>?@\\^_`{<code>&#124;</code>}~-] | Punctuation characters\n|[:space:] | \\s | [ \\t\\r\\n\\v\\f] | Whitespace characters\n| | \\S | [^ \\t\\r\\n\\v\\f] | Non-whitespace characters\n|[:upper:] | \\u | [A-Z] | Uppercase letters\n|[:xdigit:] | \\x | [A-Fa-f0-9] | Hexadecimal digits\nFor instance, the following three statements will produce\nthe same result.", "%%sql\nWITH SSNS(SSN) AS (\n VALUES \n '123-34-1322',\n 'ABC-34-9999',\n 'X123-44-0001',\n '123X-Y44-Z0001',\n '111-222-111'\n )\nSELECT 'Original', SSN,\n CASE \n WHEN REGEXP_LIKE(SSN,'^[0-9]{3}-[0-9]{2}-[0-9]{4}$') THEN 'Valid'\n ELSE 'Invalid'\n END\nFROM SSNS\nUNION ALL\nSELECT 'Posix', SSN,\n CASE \n WHEN REGEXP_LIKE(SSN,'^[:digit:]{3}-[:digit:]{2}-[:digit:]{4}$') THEN 'Valid'\n ELSE 'Invalid'\n END\nFROM SSNS\nUNION ALL\nSELECT 'Escape', SSN,\n CASE \n WHEN REGEXP_LIKE(SSN,'^\\d{3}-\\d{2}-\\d{4}$') THEN 'Valid'\n ELSE 'Invalid'\n END\nFROM SSNS", "Back to Top\n<a id='negate'></a>\nNegating Patterns\nUp to this point in time, the patterns that have been used\nare looking for a positive match. In some cases you may want\nto find values that do not match. The easiest way is to\nnegate the actual REGEXP_LIKE expression. The following\nexpression finds all of the stations that start with \"West\".", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'^West')", "Adding the NOT modifier in front of the REGEXP function\ngives us the stations that do not begin with West.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE NOT REGEXP_LIKE(STATION,'^West') ", "You can also negate some of the searches in a pattern by\nusing the [^...] syntax where the ^ tells the regular\nexpression not to match the following characters. The\nexpression [^0-9] would mean match any characters which are\nnot numeric.\nHowever, regular expressions have something called negative\nlookarounds which basically mean find the pattern which does\nnot match. You create this pattern by adding the (?!..) at\nthe beginning of the string. The same query (finding\nstations that don't start with West) would be written with\nthis lookaround logic found in the SQL below.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'^(?!West)')", "Back to Top\n<a id='capture'></a>\nCapturing Parenthesis\nThe previous example used something called a negative\nlookaround with capturing parenthesis. When you place a\npattern within a set of brackets (...) the string that\nmatches this pattern is \"remembered\". The strings that are\nmatched can be used in subsequent parts of your regular\nexpression. This allows a form of programming within your\nregular expression!\nEach set of parentheses that are matched are associated with\na number, starting at one and incrementing for each\nsubsequent pattern match. For instance, the following\npattern will have three matches:\n<pre>\n^([0-9]{3})-([0-9]{3})-([0-9]{3})$\n</pre>\nThis is similar to the SSN example used earlier on in this\nsection. The difference in this example is that each block\nof numbers is exactly the same (3 digits). This pattern will\nmatch any sequence of numbers in the format 123-456-789.", "%%sql\nWITH SSNS(SSN) AS (\n VALUES \n '123-456-789',\n '123-555-123',\n '890-533-098',\n '123-456-456'\n )\nSELECT SSN,\n CASE \n WHEN REGEXP_LIKE(SSN,'^([0-9]{3})-([0-9]{3})-([0-9]{3})$') THEN 'Valid'\n ELSE 'Invalid'\n END\nFROM SSNS", "All of these numbers fit the pattern and should be valid.\nWhen one of the capturing parenthesis matches, it will\nremember the string that it matched. For instance, in the\nfirst example (123-456-789), the first match will find the\nstring '123'. The second match will find '456' and so on. We\ncan refer to these matched strings with the special control\ncharacters \\n where n represents the capturing parenthesis\nlocation. So \\1 would refer to the '123' that was found. \\2\nwould be for '456'.\nThe regular expression will be updated so that the last part\nof the pattern needs to be numeric (0-9) but can't be same\nas the first match.", "%%sql\nWITH SSNS(SSN) AS (\n VALUES \n '123-456-789',\n '123-555-123',\n '890-533-098',\n '123-456-456'\n )\nSELECT SSN,\n CASE \n WHEN REGEXP_LIKE(SSN,'^([0-9]{3})-([0-9]{3})-(?!\\1)([0-9]{3})$') THEN 'Valid'\n ELSE 'Invalid'\n END\nFROM SSNS", "In many cases it may be easier to find the patterns that\nmatch and then negate the REGEXP statement! The (?...)\nsyntax is used for a variety of purposes in regular\nexpressions:\n| Pattern | Result\n|:----------| :-----------\n| (?: ... ) | Non-capturing parentheses. Groups the included pattern, but does not provide capturing of matching text. More efficient than capturing parentheses.\n| (?> ... ) | Atomic-match parentheses. First match of the parenthesized subexpression is the only one tried. If it does not lead to an overall pattern match, back up the search for a match to a position before the \"(?>\"\n| (?# ... ) | Free-format comment (?# comment )\n| (?= ... ) | Look-ahead assertion. True if the parenthesized pattern matches at the current input position, but does not advance the input position.\n| (?! ... ) | Negative look-ahead assertion. True if the parenthesized pattern does not match at the current input position. Does not advance the input position.\n| (?<= ... )| Look-behind assertion. True if the parenthesized pattern matches text that precedes the current input position. The last character of the match is the input character just before the current position. Does not alter the input position. The length of possible strings that is matched by the look-behind pattern must not be unbounded (no * or + operators.)\n| (?<!... ) | Negative Look-behind assertion. True if the parenthesized pattern does not match text that precedes preceding the current input position. The last character of the match is the input character just before the current position. Does not alter the input position. The length of possible strings that is matched by the look-behind pattern must not be unbounded (no * or + operators.)\nFor efficiency in matching, the best approach is to place\nstrings that you are searching for in non-capturing\nparentheses (?:...) rather than the generic () parenthesis.\nThe following example finds all stations with \"West\" in the\nname.", "%%sql \nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'(West)')", "The following SQL is equivalent, except that the matched\npattern is not kept for future use in matching.", "%%sql\nSELECT STATION FROM CENTRAL_LINE\n WHERE REGEXP_LIKE(STATION,'(?:West)')", "Back to Top\n<a id='performance'></a>\nPerformance Considerations of Regular Expressions\nWe know that there are better ways to write Regular\nExpressions (like the use of non-capturing parenthesis. How\nmuch of a difference does this make? In order to find out,\nthe following SQL will take the existing table and insert\ninto a temporary table 1000 times (for close to 50000\nrecords). \nThis SQL will generate the new table and fill it with the\nbase CENTRAL_LINE data.", "%%sql -d -q\nDROP TABLE TEMP_LINE\n@\n\nCREATE TABLE TEMP_LINE AS (SELECT * FROM CENTRAL_LINE) DEFINITION ONLY NOT LOGGED INITIALLY\n@\n \nBEGIN\n DECLARE I INTEGER DEFAULT 0; \n WHILE I <= 1000 DO\n INSERT INTO TEMP_LINE SELECT * FROM CENTRAL_LINE;\n SET I = I + 1;\n END WHILE;\nEND\n@\n\nSELECT COUNT(*) FROM TEMP_LINE\n@", "We will run four queries in the following SQL.\n\nSearch for West using the LIKE statement \nSearch for West using a regular expression with no matching () \nSearch for West using a regular expression with matching ()\nSearch for West using a regular expression with non-capturing parenthesis (?:)\n\nThe queries are run as many times as possible per second to get consistent results. Odds are that there will be variations in the results on your system!", "results_like = %sql -t SELECT COUNT(*) FROM TEMP_LINE WHERE STATION LIKE '%West%'\nresults_string = %sql -t SELECT COUNT(*) FROM TEMP_LINE WHERE REGEXP_LIKE(STATION,'West')\nresults_capturing = %sql -t SELECT COUNT(*) FROM TEMP_LINE WHERE REGEXP_LIKE(STATION,'(West)')\nresults_noncapturing = %sql -t SELECT COUNT(*) FROM TEMP_LINE WHERE REGEXP_LIKE(STATION,'(?:West)')", "The results are placed into a temporary table for easier formatting.", "%sql -q DROP TABLE RESULTS\n%sql CREATE TABLE RESULTS(TYPE VARCHAR(16), RESULT DEC(9,2))\n%sql INSERT INTO RESULTS VALUES ('LIKE', {results_like} ), \\\n ('REGX STRING', {results_string} ), \\\n ('REGX CAPTURE', {results_capturing} ), \\\n ('REGX NONCAPTURE', {results_noncapturing} )\n%sql SELECT * FROM RESULTS", "The results are clearer when we plot them all on one graph!", "%sql -pb SELECT * FROM RESULTS", "Every system will have different performance\ncharacteristics, but the odds are that the LIKE statement\nwas faster than the regular expression. The performance is\nprobably ranked this way (with tx/sec being the measurement):\n<pre>\nLIKE > REGEXP(Non-capturing) > REGEXP(Capturing) > REGEXP(String) \n</pre>\n\nHowever, your system will probably get different results. So\nwhile Regular expressions are very powerful, there is a\nperformance penalty when using them. In addition, you may\nneed to consider the use of indexes from a performance\nperspective.\nThe following SQL will add an index to the STATION name.", "%%sql -q\nDROP INDEX TEMP_STATION_INDEX;\nCREATE INDEX TEMP_STATION_INDEX ON TEMP_LINE(STATION);", "We will try the 4 queries again and plot the result.", "results_like = %sql -t SELECT COUNT(*) FROM TEMP_LINE WHERE STATION LIKE '%West%'\nresults_string = %sql -t SELECT COUNT(*) FROM TEMP_LINE WHERE REGEXP_LIKE(STATION,'West')\nresults_capturing = %sql -t SELECT COUNT(*) FROM TEMP_LINE WHERE REGEXP_LIKE(STATION,'(West)')\nresults_noncapturing = %sql -t SELECT COUNT(*) FROM TEMP_LINE WHERE REGEXP_LIKE(STATION,'(?:West)')\n%sql -q DROP TABLE RESULTS\n%sql -q CREATE TABLE RESULTS(TYPE VARCHAR(16), RESULT DEC(9,2))\n%sql -q INSERT INTO RESULTS VALUES ('LIKE', {results_like} ), \\\n ('REGX STRING', {results_string} ), \\\n ('REGX CAPTURE', {results_capturing} ), \\\n ('REGX NONCAPTURE', {results_noncapturing} )\n%sql SELECT * FROM RESULTS\n%sql -pb SELECT * FROM RESULTS", "The index can help speed up processing of the LIKE statement and the regular expression calls. The results may or may not favor LIKE over regular expressions. In summary, if you are going to use regular expressions, you may get a performance advantage by using indexes if possible.\nBack to Top\nCredits: IBM 2018, George Baklarz [baklarz@ca.ibm.com]" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
machlearn/ipython-notebooks
training-machine-learning-model.ipynb
mit
[ "https://www.youtube.com/watch?v=RlQuVL6-qe8&index=4&list=PL5-da3qGB5ICeMbQuqbbCOQWcS6OYBr5A\nReviewing the iris dataset\nK-nearest neighbors (KNN) classification\n\nPick a value for K \nSearch for K observations in the training data that are \"nearest\" to the measurements of the unknown Iris. \nuse the most popular response value from the K nearest neighbors as the predicted response value for the unknown Iris.", "# import load_iris function from datasets module \nfrom sklearn.datasets import load_iris\n\niris = load_iris()\nX = iris.data\ny = iris.target\nprint X.shape\nprint y.shape", "skikit-learn 4-step modeling pattern\n\nStep1: import the class you plan to use", "from sklearn.neighbors import KNeighborsClassifier ", "Step 2: \"Instantiate\" the \"estimator\"\n\"Estimator\" is scikit-learn's term for model \n\"Instantiate\" means \"makes an instance of\"", "knn = KNeighborsClassifier(n_neighbors=1)", "+ Name of the object does not matter\n+ Can specify tuning parameters during this step\n+ All parameters not specified are set to defaults.", "print knn", "Step 3: Fit the model with data (\"model training\")\nModel is learning the relationship between X and y\nOccurs in-place", "knn.fit(X,y)", "Step 4: predict the response for a new observation\nNew observations are called \"out-of-sample\" data \nUses the information it learned during the model training shape", "knn.predict([3,5,4,2])\n\nX_new = [[3,5,4,2], [5,4,3,2]]\nknn.predict(X_new)\n", "Using a different value for K", "knn = KNeighborsClassifier(n_neighbors=5)\n\nknn.fit(X,y)\nknn.predict(X_new)", "Using a different classification model", "from sklearn.linear_model import LogisticRegression\n\nlogreg = LogisticRegression()\n\nlogreg.fit(X,y)\n\nlogreg.predict(X_new)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
SJSlavin/phys202-2015-work
assignments/midterm/AlgorithmsEx03.ipynb
mit
[ "Algorithms Exercise 3\nImports", "%matplotlib inline\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nfrom IPython.html.widgets import interact", "Character counting and entropy\nWrite a function char_probs that takes a string and computes the probabilities of each character in the string:\n\nFirst do a character count and store the result in a dictionary.\nThen divide each character counts by the total number of character to compute the normalized probabilties.\nReturn the dictionary of characters (keys) and probabilities (values).", "def char_probs(s):\n \"\"\"Find the probabilities of the unique characters in the string s.\n \n Parameters\n ----------\n s : str\n A string of characters.\n \n Returns\n -------\n probs : dict\n A dictionary whose keys are the unique characters in s and whose values\n are the probabilities of those characters.\n \"\"\"\n probs = {}\n for n in range(len(s)):\n if s[n] not in probs:\n probs[s[n]] = 1/len(s)\n else:\n probs[s[n]] += 1/len(s)\n \n return probs\n \n\nchar_probs(\"aaannn\")\n\ntest1 = char_probs('aaaa')\nassert np.allclose(test1['a'], 1.0)\ntest2 = char_probs('aabb')\nassert np.allclose(test2['a'], 0.5)\nassert np.allclose(test2['b'], 0.5)\ntest3 = char_probs('abcd')\nassert np.allclose(test3['a'], 0.25)\nassert np.allclose(test3['b'], 0.25)\nassert np.allclose(test3['c'], 0.25)\nassert np.allclose(test3['d'], 0.25)", "The entropy is a quantiative measure of the disorder of a probability distribution. It is used extensively in Physics, Statistics, Machine Learning, Computer Science and Information Science. Given a set of probabilities $P_i$, the entropy is defined as:\n$$H = - \\Sigma_i P_i \\log_2(P_i)$$ \nIn this expression $\\log_2$ is the base 2 log (np.log2), which is commonly used in information science. In Physics the natural log is often used in the definition of entropy.\nWrite a funtion entropy that computes the entropy of a probability distribution. The probability distribution will be passed as a Python dict: the values in the dict will be the probabilities.\nTo compute the entropy, you should:\n\nFirst convert the values (probabilities) of the dict to a Numpy array of probabilities.\nThen use other Numpy functions (np.log2, etc.) to compute the entropy.\nDon't use any for or while loops in your code.", "def entropy(d):\n \"\"\"Compute the entropy of a dict d whose values are probabilities.\"\"\"\n chars = list(d.keys())\n probs = list(d.values())\n \n probs_array = np.asarray(probs)\n \n #print(-np.sum((probs_array) * np.log2(probs_array)))\n return -np.sum((probs_array) * np.log2(probs_array))\n \n\nassert np.allclose(entropy({'a': 0.5, 'b': 0.5}), 1.0)\nassert np.allclose(entropy({'a': 1.0}), 0.0)", "Use IPython's interact function to create a user interface that allows you to type a string into a text box and see the entropy of the character probabilities of the string.", "# YOUR CODE HERE\ndef interact_charprobs(s):\n print(entropy(char_probs(s)))\n #return entropy(char_probs(s))\n\ninteract(interact_charprobs, s=\"Brian E. Granger\");\n\nassert True # use this for grading the pi digits histogram" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
hagne/atm-py
examples/instruments_POPS_mie.ipynb
mit
[ "Introduction\nThis module provides tools to simulate scattering intensities detected by POPS as a function of particle size, refractive index, and some more less obvious parameters. Simulations are based on mie scattering, which gives the module the name. The only function that is worth mentioning is the one below. Its worth exploring all the optional parameters.\nImports", "from atmPy.aerosols.instruments.POPS import mie\n%matplotlib inline\n\nimport matplotlib.pylab as plt\nplt.rcParams['figure.dpi'] = 200", "standard settings", "d,amp = mie.makeMie_diameter(noOfdiameters=1000)\n\nf,a = plt.subplots()\na.plot(d,amp)\na.loglog()\na.set_xlim((0.1,3))\na.set_ylabel('Signal intensity (arb. u.)')\na.set_xlabel('Diameter ($\\mu$m)')", "Wavelength dependence\nas an example what would it mean to use a 445nm instead of a 405nm laser", "noofpoints = 1000\nd,amp405 = mie.makeMie_diameter(noOfdiameters=noofpoints, WavelengthInUm=0.405)\nd,amp445 = mie.makeMie_diameter(noOfdiameters=noofpoints, WavelengthInUm=0.445)\n\nf,a = plt.subplots()\na.plot(d, amp405, label = '405')\na.plot(d, amp445, label = '445')\na.loglog()\n\nlim = [0.14, 3]\narglim = [abs(d - lim[0]).argmin(), abs(d - lim[1]).argmin()]\n# arglim\n\nscs_at_lim_405= amp405[arglim]\n# scs_at_lim_405\n\n#w the lower detection limit will go up to \nd[abs(amp445 - scs_at_lim_405[0]).argmin()]", "refractive index dependence", "nop = 1000\ndI,ampI = mie.makeMie_diameter(noOfdiameters=nop, IOR=1.4)\ndII,ampII = mie.makeMie_diameter(noOfdiameters=nop, IOR=1.5)\ndIII,ampIII = mie.makeMie_diameter(noOfdiameters=nop, IOR=1.6)\n\nf,a = plt.subplots()\na.plot(dI,ampI)\na.plot(dII,ampII)\na.plot(dIII,ampIII)\n\na.loglog()\na.set_xlim((0.1,3))\na.set_ylabel('Signal intensity (arb. u.)')\na.set_xlabel('Diameter ($\\mu$m)')" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
mayank-johri/LearnSeleniumUsingPython
Section 3 - Machine Learning/Supervised Learning Algorithm/Classification/1. Linear Classifiers - support vector machines.ipynb
gpl-3.0
[ "Linear Classifiers - support vector machines (SVMs)\nSVMs try to construct a hyperplane maximizing the margin between the two classes. It selects a subset of the\ninput, called the support vectors, which are the observations closest to the separating hyperplane.", "from sklearn import svm\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nimport numpy as np\n%matplotlib inline\n\niris = datasets.load_iris()\niris_X = iris.data\niris_y = iris.target\nnp.unique(iris_y)\n\nsvc = svm.SVC(kernel='linear')\nsvc.fit(iris.data, iris.target)", "There are several support vector machine implementations in scikit-learn . The most commonly used ones\nare svm.SVC , svm.NuSVC and svm.LinearSVC ; “SVC” stands for Support Vector Classifier.\nUsing kernels\nClasses are not always separable by a hyperplane, so it would be desirable to have a decision function that is\nnot linear but that may be for instance polynomial or exponential:\nLinear kernel", "svc = svm.SVC(kernel='linear')", "Polynomial kernel", "svc = svm.SVC(kernel='poly', degree=3)", "RBF kernel (Radial Basis Function)", "svc = svm.SVC(kernel='rbf')", "Example", "print(__doc__)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import svm, datasets\n\n\ndef make_meshgrid(x, y, h=.02):\n \"\"\"Create a mesh of points to plot in\n\n Parameters\n ----------\n x: data to base x-axis meshgrid on\n y: data to base y-axis meshgrid on\n h: stepsize for meshgrid, optional\n\n Returns\n -------\n xx, yy : ndarray\n \"\"\"\n x_min, x_max = x.min() - 1, x.max() + 1\n y_min, y_max = y.min() - 1, y.max() + 1\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h),\n np.arange(y_min, y_max, h))\n return xx, yy\n\n\ndef plot_contours(ax, clf, xx, yy, **params):\n \"\"\"Plot the decision boundaries for a classifier.\n\n Parameters\n ----------\n ax: matplotlib axes object\n clf: a classifier\n xx: meshgrid ndarray\n yy: meshgrid ndarray\n params: dictionary of params to pass to contourf, optional\n \"\"\"\n Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n out = ax.contourf(xx, yy, Z, **params)\n return out\n\n\n# import some data to play with\niris = datasets.load_iris()\n# Take the first two features. We could avoid this by using a two-dim dataset\nX = iris.data[:, :2]\ny = iris.target\n\n# we create an instance of SVM and fit out data. We do not scale our\n# data since we want to plot the support vectors\nC = 1.0 # SVM regularization parameter\nmodels = (svm.SVC(kernel='linear', C=C),\n svm.LinearSVC(C=C),\n svm.SVC(kernel='rbf', gamma=0.7, C=C),\n svm.SVC(kernel='poly', degree=3, C=C))\nmodels = (clf.fit(X, y) for clf in models)\n\n# title for the plots\ntitles = ('SVC with linear kernel',\n 'LinearSVC (linear kernel)',\n 'SVC with RBF kernel',\n 'SVC with polynomial (degree 3) kernel')\n\n# Set-up 2x2 grid for plotting.\nfig, sub = plt.subplots(2, 2)\nplt.subplots_adjust(wspace=0.4, hspace=0.4)\n\nX0, X1 = X[:, 0], X[:, 1]\nxx, yy = make_meshgrid(X0, X1)\n\nfor clf, title, ax in zip(models, titles, sub.flatten()):\n plot_contours(ax, clf, xx, yy,\n cmap=plt.cm.coolwarm, alpha=0.8)\n ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')\n ax.set_xlim(xx.min(), xx.max())\n ax.set_ylim(yy.min(), yy.max())\n ax.set_xlabel('Sepal length')\n ax.set_ylabel('Sepal width')\n ax.set_xticks(())\n ax.set_yticks(())\n ax.set_title(title)\n\nplt.show()", "Reference\n\nhttps://www.cs.utah.edu/~piyush/teaching/\nhttps://projecteuclid.org/download/pdfview_1/euclid.aos/1211819561 or https://arxiv.org/pdf/math/0701907.pdf" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
jasonody/deep-learning-1
nbs/lesson-1-dogs-vs-cats-with-vgg-16.ipynb
mit
[ "Dogs vs Cats with vgg16\nSetup", "%matplotlib inline", "Path to training and test data", "#path = \"data/dogscats/\"\npath = \"data/dogscats/sample/\"\n\nfrom __future__ import division, print_function\nimport os, json\nfrom glob import glob\nimport numpy as np\nnp.set_printoptions(precision=4, linewidth=100)\nfrom matplotlib import pyplot as plt\n\nimport utils; reload(utils)\nfrom utils import plots", "Vgg16 for basic image recognition", "import vgg16; reload(vgg16)\nfrom vgg16 import Vgg16\n\nvgg = Vgg16()\n\nbatch_size = 64\n\nbatches = vgg.get_batches(path + \"train\", batch_size=batch_size)\nval_batches = vgg.get_batches(path + \"valid\", batch_size=batch_size)", "finetune() modifies the model so that it will be trained based on the batched data provided (cat or dog)", "vgg.finetune(batches)", "fit() the parameters of the model using the training data", "vgg.fit(batches, val_batches, nb_epoch=1)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
tpin3694/tpin3694.github.io
machine-learning/convert_pandas_categorical_column_into_integers_for_scikit-learn.ipynb
mit
[ "Title: Convert Pandas Categorical Data For Scikit-Learn\nSlug: convert_pandas_categorical_column_into_integers_for_scikit-learn\nSummary: Convert Pandas Categorical Column Into Integers For Scikit-Learn\nDate: 2016-11-30 12:00\nCategory: Machine Learning\nTags: Preprocessing Structured Data\nAuthors: Chris Albon \nPreliminaries", "# Import required packages\nfrom sklearn import preprocessing\nimport pandas as pd", "Create DataFrame", "raw_data = {'patient': [1, 1, 1, 2, 2],\n 'obs': [1, 2, 3, 1, 2],\n 'treatment': [0, 1, 0, 1, 0],\n 'score': ['strong', 'weak', 'normal', 'weak', 'strong']}\ndf = pd.DataFrame(raw_data, columns = ['patient', 'obs', 'treatment', 'score'])", "Fit The Label Encoder", "# Create a label (category) encoder object\nle = preprocessing.LabelEncoder()\n\n# Fit the encoder to the pandas column\nle.fit(df['score'])", "View The Labels", "# View the labels (if you want)\nlist(le.classes_)", "Transform Categories Into Integers", "# Apply the fitted encoder to the pandas column\nle.transform(df['score']) ", "Transform Integers Into Categories", "# Convert some integers into their category names\nlist(le.inverse_transform([2, 2, 1]))" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
darioizzo/fast-approx-ML
fast-approx-ML-DL.ipynb
mit
[ "import pickle as pk\nimport matplotlib.pylab as plt\nimport numpy as np\nfrom numpy.linalg import norm\nfrom math import sqrt, exp\n%matplotlib nbagg\nfrom PyKEP import *\nimport seaborn as sns\nsns.set_style(\"whitegrid\")\n\nimport sklearn\nfrom sklearn import *\nimport pandas as pd\nimport lasagne\nimport theano\nimport theano.tensor as T\nimport tqdm\n\nfrom matplotlib import rc\nrc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\n## for Palatino and other serif fonts use:\n#rc('font',**{'family':'serif','serif':['Palatino']})\n#rc('text', usetex=True)", "We load the data file obtained from the optimization (in low-thrust) of many legs (GTOC7): \nast1, ast2, $t_1$, $t_2$, $m^$, $m_i$, $\\Delta V^$, $\\Delta V$, $\\Delta V_L$, $\\Delta V_D$, $m^_L$, $m^_D$\nWe want to learn $\\Delta V$ (i.e. the final mass) from the rest (known quickly using a Lambert solver and Damon model). The ast1 and ast2 ids can be used with the gtoc7 asteroids to know the orbitalparameters.", "a = pk.load(open(\"learn.pkl\",\"rb\"))\ndata = pd.DataFrame(a, columns=['ast1', 'ast2', 't1', 't2', 'm_star', 'm_initial', 'dv_star',\n 'dv_optimal', 'dv_lambert', 'dv_damon', 'm_star_lambert', 'm_star_damon'])\n\ndata.iloc[0]", "Now we do some machine learning\nFrom each line ast1, ast2, $t_1$, $t_2$, $m^$, $m_i$, $\\Delta V^$, $\\Delta V$, $\\Delta V_L$, $\\Delta V_D$, $m^_L$, $m^_D$\nAs attributes we use $t_2-t_1$, $m^_D$, $m_i$, $\\Delta V^_D$, $\\Delta V_L$, $m^*_L$, as these are the ones we can compute at the cost of one lambert problem solution\nFeature Engineering using PyKEP", "def comp_v_inf(r1, r2, v1, v2, t):\n l = lambert_problem(r1, r2, t, MU_SUN, False, 1)\n v1_inf = l.get_v1()[0] - v1\n v2_inf = l.get_v2()[0] - v2\n return np.hstack((v1_inf, v2_inf))\n\ndef compute_m_D_star(v1_inf, v2_inf, DeltaT, T_max, I_sp, g_0):\n v2p1 = v2_inf + v1_inf\n v2m1 = v2_inf - v1_inf\n \n alpha = np.sum(v2p1 * v2p1, axis=1) / np.sum(v2p1 * v2m1, axis=1)\n \n tau = 0.5 * (alpha + 1 - np.sign(alpha) * np.sqrt(1 + alpha**2))\n \n # aD = damon(v1_inf, v2_inf, DeltaT)[-1] / DeltaT # this function is not vectorized\n aD = norm((v2m1.transpose() * tau - v2p1.transpose()) / (tau * DeltaT), axis=0)\n \n return 2 * T_max / aD / (1 + np.exp((-aD * DeltaT) / (I_sp * g_0)))\n\n# a, e, i, Omega, omega, M\norbital_elements = np.array([(\n planet.gtoc7(int(ast1)).osculating_elements(epoch(0)),\n planet.gtoc7(int(ast2)).osculating_elements(epoch(0)),\n ) for ast1, ast2 in zip(data['ast1'], data['ast2'])])\n\nrv = np.array([(\n planet.gtoc7(int(ast1)).eph(t1),\n planet.gtoc7(int(ast2)).eph(t2)\n ) for ast1, ast2, t1, t2 in zip(data['ast1'], data['ast2'], data['t1'], data['t2'])])\n\na1 = orbital_elements[:, 0, 0]\na2 = orbital_elements[:, 1, 0]\n\nr1 = rv[:, 0, 0, :]\nv1 = rv[:, 0, 1, :]\nr2 = rv[:, 1, 0, :]\nv2 = rv[:, 1, 1, :]\n\nn1 = np.sqrt(MU_SUN/a1**3)\nn2 = np.sqrt(MU_SUN/a2**3)\n\nh1 = np.cross(r1, v1)\nh2 = np.cross(r2, v2)\n\ncost = np.sum(h1 * h2, axis=1) / norm(h1, axis=1) / norm(h2, axis=1)\n\nDeltaT = (a[:, 3] - a[:, 2]) * DAY2SEC\n\nv_inf = np.array([comp_v_inf(rve[0, 0, :], rve[1, 0, :], rve[0, 1, :], rve[1, 1, :], dt) for rve, dt in zip(rv, DeltaT)])\n\nv1_inf = v_inf[:, :3]\nv2_inf = v_inf[:, 3:]\n\nT_max = 0.3\nI_sp = 3000\ng_0 = 9.80665\n\n#m_D_star = compute_m_D_star(v1_inf, v2_inf, DeltaT, T_max, I_sp, g_0) # this value should equal to data['m_star_damon']\n\nm_final = data['m_initial'] * (1 - np.exp(-data['dv_optimal'] / I_sp / g_0))\n\nbase_features = np.vstack((DeltaT, cost, norm(r1, axis=1), norm(r2, axis=1),\n norm(v1_inf, axis=1), norm(v2_inf, axis=1), norm(v1, axis=1), norm(v2, axis=1)))\nbase_features = np.hstack((base_features.transpose(), v_inf,\n data[['dv_lambert', 'dv_damon', 'm_star_lambert', 'm_star_damon']],\n rv.reshape(-1, 3 * 4), orbital_elements.reshape(-1, 2 * 6)))", "compose training data", "X = np.hstack((base_features, data[['m_initial', 'm_star']]))\n\n#y = data['m_star']\ny = m_final\n\nX_train, X_test, y_train, y_test = sklearn.cross_validation.train_test_split(X, y, test_size=0.3, random_state=0)", "Test all regressors", "regressors = [\n# sklearn.linear_model.LinearRegression(),\n# sklearn.linear_model.PassiveAggressiveRegressor(),\n# sklearn.linear_model.RANSACRegressor(),\n# sklearn.linear_model.SGDRegressor(),\n# sklearn.linear_model.TheilSenRegressor(),\n #sklearn.linear_model.ARDRegression(), # out of memory...\n# sklearn.linear_model.BayesianRidge(),\n# sklearn.linear_model.ElasticNet(),\n# sklearn.linear_model.Lars(),\n# sklearn.linear_model.Lasso(),\n #sklearn.neighbors.RadiusNeighborsRegressor(), # out of memory...\n# sklearn.neighbors.KNeighborsRegressor(),\n# sklearn.tree.DecisionTreeRegressor(),#min_samples_split=13, min_samples_leaf=5),\n# sklearn.ensemble.ExtraTreesRegressor(),\n# sklearn.ensemble.AdaBoostRegressor(),\n sklearn.ensemble.GradientBoostingRegressor(max_depth=8),\n# sklearn.ensemble.BaggingRegressor(),\n# sklearn.ensemble.RandomForestRegressor(),\n #sklearn.gaussian_process.GaussianProcess(), # out of memory...\n #sklearn.isotonic.IsotonicRegression(), # X is not 1D\n #sklearn.kernel_ridge.KernelRidge(), # out of memory...\n# sklearn.svm.SVR(),\n# sklearn.svm.LinearSVR(),\n# sklearn.svm.NuSVR(),\n# sklearn.cross_decomposition.PLSRegression(),\n]\n\nbest = None\nbest_mse = np.Inf\n\nfor regr in regressors:\n print(type(regr))\n regr.fit(X_train, y_train)\n mse = sklearn.metrics.mean_squared_error(y_test, regr.predict(X_test))\n if mse < best_mse:\n best_mse = mse\n best = regr\n\nmae = sklearn.metrics.mean_absolute_error(y_test, regr.predict(X_test))\n\nprint(\"And the winner is\", type(best))\nprint(\"MAE\", mae)\nprint(\"RMSE\", np.sqrt(best_mse))", "Now we learn m_star and then m_final", "X = base_features\ny = data['m_star']\n\nX_train, X_test, y_train, y_test = sklearn.cross_validation.train_test_split(X, y, test_size=0.3, random_state=0)\n\n# error of the damon model\n\nmse = sklearn.metrics.mean_squared_error(data['m_star'], data['m_star_damon'])\nmae = sklearn.metrics.mean_absolute_error(data['m_star'], data['m_star_damon'])\n\nprint(\"MAE\", mae)\nprint(\"RMSE\", np.sqrt(mse))\n\n# learn to predict m_star\n\nm_star_predictor = ensemble.GradientBoostingRegressor(max_depth=8)\nm_star_predictor.fit(X_train, y_train)\n\n# error\nmse = sklearn.metrics.mean_squared_error(y_test, m_star_predictor.predict(X_test))\nmae = sklearn.metrics.mean_absolute_error(y_test, m_star_predictor.predict(X_test))\n\nprint(\"MAE\", mae)\nprint(\"RMSE\", np.sqrt(mse))\n\n# create a prediction of m_star as feature\n\nm_star_predicted = m_star_predictor.predict(X)\n\n# training data to learn m_final\n\nX = np.hstack((base_features, data[['m_initial']], m_star_predicted.reshape(-1, 1)))\ny = m_final\n\nX_train, X_test, y_train, y_test = sklearn.cross_validation.train_test_split(X, y, test_size=0.3, random_state=0)\n\n# learn to predict m_final\n\nm_final_predictor = ensemble.GradientBoostingRegressor(max_depth=8)\nm_final_predictor.fit(X_train, y_train)\n\n# error\nmse = sklearn.metrics.mean_squared_error(y_test, m_final_predictor.predict(X_test))\nmae = sklearn.metrics.mean_absolute_error(y_test, m_final_predictor.predict(X_test))\n\nprint(\"MAE\", mae)\nprint(\"RMSE\", np.sqrt(mse))\n\n# what if we use the m_star prediction for a regressor that learned with m_star?\n\nmse = sklearn.metrics.mean_squared_error(y_test, regressors[0].predict(X_test))\nmae = sklearn.metrics.mean_absolute_error(y_test, regressors[0].predict(X_test))\n\nprint(\"MAE\", mae)\nprint(\"RMSE\", np.sqrt(mse))\n\n# the error of the m_final predictor (trained with the m_star prediction)\n\nplt.figure()\nh = plt.hist(y_test - m_final_predictor.predict(X_test), 100)\nplt.xlabel(\"error (kg) on the test set\")\nplt.axes()", "Lets see what would happen if, instead we predict the final mass as:\n$$\nm_f = m_i * exp(\\frac{-\\Delta V_L}{I_{sp}g_0)\n$$", "# error of the lambert model\n\nm_final_lambert = data['m_initial'] * (1 - np.exp(-data['dv_lambert'] / I_sp / g_0))\n\nmse = sklearn.metrics.mean_squared_error(m_final, m_final_lambert)\nmae = sklearn.metrics.mean_absolute_error(m_final, m_final_lambert)\n\nprint(\"MAE\", mae)\nprint(\"RMSE\", np.sqrt(mse))\n\n# error of the damon model\n\nm_final_damon = data['m_initial'] * (1 - np.exp(-data['dv_damon'] / I_sp / g_0))\n\nmse = sklearn.metrics.mean_squared_error(m_final, m_final_damon)\nmae = sklearn.metrics.mean_absolute_error(m_final, m_final_damon)\n\nprint(\"MAE\", mae)\nprint(\"RMSE\", np.sqrt(mse))\n\n# plot lambert versus machine learning\n\nm_final_lambert_test = X_test[:, -2] * (1 - np.exp(-X_test[:, 14] / I_sp / g_0))\n\nplt.figure()\nh = plt.hist(y_test - m_final_lambert_test, 100, alpha=0.8,normed=False, log=False)\nh = plt.hist(y_test - m_final_predictor.predict(X_test), 100, alpha=0.5, normed=False, log=False)\nplt.xlabel(\"Error (kg)\")\nplt.ylabel(\"N. instances\")\nplt.xlim(-200,200)\nplt.tight_layout(1)", "Neural Network Training", "class DeepLearningRegressor:\n def __init__(self, layers=[20, 40, 20, 10, 5], learning_rate=0.001, batch_size=16, num_epochs=500, scaler=preprocessing.StandardScaler):\n self.layers = layers\n self.learning_rate = learning_rate\n self.batch_size = batch_size\n self.num_epochs = num_epochs\n \n self.input_scaler = scaler()\n self.output_scaler = scaler()\n \n self.X_val = None\n self.y_val = None\n \n @staticmethod\n def iterate_minibatches(inputs, targets, batchsize, shuffle=False):\n assert len(inputs) == len(targets)\n if shuffle:\n indices = np.arange(len(inputs))\n np.random.shuffle(indices)\n for start_idx in range(0, len(inputs) - batchsize + 1, batchsize):\n if shuffle:\n excerpt = indices[start_idx:start_idx + batchsize]\n else:\n excerpt = slice(start_idx, start_idx + batchsize)\n yield inputs[excerpt], targets[excerpt]\n\n def fit(self, X, y, X_val=None, y_val=None):\n self.X_train = self.input_scaler.fit_transform(X)\n self.y_train = self.output_scaler.fit_transform(y.reshape((-1, 1)))\n \n if y_val is not None:\n self.X_val = self.input_scaler.transform(X_val)\n self.y_val = self.output_scaler.transform(y_val.reshape((-1, 1)))\n \n # input layer\n nn = lasagne.layers.InputLayer((None, X.shape[-1]))\n input_var = nn.input_var\n \n # hidden layers (ReLu)\n for nodes in self.layers:\n nn = lasagne.layers.DenseLayer(nn, nodes)\n \n # output layer (linear)\n nn = lasagne.layers.DenseLayer(nn, 1, nonlinearity=lasagne.nonlinearities.linear)\n \n output_var = lasagne.layers.get_output(nn)\n target_var = T.matrix('target')\n loss = lasagne.objectives.squared_error(target_var, output_var).mean()\n \n params = lasagne.layers.get_all_params(nn)\n updates = lasagne.updates.nesterov_momentum(loss, params, learning_rate=self.learning_rate)\n \n self.train_fn = theano.function([input_var, target_var], loss, updates=updates)\n self.val_fn = theano.function([input_var, target_var], loss)\n self.pred_fn = theano.function([input_var], output_var)\n \n self.train_loss = []\n self.val_loss = []\n \n self.keep_training()\n \n def keep_training(self):\n for epoch in tqdm.trange(self.num_epochs):\n train_batches = 0\n train_err = 0\n val_batches = 0\n val_err = 0\n\n for inputs, targets in DeepLearningRegressor.iterate_minibatches(self.X_train, self.y_train, self.batch_size, shuffle=True):\n train_err += self.train_fn(inputs, targets)\n train_batches += 1\n\n self.train_loss.append(train_err / train_batches)\n\n if self.y_val is not None:\n for inputs, targets in DeepLearningRegressor.iterate_minibatches(self.X_val, self.y_val, self.batch_size, shuffle=False):\n val_err += self.val_fn(inputs, targets)\n val_batches += 1\n\n self.val_loss.append(val_err / val_batches)\n \n def predict(self, X):\n return self.output_scaler.inverse_transform(self.pred_fn(self.input_scaler.transform(X)))\n \n def plot_loss(self):\n plt.figure()\n plt.plot(self.train_loss)\n plt.plot(self.val_loss)\n\nm_nn_predictor = DeepLearningRegressor()\nm_nn_predictor.fit(X_train, y_train, X_test, y_test)\n\n# error\nmse = sklearn.metrics.mean_squared_error(y_test, m_nn_predictor.predict(X_test))\nmae = sklearn.metrics.mean_absolute_error(y_test, m_nn_predictor.predict(X_test))\n\nprint(\"MAE\", mae)\nprint(\"RMSE\", np.sqrt(mse))\n\nm_nn_predictor.plot_loss()" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
nvergos/DAT-ATX-1_Project
Notebooks/2b. Supervised Learning - Classification.ipynb
mit
[ "DAT-ATX-1 Capstone Project\nNikolaos Vergos, February 2016\n&#110;&#118;&#101;&#114;&#103;&#111;&#115;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;\n2b. Supervised Learning: Classification\n0. Import libraries & packages", "import warnings\nwarnings.filterwarnings('ignore')\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline", "1. Import dataset", "#Reading the dataset in a dataframe using Pandas\ndf = pd.read_csv(\"../data/master.csv\") \n\n#Print first observations\ndf.head() ", "Throughout the Machine Learning part of this project we will be using scikit-learn, an open source machine learning library for the Python programming language.\nRecall our arbitrary division of the city into 5 \"Areas\" spanning 36 Zip Codes: Central, SE, NE, SW, NW", "# Focus on the main part of the city\n\nSE_zip = (78744, 78747, 78719, 78741)\nCentral_zip = (78701, 78702, 78703, 78705, 78721, 78723, 78712, 78751, 78756)\nNE_zip = (78752, 78753, 78754)\nNW_zip = (78757, 78758, 78727, 78722, 78729, 78717, 78750, 78759, 78726, 78730, 78731, 78732)\nSW_zip = (78704, 78745, 78748, 78739, 78749, 78735, 78733, 78746)\n\nACL_zip = SE_zip + Central_zip + NE_zip + NW_zip + SW_zip\nlen(ACL_zip)", "We won't need the numerical data here, so let's delete those columns to declutter the Notebook:", "del df['Population']\ndel df['Med_Income']\ndel df['Home_Ownership']", "Let us prepare our DataFrame for Binary Classification models by assigning those Areas, Letter Grades and Pass/Fail according to a restaurant's score (as discussed in the README file) as well as encoding dummy variables:", "# City areas\n\n# Assign Area to each Restaurant, given its Zip Code\n\nmask_SE = df.Zip_Code.isin(SE_zip)\nmask_Central = df.Zip_Code.isin(Central_zip)\nmask_NE = df.Zip_Code.isin(NE_zip)\nmask_NW = df.Zip_Code.isin(NW_zip)\nmask_SW = df.Zip_Code.isin(SW_zip)\n\ndf['Area'] = 'Austin'\ndf.loc[mask_SE, 'Area'] = 'SE Austin'\ndf.loc[mask_Central, 'Area'] = 'Central Austin'\ndf.loc[mask_NE, 'Area'] = 'NE Austin'\ndf.loc[mask_NW, 'Area'] = 'NW Austin'\ndf.loc[mask_SW, 'Area'] = 'SW Austin'\n\n# Assign Pass/Fail status and Letter Grades to each Restaurant\n\ndf['Status'] = 'Fail'\ndf['Letter_Grade'] = 'F'\n\nmask_pass = df['Score'] >= 70\n\nmask_A = df['Score'] >= 90\nmask_B = (df['Score'] >= 80) & (df['Score'] < 90)\nmask_C = (df['Score'] >= 70) & (df['Score'] < 80)\n\ndf.loc[mask_pass, 'Status'] = 'Pass'\n\ndf.loc[mask_A, 'Letter_Grade'] = 'A'\ndf.loc[mask_B, 'Letter_Grade'] = 'B'\ndf.loc[mask_C, 'Letter_Grade'] = 'C'\n\ndf.head(3)\n\n# Assign Dummy Variables for Binary Classifiers\n\n# create five dummy variables using get_dummies, then exclude the first dummy column\n# Note that the Area_Central variable is redundant\n\narea_dummies = pd.get_dummies(df.Area, prefix='Area').iloc[:, 1:]\n\n# create two dummy variables using get_dummies, then exclude the first dummy column\n# Note that the Outcome_Fail variable is redundant\n\noutcome_dummies = pd.get_dummies(df.Status, prefix='Status').iloc[:, 1:]\n\n# create four dummy variables using get_dummies, then exclude the first dummy column\n# Note that the Grade_A variable is redundant\n\nletter_dummies = pd.get_dummies(df.Letter_Grade, prefix='Grade').iloc[:, 1:]", "Let us check those DataFrames before we merge them into df:", "area_dummies.head()\n\noutcome_dummies.head()\n\nletter_dummies.head()", "Let us now concatenate those created DataFrames, keeping a copy of the original DataFrame just in case:", "# Concatenate\n\n# concatenate the dummy variable columns onto the original DataFrame (axis=0 means rows, axis=1 means columns)\n\ndata = pd.concat([df, area_dummies, outcome_dummies, letter_dummies], axis=1)\ndata.head()", "With 22 columns, the DataFrame has already become very hard to visualize, therefore we need to be very careful with our operations from now on.\nLogistic Regression\nWe will at first present an ill-fated approach in order to illustrate the workings of the logistic regression algorithm on our dataset as well as to discuss the evident class imbalance problem and attempt some techniques to mitigate its effects. A naive first approach was to use some of the features in order to predict whether a restaurant will pass the Health Inspection (Score > 69) or not.\nThe issue that makes this problem almost impossible to deal with:", "num_pass = data[data[\"Status\"]=='Pass'].count()\nnum_fail = data[data[\"Status\"]=='Fail'].count()\n\nprint \"Passing Inspections = {0}\".format(num_pass[0])\nprint \"Failing Inspections = {0}\".format(num_fail[0])", "In a sum of 15936 rows, we have 99% passing restaurants (that have scored 70 or higher) and only 1% failing restaurants (that have scored 69 or lower). This is the Class Imbalance problem.\nThe approaches for addressing this are:\n* Sampling based : By oversampling the minority class, it has more effect on the machine learning algorithm, or by undersampling majority class so it has less effect on the machine learning algorithm.\n* Cost function based approaches : Make it more 'costly' for the learning algorithm to make mistakes in the minority class. This is done by tweaking the cost function.\nI will try both approaches, starting from the latter: scikit-learn Logistic Regression model has the attribute class_weight that takes the default value None but can optionally take the value balanced. \nFrom the documentation: \"The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y))\nNote that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified.\"\nLet us start by trying to predict whether a restaurant will pass or fail inspection given the part of town (area) it is at:", "from sklearn import linear_model\nlogm = linear_model.LogisticRegression(class_weight='balanced')\n\nfeature_cols = ['Area_NE Austin', 'Area_NW Austin', 'Area_SE Austin', 'Area_SW Austin']\n\nX = data[ feature_cols ].values\ny = data['Status_Pass'].values\n\n# Check the shapes of the X and y vectors:\n\nprint X.shape\nprint y.shape\n\nlogm.fit(X,y)\n\nprint logm.predict(X) # The array of our model's predictions for each area\nprint logm.classes_ # 0: Fail, 1: Pass\nprint logm.predict_proba(X) # Probabilities for each entry to be assigned a \"Fail\" or a \"Pass\"\n\nlogm.score(X, y)", "Our classifier score is barely better than a coin toss. It seems we will have to improve our approach.", "# examine the coefficients\npd.DataFrame(zip(data[feature_cols], np.transpose(logm.coef_)))", "The coefficients above aren't necessarily significant but they show associations with increased/decreased likelihood of passing the health inspection set. As a matter of fact, a restaurant being located in Northwest Austin is more likely to pass the test whereas a restaurant in Southeast Austin is less likely to do so.\nThe real test of a good model is to train the model on a training set and then test it with data that it has not fitted. Here’s where the rubber meets the road.", "from sklearn import cross_validation\n\nX_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, train_size=0.8)\n\nlogm.fit(X_train,y_train)\n\n# predict class labels for the test set\npredicted = logm.predict(X_test)\n\nprint predicted\n\n# generate class probabilities\nprobs = logm.predict_proba(X_test)\n\nprint probs\n\nlogm.score(X_test, y_test)", "k-fold Cross Validation has not really helped us improve the score of our classifier.\nEven though we are far from creating a foolproof model, we can definitely discern some interesting trends.", "# Evaluation Metrics\n\nfrom sklearn import metrics\n\nprint metrics.accuracy_score(y_test, predicted)\nprint metrics.roc_auc_score(y_test, probs[:, 1])", "The 0.506 ROC score is fairly low. It is telling us that our model is doing slightly better in predicting a restaurant's inspection outcome (pass/fail) than a coin toss (which would have a 0.5 probability)", "# Confusion Matrix and Classification Report:\n\n# Confusion Matrix\n\ncm = metrics.confusion_matrix(y_test, logm.predict(X_test), labels=[1,0]) #labels = [1,0] will change the order: T,F\n\ncm\n\nprint metrics.confusion_matrix(y_test, predicted, labels=[1,0])\nprint metrics.classification_report(y_test, predicted,labels=[1,0])\n\n# Visualize Confusion Matrix:\n\ndef plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n \nplot_confusion_matrix(cm)", "There really isn't any reason for us to delve further into that model because the misclassification rate is really substantial and as we mentioned it's not really doing significantly better than a coin toss.\nLet us now quickly approach a different strategy to mitigate the results of class imbalance: oversampling the minority class (failing restaurants)", "#Grab DataFramea rows where column has certain values\n\nvalue_list_f = ['Fail']\nfailures = data[data.Status.isin(value_list_f)]\n\nvalue_list_p = ['Pass']\npasses = data[data.Status.isin(value_list_p)]\n\n# Let us pick two random samples of 100 rows each from the \"failures\" and \"passes\" dataframes: \n\nrows_f = np.random.choice(failures.index.values, 100)\nrows_p = np.random.choice(passes.index.values, 100)\n\n# Convert to dataframes:\n\nsampled_f = failures.ix[rows_f]\nsampled_p = passes.ix[rows_p]\n\n# Concatenate into \"training\" dataframe:\n\ntraining_df = pd.concat([sampled_p, sampled_f], axis=0)\nprint \"The training DataFrame comprises {0} rows\".format(len(training_df))\n\n# Train our logistic regression model on this data:\n\nlogm = linear_model.LogisticRegression() # We don't need balanced class weights anymore\n \nfeature_cols = ['Area_NE Austin', 'Area_NW Austin', 'Area_SE Austin', 'Area_SW Austin']\n\nX_tr = training_df[ feature_cols ].values\ny_tr = training_df['Status_Pass'].values\n\nlogm.fit(X_tr, y_tr)\n\nprint \"The model's score on the training data is {0}%\".format(logm.score(X_tr, y_tr)*100)", "This doesn't sound very promising. Regardless, let us construct the testing DataFrame (comprising all rows that aren't already seen by the model)", "# Create a DataFrame with all rows that are in data but NOT in training_df:\n\ndf1 = data\ndf2 = training_df\n\ncommon_cols = list(set(df1.columns) & set(df2.columns))\n\ntesting_df = pd.merge(df1,df2,on=common_cols,how=\"outer\",indicator=True)\n\ntesting_df = testing_df.loc[testing_df['_merge'] == 'left_only']\n\nX_ts = testing_df[ feature_cols ].values\ny_ts = testing_df['Status_Pass'].values\n\n# Model Validation:\n\n# predict class labels for the test set\npredicted = logm.predict(X_ts)\n\n# generate class probabilities\nprobs = logm.predict_proba(X_ts)\n\n# Evaluation Metrics:\n\nprint metrics.accuracy_score(y_ts, predicted)\nprint metrics.roc_auc_score(y_ts, probs[:, 1])", "The results are no better than before, and possibly more disappointing. It seems that the part of town a restaurant is located in is a terrible predictor of its Health Inspection broad outcome. (Pass/Fail)\nFrom now on I am changing my approach to something more drastic. Instead of aiming to classify health inspection outcomes as \"Passes\" or \"Fails\", I will implement a different kind of classification: A resulting letter grade of \"A\" (which implies a Health Inspection score of 90 or higher) vs. everything else (Scores 89 and below)\nBefore throwing my hands up in the air with the use of Area as input features for my models, I will try once more:", "num_A = data[data[\"Letter_Grade\"]=='A'].count()\nnum_other = data[data[\"Letter_Grade\"]!='A'].count()\n\nprint \"Pristine Restaurants (90 or above) = {0}\".format(num_A[0])\nprint \"Restaurants scoring 89 or below = {0}\".format(num_other[0])", "There is a much nicer distribution between the classes now! Let us construct two new dummy variables, one for \"Pristine\" restaurants (the same ones obtaining a grade \"A\", which has been the redundant dummy variable in my previous treatment) and one for everything else:", "# I need the \"Grade_A\" column:\n\ndef pristine(x):\n if x >= 90:\n return 1\n else:\n return 0\n\ndata['Pristine'] = data['Score'].apply(pristine)\ndata.head(2)", "Let us save this DataFrame as a csv file because we are going to use it again in the next Notebook (Text mining):", "data.to_csv('../data/data.csv', index=False)\n\n# Off to modeling:\n\nlogm = linear_model.LogisticRegression()\n\nfeature_cols = ['Area_NE Austin', 'Area_NW Austin', 'Area_SE Austin', 'Area_SW Austin']\n\nX = data[ feature_cols ].values\ny = data['Pristine'].values\n\n# Cross-validation:\n\nX_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, train_size=0.75)\n\n# Fitting the model:\n\nlogm.fit(X_train, y_train)\n\n# Model Validation:\n\n# predict class labels for the test set\npredicted = logm.predict(X_test)\n\n# generate class probabilities\nprobs = logm.predict_proba(X_test)\n\n# Evaluation Metrics:\n\nprint metrics.accuracy_score(y_test, predicted)\nprint metrics.roc_auc_score(y_test, probs[:, 1])", "Even though our goal has changed (we are seeking to predict whether a restaurant will ace the health inspection) the results of our model are still disappointing. It is becoming more and more evident that Area isn't a good predictor.\nOur final attempt will be to \"strong-arm\" our model by manually changing the logistic regression classification threshold from 0.5 to something much higher like 0.8\nHopefully this will eradicate some of the misclassifications. In order to manipulate our model like that, we will use statsmodels instead of scikit-learn:", "import statsmodels.api as sm\n\nlogit = sm.Logit(data['Pristine'], data[ feature_cols ])\n\n# fit the model\n\nmodel_result = logit.fit()\n\npredicted = model_result.predict(data[ feature_cols ])\n\nthresholds = [0.5, 0.6, 0.7, 0.8, 0.9]\n\nfor i in thresholds:\n predicted_choice = (predicted > i).astype(int)\n print \"The number of restaurants predicted to pass inspection (grade A) with logistic threshold = {0} is {1}\".\\\n format(i, sum(predicted_choice) )", "Raising the logistic regression classifier threshold to anything higher than 60% results in zero restaurants predicted to pass inspection with a grade \"A\", given the area.", "print model_result.summary()", "We get a great overview of the coefficients of the model, how well those coefficients fit, the overall fit quality, and several other statistical measures.\nThe result object also lets us to isolate and inspect parts of the model output. The confidence interval gives an idea for how robust the coefficients of the model are. Once again, we might not be getting anything really important from this classifier, but we can definitely see the \"trend\" of restaurants being located in my ad hoc \"Northwest Austin\" area being more prone to do better.", "# Odds ratio:\n\nprint np.exp(model_result.params)", "This tells us how a 1 unit increase or decrease in a variable affects the odds of scoring an \"A\". For example, we can expect the odds of scoring an \"A\" to increase by about 212% if the restaurant is located in Northwest Austin. However we should be really cautious and only perceive those odds ratios relative to each other.\nLogistic Regression outcome:\nRegardless of the model used, the overall prediction accuracy for the city is close to 60%, which is almost equal to random guessing and therefore implies that the area is probably not a useful factor.\nThe poor performance of this factor is likely due to the fact that each area is very large and consists of many diverse neighborhoods (zip codes), which means there is too much variation within each area.\nk - Nearest Neighbors Classification on average scores\nThe greatest plight of our DataFrame and our attempts to apply supervised learning techniques to predict the inspection score is the absence of continuous (or categorical) features specific to each restaurant. Let us attempt a different binary classifier, k Nearest Neighbors, for the case where our DataFrame comprises the averaged scores of each Zip Code. Again, we need to be overly cautious because we only have 35 rows now:", "average_scores = data.groupby('Zip_Code').mean()\nlen(average_scores)\n\naverage_scores.head()", "We will need to create another dummy column for \"Pristine\" since averaging removed the 1-0 dichotomy. We do get some interesting average scores for each zip code though.", "def dummy_pristine(x):\n if x >= 0.50:\n return 1\n else:\n return 0\n \naverage_scores['Pristine_Dummy'] = average_scores['Pristine'].apply(dummy_pristine)\naverage_scores.head()\n\nfrom matplotlib.colors import ListedColormap\nfrom sklearn import feature_selection\nfrom sklearn.neighbors import KNeighborsClassifier as KNN\n\nfeature_cols = ['Area_NE Austin', 'Area_NW Austin', 'Area_SE Austin', 'Area_SW Austin']\n\nX = average_scores[ feature_cols ].values\ny = average_scores['Pristine_Dummy'].values\n\nclf = KNN(3)\nclf.fit(X, y)\nprint clf.score(X, y)", "A score of 91% on 35 rows of data isn't exciting; it is overfitting. Even though we only have few points, we can attempt train/test split and cross validation:", "# Cross-validation:\n\nX_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, train_size=0.8)\n\nclf.fit(X_train, y_train)\nprint clf.score(X_test, y_test)", "Looks slightly better", "# Let's figure out what our most powerful features are.\n\nF = feature_selection.f_classif(X, y)[0]\ntitle = 'Health Inspection Features with F-Values'\n\nplt.figure(figsize=(13, 8))\nax = sns.barplot(x=feature_cols,y=F)\nax.set_title(title)\nax.set(xlabel=\"Features\");", "The k Nearest Neighbors classifier yields another interesting feature: the importance of \"Southeast Austin\" in classifying a restaurant as \"pristine\" or not.", "g = sns.PairGrid(average_scores, vars=[\"Latitude\", \"Longitude\"],\n hue=\"Pristine\", aspect=1, size=5)\ng.map(plt.scatter);\n\ny = average_scores['Pristine']\na = list(y.unique())\na = [round(n, 1) for n in a]\n\naverage_scores['Round_Pristine'] = a\n\ng = sns.PairGrid(average_scores, vars=[\"Latitude\", \"Longitude\"],\n hue=\"Round_Pristine\", aspect=1, size=5)\ng.map(plt.scatter);\ng = g.add_legend()", "We have plotted those averages on this longitude/latitude plane that resembles a map. The hue of the data points corresponds to \"Pristine\", which in our case is the fraction of restaurants that have been awarded a perfect score in each Zip Code.", "r = set(a)\nlen(r) # The number of unique \"Rounded Pristine\" scores, we will use that to visualize decision boundaries:", "Visualizing the decision boundaries", "h = .02 # step size in the mesh\n\n# Create color maps\ncol_map = sns.color_palette(\"Paired\")\nsns.palplot(col_map)\ncmap_light = ListedColormap(['#A6CEE3', '#AFDD8A', '#FA9897'])\ncmap_bold = ListedColormap(['#2078B4', '#35A12E', '#E31A1C'])\n\nprint a\n\nfeatures = ['Latitude', 'Longitude']\nX_ = average_scores[features].values\n\nr =list(r)\ny_ = [r.index(v) for v in a] # Encode the rounded scores to integers\n\nprint y_\n\nclf = KNN(2, weights='uniform')\nclf.fit(X_, y_)\n\n# Plot the decision boundary. For that, we will assign a color to each\n# point in the mesh [x_min, m_max]*[y_min, y_max].\nx_min, x_max = X_[:, 0].min() - 1, X_[:, 0].max() + 1\ny_min, y_max = X_[:, 1].min() - 1, X_[:, 1].max() + 1\n\nxx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n\nZ = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n\n# Put the result into a color plot\nZ = Z.reshape(xx.shape)\n\n# Plot also the training points\nplt.figure(figsize=(13,8))\nplt.pcolormesh(xx, yy, Z, cmap=cmap_light)\nplt.scatter(X_[:, 0], X_[:, 1], c=y_, cmap=cmap_bold)\nplt.xlim(xx.min(), xx.max())\nplt.ylim(yy.min(), yy.max())\nplt.title(\"5-Class classification (k = %i, weights = '%s')\"\n % (2, 'uniform'));", "We only got 3 classes when running our KNN algorithm for k=2 (and less classes if we raise k) - this makes sense because we have a very small number of points to classify and they all seem clustered together.\nLet us take a step back and remember what are the prerequisites for a successful implementation of the k Nearest Neighbors binary classifier:\n\nDensity of training data: you should have roughly the same number of samples for each class. Doesn't need to be exact, but I'd say not more than 10% disparity. Otherwise the boundaries will be very fuzzy.\nSize of your whole training set: you need to have sufficiently enough examples in your training set so your model can generalize to unknown samples.\nNoise: KNN is very sensitive to noise by nature, so you want to avoid noise in your training set as much as possible.\n\nNone of those prerequisites is really satisfied, so choosing a KNN Classifier was a bad idea, save from the nice scatter plot.\nDecision Trees - Random Forests\nGoing back to our \"data\" DataFrame, let us now attempt to implement a decision tree as a binary classifier", "data.head(3)\n\nfrom sklearn import tree\n\nfeature_cols = ['Area_NE Austin', 'Area_NW Austin', 'Area_SE Austin', 'Area_SW Austin']\n\nX = data[ feature_cols ].values\ny = data['Pristine'].values\n\nclf = tree.DecisionTreeClassifier()\nclf.fit(X, y)\ny_pred = clf.predict(X)\n\nprint \"Number of mislabeled points : %d\" % (y != y_pred).sum()\nprint \"Classifier score: %d\" % clf.score(X, y)\n\nlen(y)", "We have mislabeled 6022 out of the 16113 points, yet the classifier's score is equal to zero. (?)\nLet us attempt a train/test split and cross-validation:", "X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=.25)\nclf.set_params(min_samples_leaf=4)\nclf.set_params(max_depth=3)\nclf.fit(X_train, y_train)\n\nprint metrics.confusion_matrix(y_train, clf.predict(X_train))\nprint metrics.classification_report(y_train, clf.predict(X_train))\nprint \"The score of the Decision Tree classifier on the training data is {0}\".format(clf.score(X_train,y_train))\nprint \"\"\nprint metrics.confusion_matrix(y_test, clf.predict(X_test))\nprint metrics.classification_report(y_test, clf.predict(X_test))\nprint \"The score of the Decision Tree classifier on the test data is {0}\".format(clf.score(X_test,y_test))\n\n", "The zeros in the $[0][0]$ element of the confusion matrix are really bad news: they mean that our tree classifier is really incapable of correctly classifying any true positives (i.e. restaurants passing the health inspection)\nWe can still try to visualize our tree, which does have some merit due to its 63.2% classification score, but it is becoming more and more evident that this broad area division is a poor feature for our classification purposes.", "from sklearn.externals.six import StringIO\nwith open(\"pristine.dot\", 'w') as f:\n f = tree.export_graphviz(clf, out_file=f, feature_names=feature_cols)\n\n!dot -Tpng pristine.dot > pristine.png", "", "# Even a random forest comprising 250 trees yields the exact same classifier score:\n\nfrom sklearn.ensemble import RandomForestClassifier\n\n## DecisionTreeClassifier\ndtree = tree.DecisionTreeClassifier(max_depth=None, min_samples_split=1,\n random_state=0)\nscores = cross_validation.cross_val_score(dtree, X_test, y_test)\nprint \"DecisionTreeClassifier:\", scores.mean()\n\n## RandomForestClassifier\nforest = RandomForestClassifier(n_estimators=250,\n max_features=4, random_state=0, max_depth=None)\nscores = cross_validation.cross_val_score(forest, X_test, y_test)\nprint \"RandomForestClassifier:\", scores.mean()", "Decision Trees and Random Forests give us some interesting information concerning the relative importance of their estimators, and we can visualize those importances:", "importances = forest.fit(X, y).feature_importances_\nstd = np.std([tree.feature_importances_ for tree in forest.estimators_],\n axis=0)\nindices = np.argsort(importances)[::-1]\n\n# Print the feature ranking\nprint(\"Feature ranking:\")\n\nfor f in range(X.shape[1]):\n print(\"{0}. feature {1} ({2})\".format(f + 1, feature_cols[f], importances[indices[f]]))\n\n# Plot the feature importances of the forest\n\nimport matplotlib.pyplot as plt\n%matplotlib inline \n\nplt.figure()\nplt.title(\"Feature importances\")\nplt.bar(range(X.shape[1]), importances[indices],\n color=\"r\", yerr=std[indices], align=\"center\")\nplt.xticks(range(X.shape[1]), indices)\nplt.xlim([-1, X.shape[1]])\nplt.show()", "According to our Random Forest model, the most important feature is a restaurant's location in Northeast Austin. However, given the terrible performance of the classifier in actually finding any passing restaurants, we can safely ignore this result.\nSupport Vector Classifier\nOur final attempt before we give up trying to classify restaurants given the (ad hoc) area of town they are located in is a support vector machine classifier:", "from sklearn import svm\n\nsvc = svm.SVC(kernel='linear')\n\nX = data[ feature_cols ].values\ny = data['Pristine'].values\n\nsvc.fit(X, y)\n\nfrom matplotlib.colors import ListedColormap\n# Create color maps for 2-class classification problem\ncmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])\ncmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])\n\ndef plot_estimator(estimator, X, y):\n estimator.fit(X, y)\n x_min, x_max = X[:, 0].min() - .1, X[:, 0].max() + .1\n y_min, y_max = X[:, 1].min() - .1, X[:, 1].max() + .1\n xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100),\n np.linspace(y_min, y_max, 100))\n Z = estimator.predict(np.c_[xx.ravel(), yy.ravel()])\n\n # Put the result into a color plot\n Z = Z.reshape(xx.shape)\n plt.figure()\n plt.pcolormesh(xx, yy, Z, cmap=cmap_light)\n\n # Plot also the training points\n plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)\n plt.axis('tight')\n plt.axis('off')\n plt.tight_layout()\n\nX_ = data[['Area_NW Austin', 'Area_SE Austin']].values # picking two \"important\" features\ny_ = data['Score'].values\nplot_estimator(svc, X_, y_)", "Visualizing the decision boundaries of our SVC yield a terrible picture, and I assume it is because of the categorical nature of both the features and the output. Let us score it instead:", "print X.shape\nprint y.shape\n\nsvc.score(X,y)", "The support vector classifier yielded a slightly better score when ran on the entire data set. Let us try a train/test split and cross validation to make sure we are not overfitting:", "# Cross-validation:\n\nX_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, train_size=0.8)\n\nsvc.fit(X_train, y_train)\n\nprint svc.score(X_test, y_test)", "This is a rather respectable score, 62.7%\nInterestingly enough, changing the kernel function from 'linear' to 'polynomial' or 'radial' doesn't seem to really affect the classifier's performance. The same applied to changing the class_weight parameter to balanced.\nRemember that even though the Support Vector Classifier has definitely resulted in the most promising classifier (because decision trees and the random forest fail to classify ANY restaurant as \"pristine\") for our data, the price we have to pay is our model's interpretability, since SVMs are largely \"black boxes\". Our firm conviction is that Area is not a good predictor of a restaurant's health inspection status, therefore our next attempt will be text mining and using a restaurant's name or the name of the street it is located at as a predictor.\nNext: Supervised Learning - Text Mining for Classification" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
pangeo-data/rechunker
docs/tutorial.ipynb
mit
[ "Rechunker Tutorial\nThis tutorial notebook explains how to use rechunker with real datasets. We will also use xarray to make some things easier and prettier, but we note that xarray is not a dependency for rechunker.\nToy Example\nCreate Example Data\nHere we load one of xarray's tutorial datasets and write it to Zarr. This is not actually a big dataset, so rechunker is not really needed here. But it's a convenient example.", "import xarray as xr\nxr.set_options(display_style='text')\nimport zarr\nimport dask.array as dsa\n\nds = xr.tutorial.open_dataset(\"air_temperature\")\n# create initial chunk structure\nds = ds.chunk({'time': 100})\nds.air.encoding = {} # helps when writing to zarr\nds", "We can examine the chunk structure of the data variable using Dask's pretty Array repr.", "ds.air.data\n\n! rm -rf *.zarr # clean up any existing temporary data\nds.to_zarr('air_temperature.zarr')", "Now we open up a Zarr Group and Array that we will use as inputs to rechunker.", "source_group = zarr.open('air_temperature.zarr')\nprint(source_group.tree())\n\nsource_array = source_group['air']\nsource_array.info", "Rechunk a single Array\nThe original array has chunks of (100, 25, 53). Let's rechunk it to be contiguous in time, but chunked in space.\nWe specify a small value of max_mem in order to force rechunker to create an intermediate dataset. We also have to specify a place to store the final and intermediate data.\nWe use the rechunk function, which returns a Rechunked object.", "from rechunker import rechunk\n\ntarget_chunks = (2920, 25, 1)\nmax_mem = '1MB'\n\ntarget_store = 'air_rechunked.zarr'\ntemp_store = 'air_rechunked-tmp.zarr'\n\narray_plan = rechunk(source_array, target_chunks, max_mem, target_store, temp_store=temp_store)\narray_plan", "Since this array has dimensions, we can also specify the chunks using a dictionary syntax.", "target_chunks_dict = {'time': 2920, 'lat': 25, 'lon': 1}\n\n# need to remove the existing stores or it won't work\n!rm -rf air_rechunked.zarr air_rechunked-tmp.zarr\narray_plan = rechunk(source_array, target_chunks_dict, max_mem, target_store, temp_store=temp_store)\narray_plan", "The array_plan is a Rechunked object.\nIt has not actually performed the rechunking yet.\nTo do this, we need to call the execute method.\nThis will use Dask to perform the rechunking.", "result = array_plan.execute()\nresult.chunks", "By default, Dask will use the multi-threaded scheduler.\nSince rechunking can take a long time, we might want to use a progress bar.", "from dask.diagnostics import ProgressBar\n\nwith ProgressBar():\n array_plan.execute()", "If we create a distributed cluster, then rechunker will use that when it executes.", "from dask.distributed import Client, LocalCluster, progress\n\ncluster = LocalCluster()\nclient = Client(cluster)\n\nfuture = array_plan.persist()\nprogress(future)", "Now that it is written to disk, we can open the rechunked array however we please. Using Zarr...", "target_array = zarr.open('air_rechunked.zarr')\ntarget_array", "...or Dask", "target_array_dask = dsa.from_zarr('air_rechunked.zarr')\ntarget_array_dask", "Rechunk a Group\nIn the example above, we only rechunked a single array.\nWe can open it with Dask, but not Xarray, because it doesn't contain any coordinates or metadata.\nRechunker also supports rechunking entire groups.\nIn this case, target_chunks must be a dictionary.", "target_chunks = {\n 'air': {'time': 2920, 'lat': 25, 'lon': 1},\n 'time': None, # don't rechunk this array\n 'lon': None,\n 'lat': None,\n}\nmax_mem = '1MB'\n\ntarget_store = 'group_rechunked.zarr'\ntemp_store = 'group_rechunked-tmp.zarr'\n\n# need to remove the existing stores or it won't work\n!rm -rf group_rechunked.zarr group_rechunked-tmp.zarr\narray_plan = rechunk(source_group, target_chunks, max_mem, target_store, temp_store=temp_store)\narray_plan\n\narray_plan.execute()", "Now that we have written a group, we can open it back up with Xarray.", "xr.open_zarr('group_rechunked.zarr')", "Often groups have many variables sharing all or a subset of dimensions. In the common case that a given dimension should have equivalent chunks in each variable that contains it, chunks can be provided as a simpler dictionary, mapping dimension names to chunksize.", "# extend the dataset with some more variables\nds_complex = ds\nds_complex['air_slice'] = ds.air.isel(lat=10)\nds_complex['air_timeseries'] = ds.air.isel(lat=10, lon=10)\nds_complex\n\ntarget_chunks = {'time': 2920, 'lat': 25, 'lon': 1}\nmax_mem = '1MB'\n\ntarget_store = 'group_complex_rechunked.zarr'\ntemp_store = 'group_complex_rechunked-tmp.zarr'\n\n# need to remove the existing stores or it won't work\n!rm -rf group_complex_rechunked.zarr group_complex_rechunked-tmp.zarr\n\n# rechunk directly from dataset this time\narray_plan = rechunk(ds_complex, target_chunks, max_mem, target_store, temp_store=temp_store)\narray_plan\n\narray_plan.execute()\n\nxr.open_zarr('group_complex_rechunked.zarr')", "Note that all the variables now have the same time chunks. Other dimensions (if they exist) also have consistent chunks. \nCloud Example\nIn this example we use real data from Pangeo's Cloud Data Catalog.\nThis dataset is stored in Google Cloud Storage.\nWe also use a Dask Gateway distributed cluster to scale up our processing.\nThis part of the tutorial won't work for you unless you are in a Pangeo Cloud environment or binder.", "from dask_gateway import GatewayCluster\ncluster = GatewayCluster()\ncluster.scale(20)\ncluster\n\nfrom dask.distributed import Client\nclient = Client(cluster)\nclient\n\nimport gcsfs\n# a zarr group lives here\nurl = 'gs://pangeo-cmems-duacs'\ngcs = gcsfs.GCSFileSystem(requester_pays=True)\nsource_store = gcs.get_mapper(url)", "Open Zarr Array", "group = zarr.open_consolidated(source_store, mode='r')\nsource_array = group['sla']\nsource_array\n\nsource_array.chunks", "Make a Rechunking Plan", "max_mem = '1GB'\ntarget_chunks = (8901, 72, 72)\n# you must have write access to this location\nstore_tmp = gcs.get_mapper('pangeo-scratch/rabernat/rechunker_demo/temp.zarr')\nstore_target = gcs.get_mapper('pangeo-scratch/rabernat/rechunker_demo/target.zarr')\nr = rechunk(source_array, target_chunks, max_mem,\n store_target, temp_store=store_tmp)\nr", "Execute the Plan", "result = r.execute()\nresult\n\ndsa.from_zarr(result)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
rabernat/xray
examples/xarray_multidimensional_coords.ipynb
apache-2.0
[ "Working with Multidimensional Coordinates\nAuthor: Ryan Abernathey\nMany datasets have physical coordinates which differ from their logical coordinates. Xarray provides several ways to plot and analyze such datasets.", "%matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nimport cartopy.crs as ccrs\nfrom matplotlib import pyplot as plt\n\nprint(\"numpy version : \", np.__version__)\nprint(\"pandas version : \", pd.__version__)\nprint(\"xarray version : \", xr.version.version)", "As an example, consider this dataset from the xarray-data repository.", "ds = xr.tutorial.load_dataset('rasm')\nds", "In this example, the logical coordinates are x and y, while the physical coordinates are xc and yc, which represent the latitudes and longitude of the data.", "print(ds.xc.attrs)\nprint(ds.yc.attrs)", "Plotting\nLet's examine these coordinate variables by plotting them.", "fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14,4))\nds.xc.plot(ax=ax1)\nds.yc.plot(ax=ax2)", "Note that the variables xc (longitude) and yc (latitude) are two-dimensional scalar fields.\nIf we try to plot the data variable Tair, by default we get the logical coordinates.", "ds.Tair[0].plot()", "In order to visualize the data on a conventional latitude-longitude grid, we can take advantage of xarray's ability to apply cartopy map projections.", "plt.figure(figsize=(14,6))\nax = plt.axes(projection=ccrs.PlateCarree())\nax.set_global()\nds.Tair[0].plot.pcolormesh(ax=ax, transform=ccrs.PlateCarree(), x='xc', y='yc', add_colorbar=False)\nax.coastlines()\nax.set_ylim([0,90]);", "Multidimensional Groupby\nThe above example allowed us to visualize the data on a regular latitude-longitude grid. But what if we want to do a calculation that involves grouping over one of these physical coordinates (rather than the logical coordinates), for example, calculating the mean temperature at each latitude. This can be achieved using xarray's groupby function, which accepts multidimensional variables. By default, groupby will use every unique value in the variable, which is probably not what we want. Instead, we can use the groupby_bins function to specify the output coordinates of the group.", "# define two-degree wide latitude bins\nlat_bins = np.arange(0,91,2)\n# define a label for each bin corresponding to the central latitude\nlat_center = np.arange(1,90,2)\n# group according to those bins and take the mean\nTair_lat_mean = ds.Tair.groupby_bins('xc', lat_bins, labels=lat_center).mean()\n# plot the result\nTair_lat_mean.plot()", "Note that the resulting coordinate for the groupby_bins operation got the _bins suffix appended: xc_bins. This help us distinguish it from the original multidimensional variable xc." ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
RaviSoji/probabilistic_LDA
mnist_demo/mnist_demo.ipynb
apache-2.0
[ "Outline\n\nImport plda and other convenient packages.\nLoad data.\nPreprocess data and fit model.\nHow to classify datapoints: Overfit classifier.\nHow to classify datapoints: Better-fit classifier.\nExtracting LDA-features.\nHow to classify datapoints: \"same-or-different category\" discrimination.\nExtracting preprocessing information.\nExtracting model parameters.\n\nImport plda and other convenient packages.", "import matplotlib.pyplot as plt\nimport numpy as np\nimport plda\n\n%matplotlib inline", "Load Data.", "# To minimize the size of this repository, I only provide 200 training and 100 testing images.\ntraining_data = np.load('mnist_data/mnist_train_images.npy')\ntraining_labels = np.load('mnist_data/mnist_train_labels.npy')\ntesting_data = np.load('mnist_data/mnist_test_images.npy')\ntesting_labels = np.load('mnist_data/mnist_test_labels.npy')\n\nprint(training_data.shape, training_labels.shape)\nprint(testing_data.shape, testing_labels.shape)\n\nn_examples = 5\nfig, ax_arr = plt.subplots(1, n_examples, figsize=(10, 2))\n\nfor x in range(n_examples):\n ax_arr[x].imshow(training_data[x].reshape(28, 28), cmap='gray')\n ax_arr[x].set_xticks([])\n ax_arr[x].set_yticks([])\nplt.show()", "Preprocess data and fit model.\nYou have 3 options.\n\nDefault: keep as many principal components as possible (i.e. overfit). See plda.Model.fit()) for details.\nOptional: specify a smaller number of desired principal components to use (potentially reduces overfitting).\nAlternatively, you can preprocess the data yourself before passing it to this model.\n\nFit model for overfit classifier (default)", "# Use as many principal components in the data as possible.\n\noverfit_classifier = plda.Classifier()\noverfit_classifier.fit_model(training_data, training_labels)", "Fit model for better fit classifier (optional)", "# Use the 5 top principal components to reduce overfitting.\n# This will preprocess training data from shape (200, 784) to (200, 5).\n\nbetter_classifier = plda.Classifier()\nbetter_classifier.fit_model(training_data, training_labels, n_principal_components=5)", "How to classify datapoints: Overfit classifier.", "predictions, log_p_predictions = overfit_classifier.predict(testing_data)\n\n# Overfit:\n# Ratio of avg. sample size to data dimension is very small\n# (about ~20 / 200 = ~.2).\nprint('Accuracy: {}'.format((testing_labels == predictions).mean()))\n\nn_examples = 10\nfig, ax_arr = plt.subplots(1, n_examples, figsize=(20, 2))\n\nfor x in range(n_examples):\n ax_arr[x].imshow(testing_data[x].reshape(28, 28), cmap='gray')\n ax_arr[x].set_xticks([])\n ax_arr[x].set_yticks([])\n title = 'Prediction: {}'\n xlabel = 'Truth: {}'\n ax_arr[x].set_title(title.format(predictions[x]))\n ax_arr[x].set_xlabel(xlabel.format(testing_labels[x]))\nplt.show()", "How to classify datapoints: Better-fit classifier.", "predictions, log_p_predictions = better_classifier.predict(testing_data)\nprint('Accuracy: {}'.format((testing_labels == predictions).mean()))\n\nn_examples = 10\nfig, ax_arr = plt.subplots(1, n_examples, figsize=(20, 2))\n\nfor x in range(n_examples):\n ax_arr[x].imshow(testing_data[x].reshape(28, 28), cmap='gray')\n ax_arr[x].set_xticks([])\n ax_arr[x].set_yticks([])\n title = 'Prediction: {}'\n xlabel = 'Truth: {}'\n ax_arr[x].set_title(title.format(predictions[x]))\n ax_arr[x].set_xlabel(xlabel.format(testing_labels[x]))\nplt.show()", "Extracting LDA features.\nThere are 4 \"spaces\" that result from the transformations the model performs:\n1. Data space ('D'),\n2. Preprocessed data space ('X'),\n3. Latent space ('U'), and\n4. The \"effective\" space of the latent space ('U_model'), \n which is essentially the set of dimensions the model actually uses for prediction.\nYou can transform data between these spaces using the classifier.model.transform() function.", "U_model = better_classifier.model.transform(training_data, from_space='D', to_space='U_model')\n\nprint(training_data.shape)\nprint(U_model.shape)\n\nD = better_classifier.model.transform(U_model, from_space='U_model', to_space='D')\n\nprint(U_model.shape)\nprint(D.shape)", "How to classify datapoints: same-different discrimination.\nThese are log-ratios, which means:\n- negative values mean that the model believes the two data points being compared are from two different categories.\n- positive values mean that the model believes the two data points are from the same category.", "U_datum_0 = U_model[0][None,]\nU_datum_1 = U_model[1][None,]\n\nlog_ratio_0_1 = better_classifier.model.calc_same_diff_log_likelihood_ratio(U_datum_0, U_datum_1)\n\nprint(log_ratio_0_1)\n\nU_datum_2 = U_model[2][None,]\nU_datum_5 = U_model[5][None,]\n\nlog_ratio_2_5 = better_classifier.model.calc_same_diff_log_likelihood_ratio(U_datum_2, U_datum_5)\n\nprint(log_ratio_2_5)\n\nn_examples = 4\nfig, ax_arr = plt.subplots(int(n_examples / 2), 2, figsize=(5, 7.5))\n\nfor x, ax in enumerate(ax_arr.flat):\n ax.imshow(testing_data[[0, 1, 2, 5]][x].reshape(28, 28), cmap='gray')\n ax.set_xticks([])\n ax.set_yticks([])\n\n xlabel = 'Truth: {}'\n ax.set_xlabel(xlabel.format(testing_labels[[0, 1, 2, 5]][x]))\n \nax_arr[0, 0].set_title(\"logRatio = {}\".format(round(log_ratio_0_1, 4)),\n fontsize=16)\nax_arr[1, 0].set_title(\"logRatio = {}\".format(round(log_ratio_2_5, 4)),\n fontsize=16)\n\nfig.suptitle(\"Positive logRatio: Same category.\\nNegative logRatio: Different categories.\",\n x=.5, y=.99, fontsize=16)\n\nfig.tight_layout()", "Getting PCA Preprocessing information", "type(better_classifier.model.pca) # Check out the sklean documentation.\n\nbetter_classifier.model.pca\n\nbetter_classifier.model.pca.n_features_ # Original dimensionality.\n\nbetter_classifier.model.pca.n_components # Preprocessed dimensionality", "Parameters fitted via Empirical Bayes.\nThis is like maximum likelihood estimation in that you are estimating the parameters of your prior using data. Yes, I know this bugs a lot of statisticians, lol.", "Psi = better_classifier.model.Psi\nA = better_classifier.model.A\ninv_A = better_classifier.model.inv_A\nm = better_classifier.model.m\n\n# Indices of the subspace used for classification.\nrelevant_U_dims = better_classifier.model.relevant_U_dims", "Prior.", "better_classifier.model.prior_params.keys()", "Posterior", "better_classifier.model.posterior_params.keys()\n\n# Posterior parameters for a category.\nbetter_classifier.model.posterior_params[0].keys()", "Posterior Predictive", "# Categories in the training data.\nbetter_classifier.model.posterior_predictive_params.keys()\n\n# Parameters for a category.\nbetter_classifier.model.posterior_predictive_params[0].keys()" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
statsmodels/statsmodels.github.io
v0.12.2/examples/notebooks/generated/statespace_dfm_coincident.ipynb
bsd-3-clause
[ "Dynamic factors and coincident indices\nFactor models generally try to find a small number of unobserved \"factors\" that influence a substantial portion of the variation in a larger number of observed variables, and they are related to dimension-reduction techniques such as principal components analysis. Dynamic factor models explicitly model the transition dynamics of the unobserved factors, and so are often applied to time-series data.\nMacroeconomic coincident indices are designed to capture the common component of the \"business cycle\"; such a component is assumed to simultaneously affect many macroeconomic variables. Although the estimation and use of coincident indices (for example the Index of Coincident Economic Indicators) pre-dates dynamic factor models, in several influential papers Stock and Watson (1989, 1991) used a dynamic factor model to provide a theoretical foundation for them.\nBelow, we follow the treatment found in Kim and Nelson (1999), of the Stock and Watson (1991) model, to formulate a dynamic factor model, estimate its parameters via maximum likelihood, and create a coincident index.\nMacroeconomic data\nThe coincident index is created by considering the comovements in four macroeconomic variables (versions of these variables are available on FRED; the ID of the series used below is given in parentheses):\n\nIndustrial production (IPMAN)\nReal aggregate income (excluding transfer payments) (W875RX1)\nManufacturing and trade sales (CMRMTSPL)\nEmployees on non-farm payrolls (PAYEMS)\n\nIn all cases, the data is at the monthly frequency and has been seasonally adjusted; the time-frame considered is 1972 - 2005.", "%matplotlib inline\n\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\n\nnp.set_printoptions(precision=4, suppress=True, linewidth=120)\n\nfrom pandas_datareader.data import DataReader\n\n# Get the datasets from FRED\nstart = '1979-01-01'\nend = '2014-12-01'\nindprod = DataReader('IPMAN', 'fred', start=start, end=end)\nincome = DataReader('W875RX1', 'fred', start=start, end=end)\nsales = DataReader('CMRMTSPL', 'fred', start=start, end=end)\nemp = DataReader('PAYEMS', 'fred', start=start, end=end)\n# dta = pd.concat((indprod, income, sales, emp), axis=1)\n# dta.columns = ['indprod', 'income', 'sales', 'emp']", "Note: in a recent update on FRED (8/12/15) the time series CMRMTSPL was truncated to begin in 1997; this is probably a mistake due to the fact that CMRMTSPL is a spliced series, so the earlier period is from the series HMRMT and the latter period is defined by CMRMT.\nThis has since (02/11/16) been corrected, however the series could also be constructed by hand from HMRMT and CMRMT, as shown below (process taken from the notes in the Alfred xls file).", "# HMRMT = DataReader('HMRMT', 'fred', start='1967-01-01', end=end)\n# CMRMT = DataReader('CMRMT', 'fred', start='1997-01-01', end=end)\n\n# HMRMT_growth = HMRMT.diff() / HMRMT.shift()\n# sales = pd.Series(np.zeros(emp.shape[0]), index=emp.index)\n\n# # Fill in the recent entries (1997 onwards)\n# sales[CMRMT.index] = CMRMT\n\n# # Backfill the previous entries (pre 1997)\n# idx = sales.loc[:'1997-01-01'].index\n# for t in range(len(idx)-1, 0, -1):\n# month = idx[t]\n# prev_month = idx[t-1]\n# sales.loc[prev_month] = sales.loc[month] / (1 + HMRMT_growth.loc[prev_month].values)\n\ndta = pd.concat((indprod, income, sales, emp), axis=1)\ndta.columns = ['indprod', 'income', 'sales', 'emp']\ndta.index.freq = dta.index.inferred_freq\n\ndta.loc[:, 'indprod':'emp'].plot(subplots=True, layout=(2, 2), figsize=(15, 6));", "Stock and Watson (1991) report that for their datasets, they could not reject the null hypothesis of a unit root in each series (so the series are integrated), but they did not find strong evidence that the series were co-integrated.\nAs a result, they suggest estimating the model using the first differences (of the logs) of the variables, demeaned and standardized.", "# Create log-differenced series\ndta['dln_indprod'] = (np.log(dta.indprod)).diff() * 100\ndta['dln_income'] = (np.log(dta.income)).diff() * 100\ndta['dln_sales'] = (np.log(dta.sales)).diff() * 100\ndta['dln_emp'] = (np.log(dta.emp)).diff() * 100\n\n# De-mean and standardize\ndta['std_indprod'] = (dta['dln_indprod'] - dta['dln_indprod'].mean()) / dta['dln_indprod'].std()\ndta['std_income'] = (dta['dln_income'] - dta['dln_income'].mean()) / dta['dln_income'].std()\ndta['std_sales'] = (dta['dln_sales'] - dta['dln_sales'].mean()) / dta['dln_sales'].std()\ndta['std_emp'] = (dta['dln_emp'] - dta['dln_emp'].mean()) / dta['dln_emp'].std()", "Dynamic factors\nA general dynamic factor model is written as:\n$$\n\\begin{align}\ny_t & = \\Lambda f_t + B x_t + u_t \\\nf_t & = A_1 f_{t-1} + \\dots + A_p f_{t-p} + \\eta_t \\qquad \\eta_t \\sim N(0, I)\\\nu_t & = C_1 u_{t-1} + \\dots + C_q u_{t-q} + \\varepsilon_t \\qquad \\varepsilon_t \\sim N(0, \\Sigma)\n\\end{align}\n$$\nwhere $y_t$ are observed data, $f_t$ are the unobserved factors (evolving as a vector autoregression), $x_t$ are (optional) exogenous variables, and $u_t$ is the error, or \"idiosyncratic\", process ($u_t$ is also optionally allowed to be autocorrelated). The $\\Lambda$ matrix is often referred to as the matrix of \"factor loadings\". The variance of the factor error term is set to the identity matrix to ensure identification of the unobserved factors.\nThis model can be cast into state space form, and the unobserved factor estimated via the Kalman filter. The likelihood can be evaluated as a byproduct of the filtering recursions, and maximum likelihood estimation used to estimate the parameters.\nModel specification\nThe specific dynamic factor model in this application has 1 unobserved factor which is assumed to follow an AR(2) process. The innovations $\\varepsilon_t$ are assumed to be independent (so that $\\Sigma$ is a diagonal matrix) and the error term associated with each equation, $u_{i,t}$ is assumed to follow an independent AR(2) process.\nThus the specification considered here is:\n$$\n\\begin{align}\ny_{i,t} & = \\lambda_i f_t + u_{i,t} \\\nu_{i,t} & = c_{i,1} u_{1,t-1} + c_{i,2} u_{i,t-2} + \\varepsilon_{i,t} \\qquad & \\varepsilon_{i,t} \\sim N(0, \\sigma_i^2) \\\nf_t & = a_1 f_{t-1} + a_2 f_{t-2} + \\eta_t \\qquad & \\eta_t \\sim N(0, I)\\\n\\end{align}\n$$\nwhere $i$ is one of: [indprod, income, sales, emp ].\nThis model can be formulated using the DynamicFactor model built-in to statsmodels. In particular, we have the following specification:\n\nk_factors = 1 - (there is 1 unobserved factor)\nfactor_order = 2 - (it follows an AR(2) process)\nerror_var = False - (the errors evolve as independent AR processes rather than jointly as a VAR - note that this is the default option, so it is not specified below)\nerror_order = 2 - (the errors are autocorrelated of order 2: i.e. AR(2) processes)\nerror_cov_type = 'diagonal' - (the innovations are uncorrelated; this is again the default)\n\nOnce the model is created, the parameters can be estimated via maximum likelihood; this is done using the fit() method.\nNote: recall that we have demeaned and standardized the data; this will be important in interpreting the results that follow.\nAside: in their empirical example, Kim and Nelson (1999) actually consider a slightly different model in which the employment variable is allowed to also depend on lagged values of the factor - this model does not fit into the built-in DynamicFactor class, but can be accommodated by using a subclass to implement the required new parameters and restrictions - see Appendix A, below.\nParameter estimation\nMultivariate models can have a relatively large number of parameters, and it may be difficult to escape from local minima to find the maximized likelihood. In an attempt to mitigate this problem, I perform an initial maximization step (from the model-defined starting parameters) using the modified Powell method available in Scipy (see the minimize documentation for more information). The resulting parameters are then used as starting parameters in the standard LBFGS optimization method.", "# Get the endogenous data\nendog = dta.loc['1979-02-01':, 'std_indprod':'std_emp']\n\n# Create the model\nmod = sm.tsa.DynamicFactor(endog, k_factors=1, factor_order=2, error_order=2)\ninitial_res = mod.fit(method='powell', disp=False)\nres = mod.fit(initial_res.params, disp=False)", "Estimates\nOnce the model has been estimated, there are two components that we can use for analysis or inference:\n\nThe estimated parameters\nThe estimated factor\n\nParameters\nThe estimated parameters can be helpful in understanding the implications of the model, although in models with a larger number of observed variables and / or unobserved factors they can be difficult to interpret.\nOne reason for this difficulty is due to identification issues between the factor loadings and the unobserved factors. One easy-to-see identification issue is the sign of the loadings and the factors: an equivalent model to the one displayed below would result from reversing the signs of all factor loadings and the unobserved factor.\nHere, one of the easy-to-interpret implications in this model is the persistence of the unobserved factor: we find that exhibits substantial persistence.", "print(res.summary(separate_params=False))", "Estimated factors\nWhile it can be useful to plot the unobserved factors, it is less useful here than one might think for two reasons:\n\nThe sign-related identification issue described above.\nSince the data was differenced, the estimated factor explains the variation in the differenced data, not the original data.\n\nIt is for these reasons that the coincident index is created (see below).\nWith these reservations, the unobserved factor is plotted below, along with the NBER indicators for US recessions. It appears that the factor is successful at picking up some degree of business cycle activity.", "fig, ax = plt.subplots(figsize=(13,3))\n\n# Plot the factor\ndates = endog.index._mpl_repr()\nax.plot(dates, res.factors.filtered[0], label='Factor')\nax.legend()\n\n# Retrieve and also plot the NBER recession indicators\nrec = DataReader('USREC', 'fred', start=start, end=end)\nylim = ax.get_ylim()\nax.fill_between(dates[:-3], ylim[0], ylim[1], rec.values[:-4,0], facecolor='k', alpha=0.1);", "Post-estimation\nAlthough here we will be able to interpret the results of the model by constructing the coincident index, there is a useful and generic approach for getting a sense for what is being captured by the estimated factor. By taking the estimated factors as given, regressing them (and a constant) each (one at a time) on each of the observed variables, and recording the coefficients of determination ($R^2$ values), we can get a sense of the variables for which each factor explains a substantial portion of the variance and the variables for which it does not.\nIn models with more variables and more factors, this can sometimes lend interpretation to the factors (for example sometimes one factor will load primarily on real variables and another on nominal variables).\nIn this model, with only four endogenous variables and one factor, it is easy to digest a simple table of the $R^2$ values, but in larger models it is not. For this reason, a bar plot is often employed; from the plot we can easily see that the factor explains most of the variation in industrial production index and a large portion of the variation in sales and employment, it is less helpful in explaining income.", "res.plot_coefficients_of_determination(figsize=(8,2));", "Coincident Index\nAs described above, the goal of this model was to create an interpretable series which could be used to understand the current status of the macroeconomy. This is what the coincident index is designed to do. It is constructed below. For readers interested in an explanation of the construction, see Kim and Nelson (1999) or Stock and Watson (1991).\nIn essence, what is done is to reconstruct the mean of the (differenced) factor. We will compare it to the coincident index on published by the Federal Reserve Bank of Philadelphia (USPHCI on FRED).", "usphci = DataReader('USPHCI', 'fred', start='1979-01-01', end='2014-12-01')['USPHCI']\nusphci.plot(figsize=(13,3));\n\ndusphci = usphci.diff()[1:].values\ndef compute_coincident_index(mod, res):\n # Estimate W(1)\n spec = res.specification\n design = mod.ssm['design']\n transition = mod.ssm['transition']\n ss_kalman_gain = res.filter_results.kalman_gain[:,:,-1]\n k_states = ss_kalman_gain.shape[0]\n\n W1 = np.linalg.inv(np.eye(k_states) - np.dot(\n np.eye(k_states) - np.dot(ss_kalman_gain, design),\n transition\n )).dot(ss_kalman_gain)[0]\n\n # Compute the factor mean vector\n factor_mean = np.dot(W1, dta.loc['1972-02-01':, 'dln_indprod':'dln_emp'].mean())\n \n # Normalize the factors\n factor = res.factors.filtered[0]\n factor *= np.std(usphci.diff()[1:]) / np.std(factor)\n\n # Compute the coincident index\n coincident_index = np.zeros(mod.nobs+1)\n # The initial value is arbitrary; here it is set to\n # facilitate comparison\n coincident_index[0] = usphci.iloc[0] * factor_mean / dusphci.mean()\n for t in range(0, mod.nobs):\n coincident_index[t+1] = coincident_index[t] + factor[t] + factor_mean\n \n # Attach dates\n coincident_index = pd.Series(coincident_index, index=dta.index).iloc[1:]\n \n # Normalize to use the same base year as USPHCI\n coincident_index *= (usphci.loc['1992-07-01'] / coincident_index.loc['1992-07-01'])\n \n return coincident_index", "Below we plot the calculated coincident index along with the US recessions and the comparison coincident index USPHCI.", "fig, ax = plt.subplots(figsize=(13,3))\n\n# Compute the index\ncoincident_index = compute_coincident_index(mod, res)\n\n# Plot the factor\ndates = endog.index._mpl_repr()\nax.plot(dates, coincident_index, label='Coincident index')\nax.plot(usphci.index._mpl_repr(), usphci, label='USPHCI')\nax.legend(loc='lower right')\n\n# Retrieve and also plot the NBER recession indicators\nylim = ax.get_ylim()\nax.fill_between(dates[:-3], ylim[0], ylim[1], rec.values[:-4,0], facecolor='k', alpha=0.1);", "Appendix 1: Extending the dynamic factor model\nRecall that the previous specification was described by:\n$$\n\\begin{align}\ny_{i,t} & = \\lambda_i f_t + u_{i,t} \\\nu_{i,t} & = c_{i,1} u_{1,t-1} + c_{i,2} u_{i,t-2} + \\varepsilon_{i,t} \\qquad & \\varepsilon_{i,t} \\sim N(0, \\sigma_i^2) \\\nf_t & = a_1 f_{t-1} + a_2 f_{t-2} + \\eta_t \\qquad & \\eta_t \\sim N(0, I)\\\n\\end{align}\n$$\nWritten in state space form, the previous specification of the model had the following observation equation:\n$$\n\\begin{bmatrix}\ny_{\\text{indprod}, t} \\\ny_{\\text{income}, t} \\\ny_{\\text{sales}, t} \\\ny_{\\text{emp}, t} \\\n\\end{bmatrix} = \\begin{bmatrix}\n\\lambda_\\text{indprod} & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\n\\lambda_\\text{income} & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\n\\lambda_\\text{sales} & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\\n\\lambda_\\text{emp} & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\\n\\end{bmatrix}\n\\begin{bmatrix}\nf_t \\\nf_{t-1} \\\nu_{\\text{indprod}, t} \\\nu_{\\text{income}, t} \\\nu_{\\text{sales}, t} \\\nu_{\\text{emp}, t} \\\nu_{\\text{indprod}, t-1} \\\nu_{\\text{income}, t-1} \\\nu_{\\text{sales}, t-1} \\\nu_{\\text{emp}, t-1} \\\n\\end{bmatrix}\n$$\nand transition equation:\n$$\n\\begin{bmatrix}\nf_t \\\nf_{t-1} \\\nu_{\\text{indprod}, t} \\\nu_{\\text{income}, t} \\\nu_{\\text{sales}, t} \\\nu_{\\text{emp}, t} \\\nu_{\\text{indprod}, t-1} \\\nu_{\\text{income}, t-1} \\\nu_{\\text{sales}, t-1} \\\nu_{\\text{emp}, t-1} \\\n\\end{bmatrix} = \\begin{bmatrix}\na_1 & a_2 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\n1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\n0 & 0 & c_{\\text{indprod}, 1} & 0 & 0 & 0 & c_{\\text{indprod}, 2} & 0 & 0 & 0 \\\n0 & 0 & 0 & c_{\\text{income}, 1} & 0 & 0 & 0 & c_{\\text{income}, 2} & 0 & 0 \\\n0 & 0 & 0 & 0 & c_{\\text{sales}, 1} & 0 & 0 & 0 & c_{\\text{sales}, 2} & 0 \\\n0 & 0 & 0 & 0 & 0 & c_{\\text{emp}, 1} & 0 & 0 & 0 & c_{\\text{emp}, 2} \\\n0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\n0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\n0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\\n0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\\n\\end{bmatrix} \n\\begin{bmatrix}\nf_{t-1} \\\nf_{t-2} \\\nu_{\\text{indprod}, t-1} \\\nu_{\\text{income}, t-1} \\\nu_{\\text{sales}, t-1} \\\nu_{\\text{emp}, t-1} \\\nu_{\\text{indprod}, t-2} \\\nu_{\\text{income}, t-2} \\\nu_{\\text{sales}, t-2} \\\nu_{\\text{emp}, t-2} \\\n\\end{bmatrix}\n+ R \\begin{bmatrix}\n\\eta_t \\\n\\varepsilon_{t}\n\\end{bmatrix}\n$$\nthe DynamicFactor model handles setting up the state space representation and, in the DynamicFactor.update method, it fills in the fitted parameter values into the appropriate locations.\nThe extended specification is the same as in the previous example, except that we also want to allow employment to depend on lagged values of the factor. This creates a change to the $y_{\\text{emp},t}$ equation. Now we have:\n$$\n\\begin{align}\ny_{i,t} & = \\lambda_i f_t + u_{i,t} \\qquad & i \\in {\\text{indprod}, \\text{income}, \\text{sales} }\\\ny_{i,t} & = \\lambda_{i,0} f_t + \\lambda_{i,1} f_{t-1} + \\lambda_{i,2} f_{t-2} + \\lambda_{i,2} f_{t-3} + u_{i,t} \\qquad & i = \\text{emp} \\\nu_{i,t} & = c_{i,1} u_{i,t-1} + c_{i,2} u_{i,t-2} + \\varepsilon_{i,t} \\qquad & \\varepsilon_{i,t} \\sim N(0, \\sigma_i^2) \\\nf_t & = a_1 f_{t-1} + a_2 f_{t-2} + \\eta_t \\qquad & \\eta_t \\sim N(0, I)\\\n\\end{align}\n$$\nNow, the corresponding observation equation should look like the following:\n$$\n\\begin{bmatrix}\ny_{\\text{indprod}, t} \\\ny_{\\text{income}, t} \\\ny_{\\text{sales}, t} \\\ny_{\\text{emp}, t} \\\n\\end{bmatrix} = \\begin{bmatrix}\n\\lambda_\\text{indprod} & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\n\\lambda_\\text{income} & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\n\\lambda_\\text{sales} & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\\n\\lambda_\\text{emp,1} & \\lambda_\\text{emp,2} & \\lambda_\\text{emp,3} & \\lambda_\\text{emp,4} & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\\n\\end{bmatrix}\n\\begin{bmatrix}\nf_t \\\nf_{t-1} \\\nf_{t-2} \\\nf_{t-3} \\\nu_{\\text{indprod}, t} \\\nu_{\\text{income}, t} \\\nu_{\\text{sales}, t} \\\nu_{\\text{emp}, t} \\\nu_{\\text{indprod}, t-1} \\\nu_{\\text{income}, t-1} \\\nu_{\\text{sales}, t-1} \\\nu_{\\text{emp}, t-1} \\\n\\end{bmatrix}\n$$\nNotice that we have introduced two new state variables, $f_{t-2}$ and $f_{t-3}$, which means we need to update the transition equation:\n$$\n\\begin{bmatrix}\nf_t \\\nf_{t-1} \\\nf_{t-2} \\\nf_{t-3} \\\nu_{\\text{indprod}, t} \\\nu_{\\text{income}, t} \\\nu_{\\text{sales}, t} \\\nu_{\\text{emp}, t} \\\nu_{\\text{indprod}, t-1} \\\nu_{\\text{income}, t-1} \\\nu_{\\text{sales}, t-1} \\\nu_{\\text{emp}, t-1} \\\n\\end{bmatrix} = \\begin{bmatrix}\na_1 & a_2 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\n1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\n0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\n0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\n0 & 0 & 0 & 0 & c_{\\text{indprod}, 1} & 0 & 0 & 0 & c_{\\text{indprod}, 2} & 0 & 0 & 0 \\\n0 & 0 & 0 & 0 & 0 & c_{\\text{income}, 1} & 0 & 0 & 0 & c_{\\text{income}, 2} & 0 & 0 \\\n0 & 0 & 0 & 0 & 0 & 0 & c_{\\text{sales}, 1} & 0 & 0 & 0 & c_{\\text{sales}, 2} & 0 \\\n0 & 0 & 0 & 0 & 0 & 0 & 0 & c_{\\text{emp}, 1} & 0 & 0 & 0 & c_{\\text{emp}, 2} \\\n0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\n0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\n0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\\n0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\\n\\end{bmatrix} \n\\begin{bmatrix}\nf_{t-1} \\\nf_{t-2} \\\nf_{t-3} \\\nf_{t-4} \\\nu_{\\text{indprod}, t-1} \\\nu_{\\text{income}, t-1} \\\nu_{\\text{sales}, t-1} \\\nu_{\\text{emp}, t-1} \\\nu_{\\text{indprod}, t-2} \\\nu_{\\text{income}, t-2} \\\nu_{\\text{sales}, t-2} \\\nu_{\\text{emp}, t-2} \\\n\\end{bmatrix}\n+ R \\begin{bmatrix}\n\\eta_t \\\n\\varepsilon_{t}\n\\end{bmatrix}\n$$\nThis model cannot be handled out-of-the-box by the DynamicFactor class, but it can be handled by creating a subclass when alters the state space representation in the appropriate way.\nFirst, notice that if we had set factor_order = 4, we would almost have what we wanted. In that case, the last line of the observation equation would be:\n$$\n\\begin{bmatrix}\n\\vdots \\\ny_{\\text{emp}, t} \\\n\\end{bmatrix} = \\begin{bmatrix}\n\\vdots & & & & & & & & & & & \\vdots \\\n\\lambda_\\text{emp,1} & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\\n\\end{bmatrix}\n\\begin{bmatrix}\nf_t \\\nf_{t-1} \\\nf_{t-2} \\\nf_{t-3} \\\n\\vdots\n\\end{bmatrix}\n$$\nand the first line of the transition equation would be:\n$$\n\\begin{bmatrix}\nf_t \\\n\\vdots\n\\end{bmatrix} = \\begin{bmatrix}\na_1 & a_2 & a_3 & a_4 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\n\\vdots & & & & & & & & & & & \\vdots \\\n\\end{bmatrix} \n\\begin{bmatrix}\nf_{t-1} \\\nf_{t-2} \\\nf_{t-3} \\\nf_{t-4} \\\n\\vdots\n\\end{bmatrix}\n+ R \\begin{bmatrix}\n\\eta_t \\\n\\varepsilon_{t}\n\\end{bmatrix}\n$$\nRelative to what we want, we have the following differences:\n\nIn the above situation, the $\\lambda_{\\text{emp}, j}$ are forced to be zero for $j > 0$, and we want them to be estimated as parameters.\nWe only want the factor to transition according to an AR(2), but under the above situation it is an AR(4).\n\nOur strategy will be to subclass DynamicFactor, and let it do most of the work (setting up the state space representation, etc.) where it assumes that factor_order = 4. The only things we will actually do in the subclass will be to fix those two issues.\nFirst, here is the full code of the subclass; it is discussed below. It is important to note at the outset that none of the methods defined below could have been omitted. In fact, the methods __init__, start_params, param_names, transform_params, untransform_params, and update form the core of all state space models in statsmodels, not just the DynamicFactor class.", "from statsmodels.tsa.statespace import tools\nclass ExtendedDFM(sm.tsa.DynamicFactor):\n def __init__(self, endog, **kwargs):\n # Setup the model as if we had a factor order of 4\n super(ExtendedDFM, self).__init__(\n endog, k_factors=1, factor_order=4, error_order=2,\n **kwargs)\n\n # Note: `self.parameters` is an ordered dict with the\n # keys corresponding to parameter types, and the values\n # the number of parameters of that type.\n # Add the new parameters\n self.parameters['new_loadings'] = 3\n\n # Cache a slice for the location of the 4 factor AR\n # parameters (a_1, ..., a_4) in the full parameter vector\n offset = (self.parameters['factor_loadings'] +\n self.parameters['exog'] +\n self.parameters['error_cov'])\n self._params_factor_ar = np.s_[offset:offset+2]\n self._params_factor_zero = np.s_[offset+2:offset+4]\n\n @property\n def start_params(self):\n # Add three new loading parameters to the end of the parameter\n # vector, initialized to zeros (for simplicity; they could\n # be initialized any way you like)\n return np.r_[super(ExtendedDFM, self).start_params, 0, 0, 0]\n \n @property\n def param_names(self):\n # Add the corresponding names for the new loading parameters\n # (the name can be anything you like)\n return super(ExtendedDFM, self).param_names + [\n 'loading.L%d.f1.%s' % (i, self.endog_names[3]) for i in range(1,4)]\n\n def transform_params(self, unconstrained):\n # Perform the typical DFM transformation (w/o the new parameters)\n constrained = super(ExtendedDFM, self).transform_params(\n unconstrained[:-3])\n\n # Redo the factor AR constraint, since we only want an AR(2),\n # and the previous constraint was for an AR(4)\n ar_params = unconstrained[self._params_factor_ar]\n constrained[self._params_factor_ar] = (\n tools.constrain_stationary_univariate(ar_params))\n\n # Return all the parameters\n return np.r_[constrained, unconstrained[-3:]]\n\n def untransform_params(self, constrained):\n # Perform the typical DFM untransformation (w/o the new parameters)\n unconstrained = super(ExtendedDFM, self).untransform_params(\n constrained[:-3])\n\n # Redo the factor AR unconstrained, since we only want an AR(2),\n # and the previous unconstrained was for an AR(4)\n ar_params = constrained[self._params_factor_ar]\n unconstrained[self._params_factor_ar] = (\n tools.unconstrain_stationary_univariate(ar_params))\n\n # Return all the parameters\n return np.r_[unconstrained, constrained[-3:]]\n\n def update(self, params, transformed=True, **kwargs):\n # Peform the transformation, if required\n if not transformed:\n params = self.transform_params(params)\n params[self._params_factor_zero] = 0\n \n # Now perform the usual DFM update, but exclude our new parameters\n super(ExtendedDFM, self).update(params[:-3], transformed=True, **kwargs)\n\n # Finally, set our new parameters in the design matrix\n self.ssm['design', 3, 1:4] = params[-3:]\n ", "So what did we just do?\n__init__\nThe important step here was specifying the base dynamic factor model which we were operating with. In particular, as described above, we initialize with factor_order=4, even though we will only end up with an AR(2) model for the factor. We also performed some general setup-related tasks.\nstart_params\nstart_params are used as initial values in the optimizer. Since we are adding three new parameters, we need to pass those in. If we had not done this, the optimizer would use the default starting values, which would be three elements short.\nparam_names\nparam_names are used in a variety of places, but especially in the results class. Below we get a full result summary, which is only possible when all the parameters have associated names.\ntransform_params and untransform_params\nThe optimizer selects possibly parameter values in an unconstrained way. That's not usually desired (since variances cannot be negative, for example), and transform_params is used to transform the unconstrained values used by the optimizer to constrained values appropriate to the model. Variances terms are typically squared (to force them to be positive), and AR lag coefficients are often constrained to lead to a stationary model. untransform_params is used for the reverse operation (and is important because starting parameters are usually specified in terms of values appropriate to the model, and we need to convert them to parameters appropriate to the optimizer before we can begin the optimization routine).\nEven though we do not need to transform or untransform our new parameters (the loadings can in theory take on any values), we still need to modify this function for two reasons:\n\nThe version in the DynamicFactor class is expecting 3 fewer parameters than we have now. At a minimum, we need to handle the three new parameters.\nThe version in the DynamicFactor class constrains the factor lag coefficients to be stationary as though it was an AR(4) model. Since we actually have an AR(2) model, we need to re-do the constraint. We also set the last two autoregressive coefficients to be zero here.\n\nupdate\nThe most important reason we need to specify a new update method is because we have three new parameters that we need to place into the state space formulation. In particular we let the parent DynamicFactor.update class handle placing all the parameters except the three new ones in to the state space representation, and then we put the last three in manually.", "# Create the model\nextended_mod = ExtendedDFM(endog)\ninitial_extended_res = extended_mod.fit(maxiter=1000, disp=False)\nextended_res = extended_mod.fit(initial_extended_res.params, method='nm', maxiter=1000)\nprint(extended_res.summary(separate_params=False))", "Although this model increases the likelihood, it is not preferred by the AIC and BIC measures which penalize the additional three parameters.\nFurthermore, the qualitative results are unchanged, as we can see from the updated $R^2$ chart and the new coincident index, both of which are practically identical to the previous results.", "extended_res.plot_coefficients_of_determination(figsize=(8,2));\n\nfig, ax = plt.subplots(figsize=(13,3))\n\n# Compute the index\nextended_coincident_index = compute_coincident_index(extended_mod, extended_res)\n\n# Plot the factor\ndates = endog.index._mpl_repr()\nax.plot(dates, coincident_index, '-', linewidth=1, label='Basic model')\nax.plot(dates, extended_coincident_index, '--', linewidth=3, label='Extended model')\nax.plot(usphci.index._mpl_repr(), usphci, label='USPHCI')\nax.legend(loc='lower right')\nax.set(title='Coincident indices, comparison')\n\n# Retrieve and also plot the NBER recession indicators\nylim = ax.get_ylim()\nax.fill_between(dates[:-3], ylim[0], ylim[1], rec.values[:-4,0], facecolor='k', alpha=0.1);" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
rpmunoz/topicos_ingenieria_1
clase_1/01 - Introduccion a Python.ipynb
gpl-3.0
[ "Introducción a Python\nAutor: Roberto Muñoz <br />\nE-mail: &#114;&#109;&#117;&#110;&#111;&#122;&#64;&#117;&#99;&#46;&#99;&#108;\nPython es un lenguaje de programación que fue desarrollado por Guido van Rossum y distribuido como código abierto. Se puede descargar gratuitamente desde internet e instalar en cualquier computador. En este curso usaremos la versión distribuida por Anaconda.\nEn el lenguaje Python, así como en la mayoría de lenguajes de programación, hay distintos tipos de variables: números enteros (\"ints\", del inglés integer, o entero), números racionales (\"float\", del inglés floating point, punto flotante), palabras y cadenas de caracteres (\"strings\" o cadenas), entre otras. Nosotros usaremos principalmente números, tanto int como float.\nEn la siguientes líneas vamos a \"declarar\" una variable, o sea, asignarle un valor, y luego realizaremos operaciones básicas. Las líneas que comienzan con \"#\" Python las considera como comentarios, y no las ejecuta, pero están ahí para hacer más legible el código. El comando print permite mostrar en pantalla tanto texto como valores de variables, siempre y cuando los elementos a mostrar estén separados por comas. El texto en Python siempre se representa con comillas, simples o dobles.", "# primero inicializamos las variables a y b\na = 2\nb = 3.5\n\n# verificamos los valores y aplicamos operaciones simples\nprint(\"a = \",a)\nprint(\"b = \",b)\n\nc = a + b\nprint(c)\nprint(\"suma de a + b = \",c)\nd = a * b\nprint(\"multiplicación de a * b = \",d)\ne = a ** b\n# el signo \"**\" representa \"elevar a\"\nprint(\"a elevado a b = \",e)\nf = b / a\nprint(\"b dividido por a = \",f)", "Otro tipo de variable muy importante son los arreglos, que pueden ser visto como una cadena de variables. Los arreglos se declaran por medio de corchetes, y sus elementos deben ir separados por comas. Por ejemplo, creemos el arreglo con los dígitos del 0 al 9:", "a = [0,1,2,3,4,5,6,7,8,9]\nprint(a)", "En vez de usar líneas de código como la anterior, o más largas, podemos usar funciones. Una función es una línea de texto que ejecuta código más largo \"detrás de la cortina\". Una manera rápida de crear arreglos es por medio de la función range, que acá usamos para generar el arreglo a más rápida y brevemente. En los siguientes ejemplos se muestra como usar esta función para crear listas de números equidistantes:", "a=range(10)\nb=range(9,20)\nc=range(-5,15,2)\nprint(a)\nprint(b)\nprint(c)", "Vemos que escribiendo range(10) el resultado es el mismo que [0,1,2,3,4,5,6,7,8,9], pero fuimos mucho más breves. La función range es muy útil, pero no muy versátil. ¿Qué pasa si queremos crear números espaciados por 0.1?", "a=range(1,10,0.1)", "Vemos que Python lanza un error: la función range no puede correr cuando alguno de sus argumentos (valor que define lo que una función va a hacer) no es entero. Para hacer esto, necesitamos usar pedazos de código que no están incluidos por defecto en Python, los llamados paquetes. La siguiente línea importa uno de los paquetes más famosos y usados de Python: NumPy, que es muy útil para hacer cálculos rápidos, sobre todo con arreglos. Lo que la siguiente línea hace es decir que usaremos todo lo incluido en el paquete numpy bajo el \"alias\" np, para escribir menos en nuestros códigos.", "import numpy as np", "La función arange de numpy nos permite hacer lo mismo que range, pero puede recibir números no enteros en cualquiera de sus argumentos. Como esta función está dentro del paquete numpy, debemos llamarla antecediendo \"np.\" (o cualquier alias que hayamos usado) a su nombre. Veamos algunos ejemplos:", "a=np.sin(np.pi/2)\nprint(a)\n\na=np.arange(1,10,0.1)\nb=np.arange(-5,2,1.2)\nprint(a)\nprint(b)", "Importante recordar: Al igual que range, la función arange no llega hasta el valor \"final\" dado como argumento en la función.\nEl paquete numpy contiene todas las operaciones matemáticas que nosotros necesitamos para el curso y para la vida. Cuando estas operaciones son aplicadas a un arreglo, se aplican a todos los elementos de un arreglo. A continuación, algunos ejemplos:", "a=np.arange(0,10,0.5)\nb=np.sin(a) # seno de a\nprint(b)\nc=np.sqrt(a) # raíz de a, del inglés \"square root\"\nprint(c)\nd=np.power(a,2) # elevar cada elemento del arreglo a, a la segunda potencia\nprint(d)", "Escribir np.sqrt(a) es mucho más breve que la alternativa: calcular una a una las raíces cuadradas de cada elemento de a. No se preocupe de entender el siguiente código, sólo note que es bastante más complicado que hacerlo con numpy, y se llega al mismo resultado:", "c2 = []\nfor el in a:\n c2.append(el**0.5)\nprint(\"manera larga = \",c2)\nprint(\"con numpy = \",c)", "La única diferencia es el número de decimales que se muestran.\n¿Cómo verificar gráficamente si numpy está haciendo bien las cosas? Existe otro paquete de python que permite hacer visualización de datos, matplotlib. Estos dos paquetes permiten hacer maravillas. La siguiente línea importa el paquete matplotlib.pyplot (parte dedicada a graficar) con el alias plt, mientras que la segunda permite ver las figuras graficadas dentro de este mismo navegador, en vez de abrirlas en otra ventana.", "import matplotlib.pyplot as plt\n%matplotlib inline", "Para graficar en las dos dimensiones de un plano cartesiano, sólo necesitamos decirle a la función plot de matplotlib los valores de x e y que queremos graficar, muy intuitivo. Por supuesto, estos dos arreglos deben tener la misma dimensión, o sea, el mismo número de elementos. Una vez que el gráfico se genera, no se muestra automáticamente. Para eso, usamos la función show de matplotlib, como muestra el siguiente ejemplo. Como se imaginarán, todos los nombres de funciones están basados en palabras en inglés: plot significa \"graficar\", show significa \"mostrar\".", "plt.plot(a,10*b, c=\"blue\") # en azul\nplt.plot(a,5*c, c=\"green\") # en verde\nplt.plot(a,d, c=\"red\") # en rojo\nplt.show()", "Ejercicio 1\nGenere un arreglo x con números desde el -5 hasta el 10 con separación de 0.2, y un arreglo y desde 0 a 15, con separación de 0.2, y grafique x vérsus y. ¿Qué espera obtener?", "# escriba el código acá\n", "Ejercicio 2\nA continuación, están definidos dos arreglos que contienen información de los ocho planetas del Sistema Solar, desde Mercurio, hasta Neptuno, además de incluir información de Plutón (ahora considerado planetoide en vez de planeta). El primero, p, contiene el periodo de cada planeta en años, mientras que el segundo, a, contiene el tamaño de la órbita en unidades astronómicas. Con estos datos, usted construirá un gráfico en dos dimensiones, como los de los ejemplos superiores, con los que comprobará experimentalmente la 3era ley de Kepler, cuya forma matemática dice $p = a^k$, con $k$ una constante (no necesariamente entera) que ud. debe determinar tras ensayo y error. Para eso, grafique los arreglos entregados, junto con una curva de la forma $y=x^k$ para distinto valores de $k$, y vea cuál es la que más se acerca. ¿Cuál es el valor de $k$ que usted obtiene?", "p = np.array([0.214,0.615,1,1.88,11.9,29.4,83.7,163.7,247.9])\na = np.array([0.387,0.723,1,1.52,5.2,9.58,19.2,30.05,39.48])\n# escriba acá el resto del código\n", "Ejercicio propuesto 1\nEn el caso de que ud. conozca ya la forma matemática de la 3era ley de Kepler, realice el gráfico de todas maneras, pero antes de la línea plt.show(), introduzca las líneas que se entregan acá abajo. ¿Qué hacen esas líneas? ¿Qué obtiene? ¿Por qué ocurre eso?", "# introduzca estas líneas en el código de la pregunta anterior\nplt.xscale('log')\nplt.yscale('log')\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" ]
kcrandall/Kaggle_Mercedes_Manufacturing
spark/experiements/jingning/Merdes_Benz_Manufacturing_V6.ipynb
mit
[ "# import pacakges\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.base import BaseEstimator,TransformerMixin, ClassifierMixin\nfrom sklearn.linear_model import LassoLarsCV\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.utils import check_array\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom sklearn import decomposition\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.decomposition import PCA, FastICA\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.decomposition import NMF\nfrom sklearn.random_projection import GaussianRandomProjection\nfrom sklearn.random_projection import SparseRandomProjection\nfrom sklearn.metrics import r2_score\nimport xgboost as xgb\nfrom sklearn.grid_search import GridSearchCV\n\n# read data\ntrain = pd.read_csv(\"train.csv\")\ntest = pd.read_csv(\"test.csv\")", "Data Split", "train, valid = train_test_split(train, test_size = 0.2)\nprint(train.shape)\nprint(valid.shape)", "Data Exploration\nNormal distribution check and Transformation", "# plot target variable of train\nplt.figure(figsize=(8,6))\nplt.scatter(range(train.shape[0]), np.sort(train.y.values))\nplt.xlabel('index', fontsize=12)\nplt.ylabel('y', fontsize=12)\nplt.show()\n\n# plot the distribution of target variable of train\nplt.figure(figsize=(12,8))\nsns.distplot(train.y.values, bins=50, kde=False)\nplt.xlabel('y value', fontsize=12)\nplt.show()", "y is right skewed and there exits some noise in y variable", "# try some transformation to y variable for train\n## sqrt root transform\ntrain['y_sqrt'] = np.sqrt(train['y'])\nplt.figure(figsize=(12,8))\nsns.distplot(train.y_sqrt.values, bins=50, kde=False)\nplt.xlabel('y_sqrt value', fontsize=12)\nplt.show()\n\n## log transform\ntrain['y_log'] = np.log(train['y'])\nplt.figure(figsize=(12,8))\nsns.distplot(train.y_log.values, bins=50, kde=False)\nplt.xlabel('y_log value', fontsize=12)\nplt.show()\n\n## square transform\ntrain['y_square'] = np.square(train['y'])\nplt.figure(figsize=(12,8))\nsns.distplot(train.y_square.values, bins=50, kde=False)\nplt.xlabel('y_square value', fontsize=12)\nplt.show()\n\n## reciprocal transform\ntrain['y_reciprocal'] = np.reciprocal(train['y'])\nplt.figure(figsize=(12,8))\nsns.distplot(train.y_reciprocal.values, bins=50, kde=False)\nplt.xlabel('y_reciprocal value', fontsize=12)\nplt.show()\n\n## cube root transform\ntrain['y_cube_root'] = np.cbrt(train['y'])\nplt.figure(figsize=(12,8))\nsns.distplot(train.y_cube_root.values, bins=50, kde=False)\nplt.xlabel('y_cube_root value', fontsize=12)\nplt.show()", "according to the plots, we can see that the better transformation of y in train is reciprocal transformation", "train = train.drop(['y_sqrt', 'y_log', 'y_square','y_cube_root','y'], axis=1)\n\n# plot target variable of valid\nplt.figure(figsize=(8,6))\nplt.scatter(range(valid.shape[0]), np.sort(valid.y.values))\nplt.xlabel('index', fontsize=12)\nplt.ylabel('y', fontsize=12)\nplt.show()\n\n# plot the distribution of target variable of valid\nplt.figure(figsize=(12,8))\nsns.distplot(valid.y.values, bins=50, kde=False)\nplt.xlabel('y value', fontsize=12)\nplt.show()\n\n# try some transformation to y variable for valid\n## sqrt root transform\nvalid['y_sqrt'] = np.sqrt(valid['y'])\nplt.figure(figsize=(12,8))\nsns.distplot(valid.y_sqrt.values, bins=50, kde=False)\nplt.xlabel('y_sqrt value', fontsize=12)\nplt.show()\n\n## log transform\nvalid['y_log'] = np.log(valid['y'])\nplt.figure(figsize=(12,8))\nsns.distplot(valid.y_log.values, bins=50, kde=False)\nplt.xlabel('y_log value', fontsize=12)\nplt.show()\n\n## square transform\nvalid['y_square'] = np.square(valid['y'])\nplt.figure(figsize=(12,8))\nsns.distplot(valid.y_square.values, bins=50, kde=False)\nplt.xlabel('y_square value', fontsize=12)\nplt.show()\n\n## reciprocal transform\nvalid['y_reciprocal'] = np.reciprocal(valid['y'])\nplt.figure(figsize=(12,8))\nsns.distplot(valid.y_reciprocal.values, bins=50, kde=False)\nplt.xlabel('y_reciprocal value', fontsize=12)\nplt.show()\n\n## cube root transform\nvalid['y_cube_root'] = np.cbrt(valid['y'])\nplt.figure(figsize=(12,8))\nsns.distplot(valid.y_cube_root.values, bins=50, kde=False)\nplt.xlabel('y_cube_root value', fontsize=12)\nplt.show()", "according to the plots, we can see that the better transformation of y in valid is reciprocal transformation", "valid = valid.drop(['y_sqrt', 'y_log', 'y_square','y_cube_root', 'y'], axis=1)", "Handle Outliers", "# plot target variable of train after transform \nplt.figure(figsize=(8,6))\nplt.scatter(range(train.shape[0]), np.sort(train.y_reciprocal.values))\nplt.xlabel('index', fontsize=12)\nplt.ylabel('y_reciprocal', fontsize=12)\nplt.show()\n\n # plot target variable of valid after transform \nplt.figure(figsize=(8,6))\nplt.scatter(range(valid.shape[0]), np.sort(valid.y_reciprocal.values))\nplt.xlabel('index', fontsize=12)\nplt.ylabel('y_reciprocal', fontsize=12)\nplt.show()", "Not sure whether need to deal with valid data????\nCheck Multicollinearity\nusing VIF, but stuccked with the import error: TimeSeries cannot be imoported\nEncode Categorical Variales", "for c in train.columns:\n if train[c].dtype == 'object':\n lbl = LabelEncoder()\n lbl.fit(list(train[c].values) + list(valid[c].values) + list(test[c].values))\n train[c] = lbl.transform(list(train[c].values))\n #valid[c] = lbl.transform(list(valid[c].values))\n test[c] = lbl.transform(list(test[c].values))\n\nfor c in valid.columns:\n if valid[c].dtype == 'object':\n lbl = LabelEncoder()\n lbl.fit(list(valid[c].values))\n valid[c] = lbl.transform(list(valid[c].values))\n\ntrain.head()\n\nvalid.head()\n\ntest.head()", "Dimentionality Reduction", "# extract numerical variables \ntrain_x = (train.ix[:,9:377].values).astype('int32')\ntrain_y = train.ix[:,377].values.astype('float32')\nvalid_x = (valid.ix[:,9:377].values).astype('int32')\nvalid_y = valid.ix[:,377].values.astype('float32')\ntest_x = (test.ix[:,9:377].values).astype('int32')\n\n# principal conponent analysis to train\n## PCA decomposition\npca = decomposition.PCA(n_components=200) #Finds first 200 PCs\npca.fit(train_x)\nplt.plot(pca.explained_variance_ratio_)\nplt.ylabel('% of variance explained')\n\nn_comp = 6\n\n# PCA\npca = PCA(n_components=n_comp, random_state=420)\npca_results_train = pca.fit_transform(train_x)\npca_results_test = pca.transform(test_x)\n\n# TruncatedSVD analysis to train\n## TruncatedSVD decomposition\ntsvd = decomposition.TruncatedSVD(n_components=200) #Finds first 200 PCs\ntsvd.fit(train_x)\nplt.plot(tsvd.explained_variance_ratio_)\nplt.ylabel('% of variance explained')\n\nn_comp = 6\n\n# tSVD\ntsvd = TruncatedSVD(n_components=n_comp, random_state=420)\ntsvd_results_train = tsvd.fit_transform(train_x)\ntsvd_results_test = tsvd.transform(test_x)\n\n# ICA\nn_comp = 6\n\nica = FastICA(n_components = 50, random_state=420)\nica_results_train = ica.fit_transform(train_x)\nica_results_test = ica.transform(test_x)\n\n# GRP\nn_comp = 20\n\ngrp = GaussianRandomProjection(n_components=n_comp, eps=0.1, random_state=420)\ngrp_results_train = grp.fit_transform(train_x)\ngrp_results_test = grp.transform(test_x)\n\n# SRP\nn_comp = 6\n\nsrp = SparseRandomProjection(n_components=n_comp, dense_output=True, random_state=420)\nsrp_results_train = srp.fit_transform(train_x)\nsrp_results_test = srp.transform(test_x)\n\n# NMF analysis to train\n## NMF decomposition\nnmf = NMF(n_components=200) #Finds first 200 PCs\nnmf.fit(train_x)\nplt.plot(tsvd.explained_variance_ratio_)\nplt.ylabel('% of variance explained')\n\n# NMF\nn_comp = 5\n\nnmf = NMF(n_components=n_comp, random_state=420,alpha=.1, l1_ratio=.5)\nnmf_results_train = nmf.fit_transform(train_x)\nnmf_results_test = nmf.transform(test_x)\n\n#save columns list before adding the decomposition components\n\nusable_columns = list(set(train.columns) - set(['y_reciprocal']))\n\n# Append decomposition components to datasets\nn_comp = 6\nfor i in range(1, n_comp + 1):\n train['pca_' + str(i)] = pca_results_train[:, i - 1]\n test['pca_' + str(i)] = pca_results_test[:, i - 1]\n\n train['ica_' + str(i)] = ica_results_train[:, i - 1]\n test['ica_' + str(i)] = ica_results_test[:, i - 1]\n\n train['tsvd_' + str(i)] = tsvd_results_train[:, i - 1]\n test['tsvd_' + str(i)] = tsvd_results_test[:, i - 1]\n\n train['grp_' + str(i)] = grp_results_train[:, i - 1]\n test['grp_' + str(i)] = grp_results_test[:, i - 1]\n\n train['srp_' + str(i)] = srp_results_train[:, i - 1]\n test['srp_' + str(i)] = srp_results_test[:, i - 1]\n\nn_comp = 5\nfor i in range(1, n_comp + 1):\n \n train['nmf_' + str(i)] = nmf_results_train[:, i - 1]\n test['nmf_' + str(i)] = nmf_results_test[:, i - 1]", "did the same thing to valid", "# principal conponent analysis to train\n## PCA decomposition\npca = decomposition.PCA(n_components=200) #Finds first 200 PCs\npca.fit(valid_x)\nplt.plot(pca.explained_variance_ratio_)\nplt.ylabel('% of variance explained')\n\nn_comp = 6\n\n# PCA\npca = PCA(n_components=n_comp, random_state=420)\npca_results_valid = pca.fit_transform(valid_x)\n\n# TruncatedSVD analysis to train\n## TruncatedSVD decomposition\ntsvd = decomposition.TruncatedSVD(n_components=200) #Finds first 200 PCs\ntsvd.fit(valid_x)\nplt.plot(tsvd.explained_variance_ratio_)\nplt.ylabel('% of variance explained')\n\nn_comp = 6\n\n# tSVD\ntsvd = TruncatedSVD(n_components=n_comp, random_state=420)\ntsvd_results_valid = tsvd.fit_transform(valid_x)\n\n# ICA\nn_comp = 6\n\nica = FastICA(n_components = n_comp, random_state=420)\nica_results_valid = ica.fit_transform(valid_x)\n\n# GRP\nn_comp = 6\n\ngrp = GaussianRandomProjection(n_components=n_comp, eps=0.1, random_state=420)\ngrp_results_valid = grp.fit_transform(valid_x)\n\n# SRP\nn_comp = 6\n\nsrp = SparseRandomProjection(n_components=n_comp, dense_output=True, random_state=420)\nsrp_results_valid = srp.fit_transform(valid_x)\n\n# NMF analysis to train\n## NMF decomposition\nnmf = NMF(n_components=200) #Finds first 200 PCs\nnmf.fit(valid_x)\nplt.plot(tsvd.explained_variance_ratio_)\nplt.ylabel('% of variance explained')\n\n# NMF\nn_comp = 5\n\nnmf = NMF(n_components=n_comp, random_state=420,alpha=.1, l1_ratio=.5)\nnmf_results_valid = nmf.fit_transform(valid_x)\n\n# Append decomposition components to datasets\nn_comp = 6\nfor i in range(1, n_comp + 1):\n valid['pca_' + str(i)] = pca_results_valid[:, i - 1]\n \n valid['ica_' + str(i)] = ica_results_valid[:, i - 1]\n \n valid['tsvd_' + str(i)] = tsvd_results_valid[:, i - 1]\n\n valid['grp_' + str(i)] = grp_results_valid[:, i - 1]\n \n valid['srp_' + str(i)] = srp_results_valid[:, i - 1]\n \nn_comp = 5\nfor i in range(1, n_comp + 1):\n \n valid['nmf_' + str(i)] = nmf_results_valid[:, i - 1]\n\ny_train = train['y_reciprocal'].values\ny_valid = valid['y_reciprocal'].values\ny_mean = np.mean(y_train)\nid_test = test['ID'].values\n#finaltrainset and finaltestset are data to be used only the stacked model (does not contain PCA, SVD... arrays) \nfinaltrainset = train[usable_columns].values\nfinaltestset = test[usable_columns].values\n\nclass StackingEstimator(BaseEstimator, TransformerMixin):\n \n def __init__(self, estimator):\n self.estimator = estimator\n\n def fit(self, X, y=None, **fit_params):\n self.estimator.fit(X, y, **fit_params)\n return self\n def transform(self, X):\n X = check_array(X)\n X_transformed = np.copy(X)\n # add class probabilities as a synthetic feature\n if issubclass(self.estimator.__class__, ClassifierMixin) and hasattr(self.estimator, 'predict_proba'):\n X_transformed = np.hstack((self.estimator.predict_proba(X), X))\n\n # add class prodiction as a synthetic feature\n X_transformed = np.hstack((np.reshape(self.estimator.predict(X), (-1, 1)), X_transformed))\n\n return X_transformed\n\n'''Train the xgb model then predict the test data'''\n\nxgb_params = {\n 'n_trees': 520, \n 'eta': 0.0045,\n 'max_depth': 5,\n 'subsample': 0.93,\n 'objective': 'reg:linear',\n 'eval_metric': 'rmse',\n 'base_score': y_mean, # base prediction = mean(target)\n 'silent': 1\n \n}\n# NOTE: Make sure that the class is labeled 'class' in the data file\n\ndtrain = xgb.DMatrix(train.drop('y_reciprocal', axis=1), y_train)\ndvalid = xgb.DMatrix(valid.drop('y_reciprocal', axis=1), y_valid)\ndtest = xgb.DMatrix(test)\n\nevalist = [(dtrain,'train'),(dvalid,'eval')]\n\n#cv_params = {'max_depth': [4,5,6], 'min_child_weight': [1,3,5]}\n#ind_params = {'learning_rate': 0.1, 'n_estimators': 1000, 'seed':0, 'subsample': 0.8, 'colsample_bytree': 0.8, \n #'objective': 'binary:logistic'}\n#optimized_GBM = GridSearchCV(xgb.XGBClassifier(**ind_params), \n #cv_params, \n #scoring = 'accuracy', cv = 5, n_jobs = -1) \n# Optimize for accuracy since that is the metric used in the Adult Data Set notation\n\nnum_boost_rounds = 1250\n# train model\nbst = xgb.train(dict(xgb_params, silent=0), dtrain, num_boost_round = num_boost_rounds, evals = evalist, early_stopping_rounds=10)\ny_pred = bst.predict(dtest,ntree_limit=bst.best_ntree_limit)\n\n'''Train the stacked models then predict the test data'''\n\nstacked_pipeline = make_pipeline(\n StackingEstimator(estimator=LassoLarsCV(normalize=True)),\n StackingEstimator(estimator=GradientBoostingRegressor(learning_rate=0.001, loss=\"huber\", max_depth=4, max_features=0.55, min_samples_leaf=18, min_samples_split=14, subsample=0.8)),\n LassoLarsCV()\n\n)\n\nstacked_pipeline.fit(finaltrainset, y_train)\nresults = stacked_pipeline.predict(finaltestset)\n\n'''R2 Score on the entire Train data when averaging'''\n\nprint('R2 score on train data:')\nprint(r2_score(y_train,stacked_pipeline.predict(finaltrainset)*0.3 + bst.predict(dtrain)*0.7))\n\n'''Average the preditionon test data of both models then save it on a csv file'''\n\nsub = pd.DataFrame()\nsub['ID'] = id_test\nsub['y'] = 1/y_pred*0.7 + 1/results*0.3\nsub.to_csv('stacked-models_v15.csv', index=False)" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
DJCordhose/ai
notebooks/workshops/d2d/cnn-intro.ipynb
mit
[ "Einführung in CNNs\n\nWir haben ein realitätsnahes Beispiel\nhttps://twitter.com/art_sobolev/status/907857395757481985?s=03: I don't think it's fine to only list experiments on toy datasets, and hide failures on more complicated cases.\ndafür können wir leider nicht alles auf lokalen Rechnern oder Azure trainieren", "import warnings\nwarnings.filterwarnings('ignore')\n\n%matplotlib inline\n%pylab inline\n\nimport matplotlib.pylab as plt\nimport numpy as np\n\nfrom distutils.version import StrictVersion\n\nimport sklearn\nprint(sklearn.__version__)\n\nassert StrictVersion(sklearn.__version__ ) >= StrictVersion('0.18.1')\n\nimport tensorflow as tf\ntf.logging.set_verbosity(tf.logging.ERROR)\nprint(tf.__version__)\n\nassert StrictVersion(tf.__version__) >= StrictVersion('1.1.0')\n\n# We need keras 2.0.6 or later as this is the version our GPU based system used to create some models\n!pip install keras --upgrade\n# after installation call Restart & Run All in Kernel menu\n\nimport keras\nprint(keras.__version__)\n\nassert StrictVersion(keras.__version__) >= StrictVersion('2.0.6')\n\nimport pandas as pd\nprint(pd.__version__)\n\nassert StrictVersion(pd.__version__) >= StrictVersion('0.19.0')", "Laden und Vorbereiten der Bild-Daten", "!curl -O https://raw.githubusercontent.com/DJCordhose/speed-limit-signs/master/data/speed-limit-signs.zip\nfrom zipfile import ZipFile\nzip = ZipFile(r'speed-limit-signs.zip')\nzip.extractall('.')\n\n!ls -l speed-limit-signs\n\n!cat speed-limit-signs/README.md", "Big Kudos to Waleed Abdulla for providing the initial idea and many of the functions used to prepare and display the images: https://medium.com/@waleedka/traffic-sign-recognition-with-tensorflow-629dffc391a6#.i728o84ib", "import os\nimport skimage.data\nimport skimage.transform\nfrom keras.utils.np_utils import to_categorical\nimport numpy as np\n\ndef load_data(data_dir, type=\".ppm\"):\n num_categories = 6\n\n # Get all subdirectories of data_dir. Each represents a label.\n directories = [d for d in os.listdir(data_dir) \n if os.path.isdir(os.path.join(data_dir, d))]\n # Loop through the label directories and collect the data in\n # two lists, labels and images.\n labels = []\n images = []\n for d in directories:\n label_dir = os.path.join(data_dir, d)\n file_names = [os.path.join(label_dir, f) for f in os.listdir(label_dir) if f.endswith(type)]\n # For each label, load it's images and add them to the images list.\n # And add the label number (i.e. directory name) to the labels list.\n for f in file_names:\n images.append(skimage.data.imread(f))\n labels.append(int(d))\n images64 = [skimage.transform.resize(image, (64, 64)) for image in images]\n return images64, labels\n\n# Load datasets.\nROOT_PATH = \"./\"\noriginal_dir = os.path.join(ROOT_PATH, \"speed-limit-signs\")\nimages, labels = load_data(original_dir, type=\".ppm\")\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\ndef display_images_and_labels(images, labels):\n \"\"\"Display the first image of each label.\"\"\"\n unique_labels = set(labels)\n plt.figure(figsize=(15, 15))\n i = 1\n for label in unique_labels:\n # Pick the first image for each label.\n image = images[labels.index(label)]\n plt.subplot(8, 8, i) # A grid of 8 rows x 8 columns\n plt.axis('off')\n plt.title(\"Label {0} ({1})\".format(label, labels.count(label)))\n i += 1\n _ = plt.imshow(image)\n\ndisplay_images_and_labels(images, labels)", "Modell-Architektur\nhttp://cs231n.github.io/neural-networks-1/#power\nLayout of a typical CNN\n\nhttp://cs231n.github.io/convolutional-networks/\nClassic VGG like Architecture\n\nwe use a VGG like architecture\nbased on https://arxiv.org/abs/1409.1556\nbasic idea: sequential, deep, small convolutional filters, use dropouts to reduce overfitting\n16/19 layers are typical\nwe choose less layers, because we have limited resources\n\nConvolutional Blocks: Cascading many Convolutional Layers having down sampling in between\n\nhttp://cs231n.github.io/convolutional-networks/#conv\nExample of a Convolution\nOriginal Image\n\nMany convolutional filters applied over all channels\n\nhttp://cs.stanford.edu/people/karpathy/convnetjs/demo/cifar10.html\nDownlsampling Layer: Reduces data sizes and risk of overfitting\n\n\nhttp://cs231n.github.io/convolutional-networks/#pool\nWähle aus einer von 2 Hands-Ons\n\nHands-On Alternative 1 (Überblick)\nMache Erfahrungen mit allen Schichten: https://transcranial.github.io/keras-js/#/mnist-cnn\n\n\nDie Architektur für MNIST ist einfacher, aber enthält alle Arten von Schichten, die wir auch hier nutzen \nZeichne ein paar Zahlen und sieh dir die Zwischenergebnisse in allen Schichten an\n\nNebenbei: Keras.js kann deine Keras-Modelle auch im Browser ausführen\n\n\nHands-On Alternative 2 (Funktionsweise)\nProbiere Filter Kernel für CNNs aus: http://setosa.io/ev/image-kernels/\n\n* Nutze zumindest Sharpen und Blur\n* Probiere beide auf einem Verkersschild aus: https://github.com/DJCordhose/speed-limit-signs/raw/master/data/real-world/4/100-sky-cutoff-detail.jpg\n* Erzeuge einen eigenen Filter\n* Kannst du einen Filter erstellen, der eine schwarze Ausgabe erzeugt?", "# again a little bit of feature engeneering\n\ny = np.array(labels)\nX = np.array(images)\nfrom keras.utils.np_utils import to_categorical\n\nnum_categories = 6\n\ny = to_categorical(y, num_categories)\n\nfrom keras.models import Model\nfrom keras.layers import Dense, Dropout, Flatten, Input\nfrom keras.layers import Convolution2D, MaxPooling2D\n\n# input tensor for a 3-channel 64x64 image\ninputs = Input(shape=(64, 64, 3))\n\n# one block of convolutional layers\nx = Convolution2D(64, 3, activation='relu', padding='same')(inputs)\nx = Convolution2D(64, 3, activation='relu', padding='same')(x)\nx = Convolution2D(64, 3, activation='relu', padding='same')(x)\nx = MaxPooling2D(pool_size=(2, 2))(x)\n\n# one more block\nx = Convolution2D(128, 3, activation='relu', padding='same')(x)\nx = Convolution2D(128, 3, activation='relu', padding='same')(x)\nx = MaxPooling2D(pool_size=(2, 2))(x)\n\n# one more block\nx = Convolution2D(256, 3, activation='relu', padding='same')(x)\nx = MaxPooling2D(pool_size=(2, 2))(x)\n\nx = Flatten()(x)\nx = Dense(256, activation='relu')(x)\n\n# softmax activation, 6 categories\npredictions = Dense(6, activation='softmax')(x)\n\nmodel = Model(input=inputs, output=predictions)\nmodel.summary()\n\nmodel.compile(optimizer='adam',\n loss='categorical_crossentropy',\n metrics=['accuracy'])", "Optimizers: Adam and RMSprop seem nice\n\n\nhttp://cs231n.github.io/neural-networks-3/#ada\nZuerst testen wir unser Modell, ob wir es überhaupt trainiert bekommen, indem wir auf einer kleinen Menge von Daten overfitten\nhttp://cs231n.github.io/neural-networks-3/#sanitycheck", "from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.9, random_state=42, stratify=y)\n\nX_train.shape, y_train.shape\n\n# %time model.fit(X_train, y_train, epochs=50, validation_split=0.3)\n%time model.fit(X_train, y_train, epochs=100, validation_split=0.3)", "Verlauf der Metriken beim Overfitting\nAccuracy\n\nValidation Accuracy\n\n\nHands-On: Hauptübung\nVereinfache die Architektur so weit, bis sie nicht mehr overfitten kann\n\nreduziere dazu entweder die Layers\noder die Feature Channels\nReduziere die Epochen auf ca. 50, damit du schnell experimentieren kannst\n\nEin solches Modell kann extrem einfach sein und schon dadurch Overfittung verhindern. \nWir verfolgen hier aber eine andere Philosophie: Wir machen das Modell so komplex wie es unsere Hardware zulässt und nutzen eine andere Methode, um Overfitting zu verhindern.\n\nOverfitting vermeiden mit Dropout", "from keras.models import Model\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Input\nfrom keras.layers import Convolution2D, MaxPooling2D\n\n# this is important, try and vary between .4 and .75\ndrop_out = 0.7\n\n# input tensor for a 3-channel 64x64 image\ninputs = Input(shape=(64, 64, 3))\n\n# one block of convolutional layers\nx = Convolution2D(64, 3, activation='relu', padding='same')(inputs)\nx = Convolution2D(64, 3, activation='relu', padding='same')(x)\nx = Convolution2D(64, 3, activation='relu', padding='same')(x)\nx = MaxPooling2D(pool_size=(2, 2))(x)\nx = Dropout(drop_out)(x)\n\n# one more block\nx = Convolution2D(128, 3, activation='relu', padding='same')(x)\nx = Convolution2D(128, 3, activation='relu', padding='same')(x)\nx = MaxPooling2D(pool_size=(2, 2))(x)\nx = Dropout(drop_out)(x)\n\n# one more block\nx = Convolution2D(256, 3, activation='relu', padding='same')(x)\nx = MaxPooling2D(pool_size=(2, 2))(x)\nx = Dropout(drop_out)(x)\n\nx = Flatten()(x)\nx = Dense(256, activation='relu')(x)\nx = Dropout(drop_out)(x)\n\n# softmax activation, 6 categories\npredictions = Dense(6, activation='softmax')(x)\n\nmodel = Model(input=inputs, output=predictions)\nmodel.summary()\n\nmodel.compile(optimizer='adam',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)", "Training\n\nAuf einem GPU basierten System geht das in ein paar Minuten\nAzure Rechner sind relativ schnell, haben aber keine GPU\nHier dauert jede Epoche ca. 10 Sekunden, bei 500 Epochen = 5000 Sekunden = 1,5 Stunden\nDas können wir nicht warten\n2 Möglichkeiten:\nDu trainierst mit deinem vereinfachten Modell\nWir trainieren mit diesem Notebook gemeinsam ein Modell auf einer K80 GPU\ndieses Modell wird dann geteilt und jeder macht dann die Auswertung wieder in seinem Notebook\nWährend das Modell trainiert (dauert auf K80 GPU nur ein paar Minuten) sehen wir uns das TensorBoard an und verfolgen das Training\nLoss, Accuracy, Validation Loss, Validation Accuracy", "# https://keras.io/callbacks/#tensorboard\ntb_callback = keras.callbacks.TensorBoard(log_dir='./tf_log')\n# To start tensorboard\n# tensorboard --logdir=/mnt/c/Users/olive/Development/ml/tf_log\n# open http://localhost:6006\n\nearly_stopping_callback = keras.callbacks.EarlyStopping(monitor='val_loss', patience=100, verbose=1)\n\ncheckpoint_callback = keras.callbacks.ModelCheckpoint('./model-checkpoints/weights.epoch-{epoch:02d}-val_loss-{val_loss:.2f}.hdf5');\n\n!rm -r tf_log\n\n# Depends on harware GPU architecture, set as high as possible (this works well on K80)\nBATCH_SIZE = 500\n\n# %time model.fit(X_train, y_train, epochs=500, batch_size=BATCH_SIZE, validation_split=0.2, callbacks=[tb_callback, early_stopping_callback])\n%time model.fit(X_train, y_train, epochs=500, batch_size=BATCH_SIZE, validation_split=0.2, callbacks=[tb_callback])\n# %time model.fit(X_train, y_train, epochs=500, batch_size=BATCH_SIZE, validation_split=0.2)", "Idealer Verlauf der Metriken beim vollen Training\n100% bei Training und über 95% bei Validation sind möglich, sind bei der Datenmenge aber mit Vorsicht zu genießen\nAccuracy\n\nValidation Accuracy\n\nSichern des Modells (falls in diesem Notebook trainiert wurde)\n\nunser Modell ist 55 MB groß, das ist ein wirklich großes Modell", "model.save('conv-vgg.hdf5')\n\n!ls -lh\n\n# https://transfer.sh/\n# Speichert eure Daten für 14 Tage\n!curl --upload-file conv-vgg.hdf5 https://transfer.sh/conv-vgg.hdf5\n\n# Vortrainiertes Modell\n# loss: 0.0310 - acc: 0.9917 - val_loss: 0.4075 - val_acc: 0.9508\n# https://transfer.sh/B1W8e/conv-vgg.hdf5", "ODER Laden des trainierten Modells", "!ls -lh\n\n!rm conv-vgg.hdf5\n\n# anpassen an aktuelles Modell\n# Nachricht an Olli: Liegt auch local auf Ollis Rechner und kann zur Not von da hochgeladen werden (ai/models/conv-vgg.hdf5)\n!curl -O https://transfer.sh/B1W8e/conv-vgg.hdf5\n\n!ls -lh\n\nfrom keras.models import load_model\nmodel = load_model('conv-vgg.hdf5')", "Bewertung", "train_loss, train_accuracy = model.evaluate(X_train, y_train, batch_size=BATCH_SIZE)\ntrain_loss, train_accuracy\n\ntest_loss, test_accuracy = model.evaluate(X_test, y_test, batch_size=BATCH_SIZE)\ntest_loss, test_accuracy", "Ausprobieren auf ein paar Test-Daten", "import random\n\n# Pick 10 random images for test data set\nrandom.seed(4) # to make this deterministic\nsample_indexes = random.sample(range(len(X_test)), 10)\nsample_images = [X_test[i] for i in sample_indexes]\nsample_labels = [y_test[i] for i in sample_indexes]\n\nground_truth = np.argmax(sample_labels, axis=1)\nground_truth\n\nX_sample = np.array(sample_images)\nprediction = model.predict(X_sample)\npredicted_categories = np.argmax(prediction, axis=1)\npredicted_categories\n\n# Display the predictions and the ground truth visually.\ndef display_prediction (images, true_labels, predicted_labels):\n fig = plt.figure(figsize=(10, 10))\n for i in range(len(true_labels)):\n truth = true_labels[i]\n prediction = predicted_labels[i]\n plt.subplot(5, 2,1+i)\n plt.axis('off')\n color='green' if truth == prediction else 'red'\n plt.text(80, 10, \"Truth: {0}\\nPrediction: {1}\".format(truth, prediction), \n fontsize=12, color=color)\n plt.imshow(images[i])\n\ndisplay_prediction(sample_images, ground_truth, predicted_categories)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
robertoalotufo/ia898
master/FerramentasdeEdicaoHTML.ipynb
mit
[ "Table of Contents\n<p><div class=\"lev1 toc-item\"><a href=\"#Jupyter-Notebook:-Ferramentas-de-edição-multimídia\" data-toc-modified-id=\"Jupyter-Notebook:-Ferramentas-de-edição-multimídia-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Jupyter Notebook: Ferramentas de edição multimídia</a></div><div class=\"lev2 toc-item\"><a href=\"#Títulos-e-subtítulos\" data-toc-modified-id=\"Títulos-e-subtítulos-11\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Títulos e subtítulos</a></div><div class=\"lev3 toc-item\"><a href=\"#Subtítulo-de-terceiro-nível\" data-toc-modified-id=\"Subtítulo-de-terceiro-nível-111\"><span class=\"toc-item-num\">1.1.1&nbsp;&nbsp;</span>Subtítulo de terceiro nível</a></div><div class=\"lev4 toc-item\"><a href=\"#Subítulo-de-quarto-nível\" data-toc-modified-id=\"Subítulo-de-quarto-nível-1111\"><span class=\"toc-item-num\">1.1.1.1&nbsp;&nbsp;</span>Subítulo de quarto nível</a></div><div class=\"lev2 toc-item\"><a href=\"#Negrito,-itálico-e-literal\" data-toc-modified-id=\"Negrito,-itálico-e-literal-12\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Negrito, itálico e literal</a></div><div class=\"lev2 toc-item\"><a href=\"#Texto-colorido\" data-toc-modified-id=\"Texto-colorido-13\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>Texto colorido</a></div><div class=\"lev2 toc-item\"><a href=\"#Colocando-links-Internet\" data-toc-modified-id=\"Colocando-links-Internet-14\"><span class=\"toc-item-num\">1.4&nbsp;&nbsp;</span>Colocando links Internet</a></div><div class=\"lev2 toc-item\"><a href=\"#Itemização-de-texto\" data-toc-modified-id=\"Itemização-de-texto-15\"><span class=\"toc-item-num\">1.5&nbsp;&nbsp;</span>Itemização de texto</a></div><div class=\"lev2 toc-item\"><a href=\"#Linha-de-separação\" data-toc-modified-id=\"Linha-de-separação-16\"><span class=\"toc-item-num\">1.6&nbsp;&nbsp;</span>Linha de separação</a></div><div class=\"lev2 toc-item\"><a href=\"#Equações-LaTeX\" data-toc-modified-id=\"Equações-LaTeX-17\"><span class=\"toc-item-num\">1.7&nbsp;&nbsp;</span>Equações LaTeX</a></div><div class=\"lev2 toc-item\"><a href=\"#Mostrando-imagens-na-célula-markdown\" data-toc-modified-id=\"Mostrando-imagens-na-célula-markdown-18\"><span class=\"toc-item-num\">1.8&nbsp;&nbsp;</span>Mostrando imagens na célula markdown</a></div><div class=\"lev3 toc-item\"><a href=\"#Na-forma-de-link-HTML\" data-toc-modified-id=\"Na-forma-de-link-HTML-181\"><span class=\"toc-item-num\">1.8.1&nbsp;&nbsp;</span>Na forma de link HTML</a></div><div class=\"lev3 toc-item\"><a href=\"#Na-forma-de-link-Jupyter\" data-toc-modified-id=\"Na-forma-de-link-Jupyter-182\"><span class=\"toc-item-num\">1.8.2&nbsp;&nbsp;</span>Na forma de link Jupyter</a></div><div class=\"lev2 toc-item\"><a href=\"#Inserindo-vídeo-e-website\" data-toc-modified-id=\"Inserindo-vídeo-e-website-19\"><span class=\"toc-item-num\">1.9&nbsp;&nbsp;</span>Inserindo vídeo e website</a></div><div class=\"lev2 toc-item\"><a href=\"#Forma-de-baixar-um-arquivo-de-dados-para-computador-local\" data-toc-modified-id=\"Forma-de-baixar-um-arquivo-de-dados-para-computador-local-110\"><span class=\"toc-item-num\">1.10&nbsp;&nbsp;</span>Forma de baixar um arquivo de dados para computador local</a></div>\n\n# Jupyter Notebook: Ferramentas de edição multimídia \n\nEste documento ilustra as principais ferramentas para editar o notebook, utilizando células de texto Markdown:", "# Ajuste de largura do notebook no display\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:95% !important; }</style>\"))", "Títulos e subtítulos\nTítulos e subtítulos são colocados com #, ##, ### ou mais # como a seguir\nSubtítulo de terceiro nível\nSubítulo de quarto nível\nNegrito, itálico e literal\nNegrito coloca-se com dois asteriscos. Por exemplo:\n- o texto **Este texto em negrito** fica Este texto em negrito \nO texto em Itálico é utilizado com apenas um asterisco. Por exemplo \n- o texto *Este texto em itálico* aparece Este texto em itálico\nPara mostrar um texto original (verbatim) usa-se texto separado por crases. Por exemplo \n- este texto aparece com espaçamento fixo: Este é um texto cru\nPode-se criar um bloco de texto original usando linhas com três crases:\nEste é um bloco literal\n Os espaçamentos são preservados,\n {assim como &lt;&lt;&lt;[] } os caracteres especiais não têm significado\nTexto colorido\nForma simples de criar texto colorido é utilizando sintaxe do HTML: \n- escrevendo-se &lt;code style=\"color:red\"&gt;vermelho&lt;/code&gt;, o texto aparece como <code style=\"color:red\">vermelho</code> \nColocando links Internet\nColoca-se [Link para divulgação curso DL](http://adessowiki.fee.unicamp.br/rnpi)\nVeja como aparece: Link para divulgação curso DL\nFazendo um link para uma seção dentro do próprio notebook. Utiliza-se o link usando-se a sintaxe do HTML para referências dentro de arquivo. Lembrar de trocar os espaços dos subtítulos por traço.\nPor exemplo:\nLink para [Negrito e itálico](#Negrito-e-itálico) fica\nLink para Negrito, itálico e cru\nItemização de texto\nA itemização utiliza caracteres como -, * e números. Para criar itens aninhados, utiliza-se um afastamento maior. Veja estes exemplos:\n\nitem 1\nitem 1.1\nitem 2\n\nItemização numérica\n\nitem 1\nitem 1.a \n este texto pertence ao item 1.a\nitem 2\n\nLinha de separação\nUma linha de separação é feita colocando-se três caracteres _ no começo de uma linha:\n\nEquações LaTeX\nEquações LaTeX podem ser inseridas com o caractere \\$, de forma in line: $ a = \\sum i $ ou de forma destacada:\n$$ A = \\sum_{i=0}^{n-1} a_i $$\nMostrando imagens na célula markdown\nAs imagens gravadas em disco em disponíveis na Internet podem ser mostradas tanto como elementos HTML usando &lt;img src= link&gt; como um link jupyter especial para a image utilizando o caracter !. No primeiro caso, a vantagem é que se tem um maior controle do seu posicionamento e dimensão.\nNa forma de link HTML\nNo primeiro exemplo a seguir, é utilizado uma imagem com a largura de 256 pontos &lt;img src=link, width=256&gt;: \n<img src=\"https://lh5.googleusercontent.com/-4z1aOb-x0Co/AAAAAAAAAAI/AAAAAAAADXc/sAeBMo6pz_k/photo.jpg\",width=256>\nNa forma de link Jupyter\nJá esta outra imagem, é mostrada como um link do IPython no formato ![texto](link):\n\nInserindo vídeo e website\nA inserção de vídeo e website somente na célula de programação Python. O display do IPython possui aplicação específica para importar vídeos do YouTube:", "from IPython.display import YouTubeVideo\n# a talk about IPython at Sage Days at U. Washington, Seattle.\n# Video credit: William Stein.\nYouTubeVideo('1j_HxD4iLn8')", "Para inserir website, o display do IPython tem suporte para mostrar um IFrame, onde é possível colocar o endereço de um website:", "from IPython.display import IFrame\nIFrame('http://wikipedia.com', width=700, height=350)", "Forma de baixar um arquivo de dados para computador local\nUma forma simples de transferir um arquivo gerado pelo Jupyter no servidor para seu computador local é zipá-lo usando o comando gzip do linux e criar um link para ele. Como a extensão será gz quando se clica, o navegador faz o download do arquivo para seu computador local.\nColocar numa célula de código:\n!gzip &lt;nome do arquivo&gt;\nColocar numa célula Markdown:\n[link para download](&lt;nome do arquivo&gt;.gz)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
ctroupin/OceanData_NoteBooks
PythonNotebooks/PlatformPlots/plot_CMEMS_drifter.ipynb
gpl-3.0
[ "The objective of this notebook is to show how to read and plot the trajectory and the temperature measured by a drifting buoy.", "%matplotlib inline\nimport netCDF4\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\nfrom mpl_toolkits.basemap import Basemap", "Data reading\nThe data file is located in the datafiles directory.", "datadir = './datafiles/'\ndatafile = 'GL_TS_DC_2300691.nc'", "We extract only the spatial coordinates:", "with netCDF4.Dataset(datadir + datafile) as nc:\n lon = nc.variables['LONGITUDE'][:]\n lat = nc.variables['LATITUDE'][:]", "Basic plot\nBefore starting the plots, we set the font size to 16:", "mpl.rcParams.update({'font.size': 16})", "We will also indicate Start and End labels at the corresponding locations.", "fig = plt.figure(figsize=(8,8))\nax = plt.subplot(111)\nplt.plot(lon, lat, 'ko', ms=1)\nplt.text(lon[0], lat[0], 'Start', fontsize=16)\nplt.text(lon[-1], lat[-1], 'End', fontsize=16)\nplt.show()", "The figure can be improved by adding the landmask and coastline.\nPlot on a map\nThe first thing to do is to create a projection using basemap. We can obtain the bounding box from the previous plot:", "lonmin, lonmax = ax.get_xlim()\nlatmin, latmax = ax.get_ylim()", "then we create the projection, slightly enlarging the longitude extension:", "m = Basemap(projection='merc', llcrnrlat=latmin, urcrnrlat=latmax,\n llcrnrlon=lonmin-5, urcrnrlon=lonmax+5, lat_ts=20, resolution='i')", "The new figure is generated similarly to the previous one:", "lon2, lat2 = m(lon, lat)\nfig = plt.figure(figsize=(8,8))\nm.plot(lon2, lat2, 'ko', ms=1)\n\nm.drawcoastlines(linewidth=0.5, zorder=3)\nm.fillcontinents(zorder=2)\n\nm.drawparallels(np.arange(-90.,91.,5.), labels=[1,0,0,0], zorder=1)\nm.drawmeridians(np.arange(-180.,181.,5.), labels=[0,1,0,0], zorder=1)\nplt.show()", "Scatter plot\nIf the platforms also measures the temperature, we can create a scatter plot (the color of the dot on the map depends on the measured temperature).<br/>\nThe temperature variable is loaded the same way as for the coordinates.", "with netCDF4.Dataset(datadir + datafile) as nc:\n temperature = nc.variables['TEMP'][:,1]\n print temperature.shape", "For the plot, we will keep the same projection.<br/>\nWe also have to set the colormap.", "cmap = plt.cm.Spectral_r\nnorm = colors.Normalize(vmin=26, vmax=29)", "We specify the coordinates and the temperature as the arguments of the scatter plot:\n* s=10 indicate the size of the dots,\n* c=temperature indicates which variable is used as the z-dimension (color)\n* edgecolor='None' means that no color is applied around the edge of the marker\n* cmap=cmap sets the colormap to cmap, defined before and\n* norm=norm sets the limits for the color scale.", "fig = plt.figure(figsize=(8,8))\nm.scatter(lon2, lat2, s=10, c=temperature, edgecolor='None', cmap=cmap, norm=norm)\nm.drawcoastlines(linewidth=0.5, zorder=3)\nm.fillcontinents(zorder=2)\nm.drawparallels(np.arange(-90.,91.,5.), labels=[1,0,0,0], zorder=1)\nm.drawmeridians(np.arange(-180.,181.,5.), labels=[0,0,1,0], zorder=1)\nplt.colorbar(extend='both', cmap=cmap, norm=norm)\nplt.show()", "The temperature values measured close to the Equator are higher than those measured along the coast." ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
bgroveben/python3_machine_learning_projects
introduction_to_ml_with_python/4_Data_and_Features.ipynb
mit
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport mglearn\nfrom IPython.display import display\n%matplotlib inline", "Chapter 4. Representing Data and Engineering Features\nSo far, we’ve assumed that our data comes in as a two-dimensional array of floating-point numbers, where each column is a continuous feature that describes the data points.\nFor many applications, this is not how the data is collected.\nA particularly common type of feature is the categorical features.\nAlso known as discrete features, these are usually not numeric.\nThe distinction between categorical features and continuous features is analogous to the distinction between classification and regression, only on the input side rather than the output side.\nExamples of continuous features that we have seen are pixel brightnesses and size measurements of plant flowers.\nExamples of categorical features are the brand of a product, the color of a product, or the department (books, clothing, hardware) it is sold in.\nThese are all properties that can describe a product, but they don’t vary in a continuous way.\nA product belongs either in the clothing department or in the books department.\nThere is no middle ground between books and clothing, and no natural order for the different categories (books is not greater or less than clothing, hardware is not between books and clothing, etc.).\nRegardless of the types of features your data consists of, how you represent them can have an enormous effect on the performance of machine learning models.\nWe saw in Chapters 2 and 3 that scaling of the data is important.\nIn other words, if you don’t rescale your data (say, to unit variance), then it makes a difference whether you represent a measurement in centimeters or inches.\nWe also saw in Chapter 2 that it can be helpful to augment your data with additional features, like adding interactions (products) of features or more general polynomials.\nThe question of how to represent your data best for a particular application is known as feature engineering, and it is one of the main tasks of data scientists and machine learning practitioners trying to solve real-world problems.\nRepresenting your data in the right way can have a bigger influence on the performance of a supervised model than the exact parameters you choose.\nIn this chapter, we will first go over the important and very common case of categorical features, and then give some examples of helpful transformations for specific combinations of features and models.\nCategorical Variables\nAs an example, we will use the dataset of adult incomes in the United States, derived from the 1994 census database.\nThe task of the adult dataset is to predict whether a worker has an income of over \\$50,000 or under \\$50,000.\nThe features in this dataset include the workers’ ages, how they are employed (self employed, private industry employee, government employee, etc.), their education, their gender, their working hours per week, occupation, and more.\nTable 4-1 shows the first few entries in the dataset:\n\nThe task is phrased as a classification task with the two classes being income &lt;=50k and &gt;50k.\nIt would also be possible to predict the exact income, and make this a regression task.\nHowever, that would be much more difficult, and the 50K division is interesting to understand on its own.\nIn this dataset, age and hours-per-week are continuous features, which we know how to treat.\nThe workclass, education, sex, and occupation features are categorical, however.\nAll of them come from a fixed list of possible values, as opposed to a range, and denote a qualitative property, as opposed to a quantity.\nAs a starting point, let’s say we want to learn a logistic regression classifier on this data.\nWe know from Chapter 2 that a logistic regression makes predictions, $ŷ$, using the following formula:\n$ŷ = w[0] * x[0] +w[1] * x[1] + \\ldots + w[p] * x[p] + b > 0$\nwhere $w[i]$ and $b$ are coefficients learned from the training set and $x[i]$ are the input features.\nThis formula makes sense when $x[i]$ are numbers, but not when $x[2]$ is \"Masters\" or \"Bachelors\".\nClearly we need to represent our data in some different way when applying logistic regression.\nThe next section will explain how we can overcome this problem.\nOne-Hot-Encoding (Dummy Variables)\nBy far the most common way to represent categorical variables is using the one-hot-encoding or one-out-of-N encoding, also known as dummy variables.\nThe idea behind dummy variables is to replace a categorical variable with one or more new features that can have the values 0 and 1.\nThe values 0 and 1 make sense in the formula for linear binary classification (and for all other models in scikit-learn), and we can represent any number of categories by introducing one new feature per category, as described here.\nLet’s say for the workclass feature we have possible values of \"Government Employee\", \"Private Employee\", \"Self Employed\", and \"Self Employed Incorporated\".\nTo encode these four possible values, we create four new features, called \"Government Employee\", \"Private Employee\", \"Self Employed\", and \"Self Employed Incorporated\".\nA feature is 1 if workclass for this person has the corresponding value and 0 otherwise, so exactly one of the four new features will be 1 for each data point.\nThis is why this is called one-hot or one-out-of-N encoding.\nThe principle is illustrated in Table 4-2.\nA single feature is encoded using four new features.\nWhen using this data in a machine learning algorithm, we would drop the original workclass feature and only keep the 0-1 features.\n\nNOTE\nThe one-hot encoding we use is quite similar, but not identical, to the dummy coding used in statistics.\nFor simplicity, we encode each category with a different binary feature.\nIn statistics, it is common to encode a categorical feature with k different possible values into k–1 features (the last one is represented as all zeros).\nThis is done to simplify the analysis (more technically, this will avoid making the data matrix rank-deficient.\nThere are two ways to convert your data to a one-hot encoding of categorical variables, using either pandas or scikit-learn.\nAt the time of writing, using pandas is slightly easier, so let’s go this route.\nFirst we load the data using pandas from a comma-separated values (CSV) file:", "import os\n# The file has no headers naking the columns, so we pass \n# header=None and provide the column names explicitly in \"names\".\nadult_path = os.path.join(mglearn.datasets.DATA_PATH, \"adult.data\")\nprint(adult_path)\n\ndata = pd.read_csv(adult_path, header=None, index_col=False,\n names=['age', 'workclass', 'fnlwgt', 'education',\n 'education-num', 'marital-status', 'occupation',\n 'relationship', 'race', 'gender', 'capital-gain',\n 'capital-loss', 'hours-per-week', 'native-country',\n 'income'])\n# For illustrative purposes, we'll only select some of the columns:\ndata = data[['age', 'workclass', 'education', 'gender',\n 'hours-per-week', 'occupation', 'income']]\n# IPython.display allows nice output formatting within the \n# Jupyter notebook:\ndisplay(data.head())", "Checking string-encoded categorical data\nAfter reading a dataset like this, it is often good to first check if a column actually contains meaningful categorical data.\nWhen working with data that was input by humans (say, users on a website), there might not be a fixed set of categories, and differences in spelling and capitalization might require preprocessing.\nFor example, it might be that some people specified gender as “male” and some as “man,” and we might want to represent these two inputs using the same category.\nA good way to check the contents of a column is using the value_counts method of a pandas Series (the type of a single column in a DataFrame), to show us what the unique values are and how often they appear:", "print(data.gender.value_counts())", "We can see that there are exactly two values for gender in this dataset, Male and Female, meaning the data is already in a good format to be represented using one-hot-encoding.\nIn a real application, you should look at all columns and check their values.\nWe will skip this here for brevity’s sake.\nThere is a very simple way to encode the data in pandas, using the get_dummies() function.\nThe get_dummies() function automatically transforms all columns that have object type (like strings) or are categorical (which is a special pandas concept that we haven’t talked about yet):", "print(\"Original Features: \\n\", list(data.columns))\n\ndata_dummies = pd.get_dummies(data)\nprint(\"Features After Applying get_dummies(): \\n\",\n list(data_dummies.columns))", "You can see that the continuous features age and hours-per-week were not touched, while the categorical features were expanded into one new feature for each possible value:", "data_dummies.head()", "We can now use the values attribute to convert the data_dummies DataFrame into a NumPy array, and then train a machine learning model on it.\nBe careful to separate the target variable (which is now encoded in two income columns) from the data before training a model.\nIncluding the output variable, or some derived property of the output variable, into the feature representation is a very common mistake in building supervised machine learning models.\nWARNING\nBe careful: column indexing in pandas includes the end of the range, so 'age':'occupation_ Transport-moving' is inclusive of occupation_ Transport-moving.\nThis is different from slicing a NumPy array, where the end of a range is not included: for example, np.arange(11)[0:10] doesn’t include the entry with index 10.\nIn this case, we extract only the columns containing features -- that is, all columns from age to occupation_ Transport-moving.\nThis range contains all of the features but not the target:", "features = data_dummies.loc[:, 'age':'occupation_ Transport-moving']\n# Extract NumPy arrays:\nX = features.values\nprint(\"X[:5]: \\n\", X[:5], \"\\n\")\ny = data_dummies['income_ >50K'].values\nprint(\"y[:5]: \\n\", y[:5], \"\\n\")\nprint(\"X.shape: {} y.shape: {}\".format(X.shape, y.shape))", "Now the data is represented in a way that scikit-learn can work with, and we can proceed as usual:", "from sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y,\n random_state=0)\nlogreg = LogisticRegression()\nlogreg.fit(X_train, y_train)\nprint(\"Test Score: {:.2f}\".format(logreg.score(X_test, y_test)))", "WARNING\nIn this example, we called get_dummies() on a DataFrame containing both the training and the test data.\nThis is important to ensure categorical values are represented in the same way in the training set and the test set.\nImagine we have the training and test sets in two different DataFrames.\nIf the \"Private Employee\" value for the workclass feature does not appear in the test set, pandas will assume there are only three possible values for this feature and will create only three new dummy features.\nNow our training and test sets have different numbers of features, and we can’t apply the model we learned on the training set to the test set anymore.\nEven worse, imagine the workclass feature has the values \"Government Employee\" and \"Private Employee\" in the training set, and \"Self Employed\" and \"Self Employed Incorporated\" in the test set.\nIn both cases, pandas will create two new dummy features, so the encoded DataFrames will have the same number of features.\nHowever, the two dummy features have entirely different meanings in the training and test sets.\nThe column that means \"Government Employee\" for the training set would encode \"Self Employed\" for the test set.\nIf we built a machine learning model on this data it would work very badly, because it would assume the columns mean the same things (because they are in the same position) when in fact they mean very different things.\nTo fix this, either call get_dummies() on a DataFrame that contains both the training and the test data points, or make sure that the column names are the same for the training and test sets after calling get_dummies(), to ensure they have the same semantics.\nNumbers Can Encode Categoricals\nIn the example of the adult dataset, the categorical variables were encoded as strings.\nOn the one hand, that opens up the possibility of spelling errors, but on the other hand, it clearly marks a variable as categorical.\nOften, whether for ease of storage or because of the way the data is collected, categorical variables are encoded as integers.\nFor example, imagine the census data in the adult dataset was collected using a questionnaire, and the answers for workclass were recorded as 0 (first box ticked), 1 (second box ticked), 2 (third box ticked), and so on.\nNow the column will contain numbers from 0 to 8, instead of strings like \"Private\", and it won’t be immediately obvious to someone looking at the table representing the dataset whether they should treat this variable as continuous or categorical.\nKnowing that the numbers indicate employment status, however, it is clear that these are very distinct states and should not be modeled by a single continuous variable.\nWARNING\nCategorical features are often encoded using integers.\nThat they are numbers doesn’t mean that they should necessarily be treated as continuous features.\nIt is not always clear whether an integer feature should be treated as continuous or discrete (and one-hot-encoded).\nIf there is no ordering between the semantics that are encoded (like in the workclass example), the feature must be treated as discrete.\nFor other cases, like five-star ratings, the better encoding depends on the particular task and data and which machine learning algorithm is used.\nThe get_dummies() function in pandas treats all numbers as continuous and will not create dummy variables for them.\nTo get around this, you can either use scikit-learn’s OneHotEncoder, for which you can specify which variables are continuous and which are discrete, or convert numeric columns in the DataFrame to strings.\nTo illustrate, let’s create a DataFrame object with two columns, one containing strings and one containing integers:", "# Create a DataFrame with an integer feature and a categorical\n# string feature:\ndemo_df = pd.DataFrame({'Integer Feature': [0, 1, 2, 1],\n 'Categorical Feature': ['socks',\n 'fox',\n 'socks',\n 'box']})\ndisplay(demo_df)", "Using get_dummies() will only encode the string feature and will not change the integer feature, as you can see in Table 4-5:", "display(pd.get_dummies(demo_df))", "If you want dummy variables to be created for the \"Integer Feature\" column, you can explicitly list the columns you want to encode using the columns parameter.\nThen, both features will be treated as categorical (see Table 4-6):", "demo_df['Integer Feature'] = demo_df['Integer Feature'].astype(str)\ndisplay(pd.get_dummies(demo_df,\n columns=['Integer Feature',\n 'Categorical Feature']))", "Binning, Discretization, Linear Models, and Trees\nThe best way to represent data depends not only on the semantics of the data, but also on the kind of model you are using.\nLinear models and tree-based models (such as decision trees, gradient boosted trees, and random forests), two large and very commonly used families, have very different properties when it comes to how they work with different feature representations.\nLet’s go back to the wave regression dataset that we used in Chapter 2.\nIt has only a single input feature.\nHere is a comparison of a linear regression model and a decision tree regressor on this dataset (see Figure 4-1):", "from sklearn.linear_model import LinearRegression\nfrom sklearn.tree import DecisionTreeRegressor\n\nX, y = mglearn.datasets.make_wave(n_samples=100)\nline = np.linspace(-3, 3, 1000, endpoint=False).reshape(-1, 1)\n\nreg = DecisionTreeRegressor(min_samples_split=3).fit(X, y)\nplt.plot(line, reg.predict(line), label='decision tree')\n\nreg = LinearRegression().fit(X, y)\nplt.plot(line, reg.predict(line), label='linear regression')\n\nplt.plot(X[:, 0], y, 'o', c='k')\nplt.ylabel(\"Regression Output\")\nplt.xlabel(\"Input Feature\")\nplt.legend(loc=\"best\")", "As you know, linear models can only model linear relationships, which are lines in the case of a single feature.\nThe decision tree can build a much more complex model of the data.\nHowever, this is strongly dependent on the representation of the data.\nOne way to make linear models more powerful on continuous data is to use binning (also known as discretization) of the feature to split it up into multiple features, as described here.\nWe imagine a partition of the input range for the feature (in this case, the numbers from –3 to 3) into a fixed number of bins -- say, 10.\nA data point will then be represented by which bin it falls into.\nTo determine this, we first have to define the bins.\nIn this case, we’ll define 10 bins equally spaced between –3 and 3.\nWe use the np.linspace function for this, creating 11 entries, which will create 10 bins -- they are the spaces in between two consecutive boundaries:", "bins = np.linspace(-3, 3, 11)\nprint(\"bins: {}\".format(bins))", "Here, the first bin contains all data points with feature values –3 to –2.4, the second bin contains all points with feature values from –2.4 to –1.8, and so on.\nNext, we record for each data point which bin it falls into.\nThis can be easily computed using the np.digitize() function:", "which_bin = np.digitize(X, bins=bins)\nprint(\"\\nData Points:\\n\", X[:5])\nprint(\"\\nBin Membership for Data Points:\\n\", which_bin[:5])", "What we did here is transform the single continuous input feature in the wave dataset into a categorical feature that encodes which bin a data point is in.\nTo use a scikit-learn model on this data, we transform this discrete feature to a one-hot encoding using the OneHotEncoder from the preprocessing module.\nThe OneHotEncoder does the same encoding as pandas.get_dummies(), though it currently only works on categorical variables that are integers:", "from sklearn.preprocessing import OneHotEncoder\n\n# Transform data using the OneHotEncoder:\nencoder = OneHotEncoder(sparse=False)\n# Use encoder.fit to find the unique values that appear\n# in which_bin:\nencoder.fit(which_bin)\n# Transform creates the one-hot encoding:\nX_binned = encoder.transform(which_bin)\nprint(X_binned[:5])", "Because we specified 10 bins, the transformed dataset X_binned now is made up of 10 features:", "print(\"X_binned.shape: {}\".format(X_binned.shape))", "Now we can build a new linear regression model and a new decision tree model on the one-hot-encoded data.\nThe result is visualized in Figure 4-2, together with the bin boundaries, shown as dotted black lines:", "line_binned = encoder.transform(np.digitize(line, bins=bins))\n\nreg = LinearRegression().fit(X_binned, y)\nplt.plot(line, reg.predict(line_binned),\n label=\"Linear Regression Binned\")\n\nreg = DecisionTreeRegressor(min_samples_split=3).fit(X_binned, y)\nplt.plot(line, reg.predict(line_binned),\n label=\"Decision Tree Binned\")\n\nplt.plot(X[:, 0], y, 'o', c='k')\nplt.vlines(bins, -3, 3, linewidth=1, alpha=.2)\nplt.legend(loc=\"best\")\nplt.ylabel(\"Regression Output\")\nplt.xlabel(\"Input Feature\")", "The dashed line and solid line are exactly on top of each other, meaning the linear regression model and the decision tree make exactly the same predictions.\nFor each bin, they predict a constant value.\nAs features are constant within each bin, any model must predict the same value for all points within a bin.\nComparing what the models learned before binning the features and after, we see that the linear model became much more flexible, because it now has a different value for each bin, while the decision tree model got much less flexible.\nBinning features generally has no beneficial effect for tree-based models, as these models can learn to split up the data anywhere.\nIn a sense, that means decision trees can learn whatever binning is most useful for predicting on this data.\nAdditionally, decision trees look at multiple features at once, while binning is usually done on a per-feature basis.\nHowever, the linear model benefited greatly in expressiveness from the transformation of the data.\nIf there are good reasons to use a linear model for a particular dataset -- say, because it is very large and high-dimensional, but some features have nonlinear relations with the output -- binning can be a great way to increase modeling power.\nInteractions and Polynomials\nAnother way to enrich a feature representation, particularly for linear models, is adding interaction features and polynomial features of the original data.\nThis kind of feature engineering is often used in statistical modeling, but it’s also common in many practical machine learning applications.\nAs a first example, look again at Figure 4-2.\nThe linear model learned a constant value for each bin in the wave dataset.\nWe know, however, that linear models can learn not only offsets, but also slopes.\nOne way to add a slope to the linear model on the binned data is to add the original feature (the x-axis in the plot) back in.\nThis leads to an 11-dimensional dataset, as seen in Figure 4-3:", "X_combined = np.hstack([X, X_binned])\nprint(X_combined.shape)\n\nreg = LinearRegression().fit(X_combined, y)\n\nline_combined = np.hstack([line, line_binned])\nplt.plot(line, reg.predict(line_combined),\n label=\"Linear Regression Combined\")\n\nfor bin in bins:\n plt.plot([bin, bin], [-3, 3], ':', c='k', linewidth=1)\nplt.legend(loc=\"best\")\nplt.ylabel(\"Regression Output\")\nplt.xlabel(\"Input Feature\")\nplt.plot(X[:, 0], y, 'o', c='k')", "In this example, the model learned an offset for each bin, together with a slope.\nThe learned slope is downward, and shared across all the bins --there is a single x-axis feature, which has a single slope.\nBecause the slope is shared across all bins, it doesn’t seem to be very helpful.\nWe would rather have a separate slope for each bin!\nWe can achieve this by adding an interaction or product feature that indicates which bin a data point is in and where it lies on the x-axis.\nThis feature is a product of the bin indicator and the original feature.\nLet’s create this dataset:", "X_product = np.hstack([X_binned, X * X_binned])\nprint(X_product.shape)", "The dataset now has 20 features: the indicators for which bin a data point is in, and a product of the original feature and the bin indicator.\nYou can think of the product feature as a separate copy of the x-axis feature for each bin.\nIt is the original feature within the bin, and zero everywhere else.\nFigure 4-4 shows the result of the linear model on this new representation:", "reg = LinearRegression().fit(X_product, y)\n\nline_product = np.hstack([line_binned, line * line_binned])\nplt.plot(line, reg.predict(line_product),\n label=\"Linear Regression Product\")\n\nfor bin in bins:\n plt.plot([bin, bin], [-3, 3], ':', c='k', linewidth=1)\n \nplt.plot(X[:, 0], y, 'o', c='k')\nplt.ylabel(\"Regression Output\")\nplt.xlabel(\"Input Features\")\nplt.legend()", "As you can see, now each bin has its own offset and slope in this model.\nUsing binning is one way to expand a continuous feature.\nAnother one is to use polynomials of the original features.\nFor a given feature x, we might want to consider x ** 2, x ** 3, x ** 4, and so on.\nThis is implemented in PolynomialFeatures in the preprocessing module:", "from sklearn.preprocessing import PolynomialFeatures\n# Include polynomials up to x ** 10.\n# The default \"include_bias=True\" adds a feature that's\n# constantly 1.\npoly = PolynomialFeatures(degree=10, include_bias=False)\npoly.fit(X)\nX_poly = poly.transform(X)", "Using a degree of 10 yields 10 features:", "print(\"X_poly.shape: {}\".format(X_poly.shape))", "Let's compare the entries of X_poly to those of X:", "print(\"Entries of X: \\n{}\".format(X[:5]))\n\nprint(\"Entries of X_poly: \\n{}\".format(X_poly[:5]))", "You can obtain the semantics of the features by calling the get_feature_names() method, which provides the exponent for each feature:", "print(\"Polynomial feature names: \\n{}\".format(\n poly.get_feature_names()))", "You can see that the first column of X_poly corresponds exactly to X, while the other columns are the powers of the first entry.\nIt’s interesting to see how large some of the values can get.\nThe second row has entries above 20,000, orders of magnitude different from the rest.\nUsing polynomial features together with a linear regression model yields the classical model of polynomial regression (see Figure 4-5):", "reg = LinearRegression().fit(X_poly, y)\nline_poly = poly.transform(line)\n\nplt.plot(line, reg.predict(line_poly),\n label=\"Polynomial Linear Regression\")\nplt.plot(X[:, 0], y, 'o', c='k')\nplt.ylabel(\"Regression Output\")\nplt.xlabel(\"Input Feature\")\nplt.legend()", "As you can see, polynomial features yield a very smooth fit on this one-dimensional data.\nHowever, polynomials of high degree tend to behave in extreme ways on the boundaries or in regions with little data.\nAs a comparison, here is a kernel SVM model learned on the original data, without any transformation (see Figure 4-6):", "from sklearn.svm import SVR\n\nfor gamma in [1, 10]:\n svr = SVR(gamma=gamma).fit(X, y)\n plt.plot(line, svr.predict(line),\n label=\"SVR gamma={}\".format(gamma))\n \nplt.plot(X[:, 0], y, 'o', c='k')\nplt.ylabel(\"Regression Output\")\nplt.xlabel(\"Input Feature\")\nplt.legend()", "Using a more complex model, a kernel SVM, we are able to learn a similarly complex prediction to the polynomial regression without an explicit transformation of the features.\nAs a more realistic application of interactions and polynomials, let’s look again at the Boston Housing dataset.\nWe already used polynomial features on this dataset in Chapter 2.\nNow let’s have a look at how these features were constructed, and at how much the polynomial features help.\nFirst we load the data, and rescale it to between 0 and 1 using MinMaxScaler:", "from sklearn.datasets import load_boston\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\n\nboston = load_boston()\nX_train, X_test, y_train, y_test = train_test_split(\n boston.data, boston.target, random_state=0)\n# Rescale the data:\nscaler = MinMaxScaler()\nX_train_scaled = scaler.fit_transform(X_train)\nX_test_scaled = scaler.transform(X_test)", "Now we extract polynomial features and interactions up to a degree of 2:", "poly = PolynomialFeatures(degree=2).fit(X_train_scaled)\nX_train_poly = poly.transform(X_train_scaled)\nX_test_poly = poly.transform(X_test_scaled)\nprint(\"X_train.shape: {}\".format(X_train.shape))\nprint(\"X_train_poly.shape: {}\".format(X_train_poly.shape))", "The data originally had 13 features, which were expanded into 105 interaction features.\nThese new features represent all possible interactions between two different original features, as well as the square of each original feature.\ndegree=2 here means that we look at all features that are the product of up to two original features.\nThe exact correspondence between input and output features can be found using the get_feature_names() method:", "print(\"Polynomial Feature Names: \\n{}\".format(\n poly.get_feature_names()))", "The first new feature is a constant feature, called \"1\" here. The next 13 features are the original features (called \"x0\" to \"x12\").\nThen follows the first feature squared (\"x0^2\") and combinations of the first and the other features.\nLet’s compare the performance using Ridge on the data with and without interactions:", "from sklearn.linear_model import Ridge\n\nridge = Ridge().fit(X_train_scaled, y_train)\nprint(\"Score without interactions: {:.3f}\".format(\n ridge.score(X_test_scaled, y_test)))\n\nridge = Ridge().fit(X_train_poly, y_train)\nprint(\"Score with interactions: {:.3f}\".format(\n ridge.score(X_test_poly, y_test)))", "Clearly, the interactions and polynomial features gave us a good boost inperformance when using Ridge.\nWhen using a more complex model like a random forest, the story is a bit different:", "from sklearn.ensemble import RandomForestRegressor\n\nrf = RandomForestRegressor(n_estimators=100).fit(\n X_train_scaled, y_train)\nprint(\"Score without interactions: {:.3f}\".format(\n rf.score(X_test_scaled, y_test)))\n\nrf = RandomForestRegressor(n_estimators=100).fit(\n X_train_poly, y_train)\nprint(\"Score with interactions: {:.3f}\".format(\n rf.score(X_test_poly, y_test)))", "You can see that even without additional features, the random forest beats the performance of Ridge.\nAdding interactions and polynomials actually decreases performance slightly.\nUnivariate Nonlinear Transformations\nWe just saw that adding squared or cubed features can help linear models for regression.\nThere are other transformations that often prove useful for transforming certain features: in particular, applying mathematical functions like log(), exp(), or sin().\nWhile tree-based models only care about the ordering of the features, linear models and neural networks are very tied to the scale and distribution of each feature, and if there is a nonlinear relation between the feature and the target, that becomes hard to model -- particularly in regression.\nThe functions log() and exp() can help by adjusting the relative scales in the data so that they can be captured better by a linear model or neural network.\nWe saw an application of that in Chapter 2 with the memory price data.\nThe sin() and cos() functions can come in handy when dealing with data that encodes periodic patterns.\nMost models work best when each feature (and in regression also the target) is loosely Gaussian distributed -- that is, a histogram of each feature should have something resembling the familiar \"bell curve\" shape.\nUsing transformations like log() and exp() is a hacky but simple and efficient way to achieve this.\nA particularly common case when such a transformation can be helpful is when dealing with integer count data.\nBy count data, we mean features like \"how often did user A log in?\"\nCounts are never negative, and often follow particular statistical patterns.\nWe are using a synthetic dataset of counts here that has properties similar to those you can find in the wild.\nThe features are all integer-valued, while the response is continuous:", "rnd = np.random.RandomState(0)\nX_org = rnd.normal(size=(1000, 3))\nw = rnd.normal(size=3)\n\n# The Poisson distribution is a discrete probability distribution\n# that expresses the probability of a given number of events \n# occurring in a fixed interval of time and/or space if these \n# events occur with a known constant rate and independently of\n# the time since the last event.\nX = rnd.poisson(10 * np.exp(X_org))\ny = np.dot(X_org, w)", "Let’s look at the first 10 entries of the first feature.\nAll are integer values and positive, but apart from that it’s hard to make out a particular pattern.\nIf we count the appearance of each value, the distribution of values becomes clearer:", "print(\"Number of Feature Appearances: \\n{}\".format(\n np.bincount(X[:, 0])))", "The value 2 seems to be the most common, with 68 appearances (bincount always starts at 0), and the counts for higher values fall quickly.\nHowever, there are some very high values, like 84 and 85, that are appearing twice.\nWe visualize the counts in Figure 4-7:", "bins = np.bincount(X[:, 0])\nplt.bar(range(len(bins)), bins, color='r')\nplt.ylabel(\"Number of Appearances\")\nplt.xlabel(\"Value\")", "Features X[:, 1] and X[:, 2] have similar properties.\nThis kind of distribution of values (many small ones and a few very large ones) is very common in practice.\nHowever, it is something most linear models can’t handle very well.\nLet’s try to fit a ridge regression to this model:", "from sklearn.linear_model import Ridge\n\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, random_state=0)\nscore = Ridge().fit(X_train, y_train).score(X_test, y_test)\nprint(\"Test score: {:.3f}\".format(score))", "As you can see from the relatively low $R^2$ score, Ridge was not able to really capture the relationship between X and y.\nApplying a logarithmic transformation can help, though.\nBecause the value 0 appears in the data (and the logarithm is not defined at 0), we can’t actually just apply log(), but we have to compute log(X + 1):", "X_train_log = np.log(X_train + 1)\nX_test_log = np.log(X_test + 1)\nprint(\"First entries of X_test: \\n{}\".format(X_test[:5]))\nprint()\nprint(\"First entries of X_test_log: \\n{}\".format(X_test_log[:5]))", "After the transformation, the distibution of the data is less asymmetrical and doesn't have any large outliers anymore (see Figure 4-8 and Figure 4-8A):", "plt.hist(X_train_log[:, 0], bins=25, color='gray')\nplt.ylabel(\"Number of Appearances\")\nplt.xlabel(\"Value\")", "Let's show a comparison with the un-transformed X_train data:", "plt.hist(X_train[:, 0], bins=25, color='gray')\nplt.ylabel(\"Number of Appearances\")\nplt.xlabel(\"Value\")", "As you will see, building a ridge model on the new data provides a much better fit:", "score = Ridge().fit(X_train_log, y_train).score(\n X_test_log, y_test)\nprint(\"Test Score: {:.3f}\".format(score))", "Finding the transformation that works best for each combination of dataset and model is somewhat of an art.\nIn this example, all the features had the same properties.\nThis is rarely the case in practice, and usually only a subset of the features should be transformed, or sometimes each feature needs to be transformed in a different way.\nAs we mentioned earlier, these kinds of transformations are irrelevant for tree-based models but might be essential for linear models.\nSometimes it is also a good idea to transform the target variable y in regression.\nTrying to predict counts (say, number of orders) is a fairly common task, and using the log(y + 1) transformation often helps.\nAs you saw in the previous examples, binning, polynomials, and interactions can have a huge influence on how models perform on a given dataset.\nThis is particularly true for less complex models like linear models and naive Bayes models.\nTree-based models, on the other hand, are often able to discover important interactions themselves, and don’t require transforming the data explicitly most of the time.\nOther models, like SVMs, nearest neighbors, and neural networks, might sometimes benefit from using binning, interactions, or polynomials, but the implications there are usually much less clear than in the case of linear models.\nAutomatic Feature Selection\nWith so many ways to create new features, you might get tempted to increase the dimensionality of the data way beyond the number of original features.\nHowever, adding more features makes all models more complex, and so increases the chance of overfitting.\nWhen adding new features, or with high-dimensional datasets in general, it can be a good idea to reduce the number of features to only the most useful ones, and discard the rest.\nThis can lead to simpler models that generalize better.\nBut how can you know how good each feature is?\nThere are three basic strategies: univariate statistics, model-based selection, and iterative selection.\nWe will discuss all three of them in detail.\nAll of these methods are supervised methods, meaning they need the target for fitting the model.\nThis means we need to split the data into training and test sets, and fit the feature selection only on the training part of the data.\nUnivariate Statistics\nIn univariate statistics, we compute whether there is a statistically significant relationship between each feature and the target.\nThen the features that are related with the highest confidence are selected.\nIn the case of classification, this is also known as analysis of variance (ANOVA).\nA key property of these tests is that they are univariate, meaning that they only consider each feature individually.\nConsequently, a feature will be discarded if it is only informative when combined with another feature.\nUnivariate tests are often very fast to compute, and don’t require building a model.\nOn the other hand, they are completely independent of the model that you might want to apply after the feature selection.\nTo use univariate feature selection in scikit-learn, you need to choose a test, usually either f_classif (the default) for classification or f_regression for regression, and a method to discard features based on the $p$-values determined in the test.\nAll methods for discarding parameters use a threshold to discard all features with too high a $p$-value (which means they are unlikely to be related to the target).\nThe methods differ in how they compute this threshold, with the simplest ones being SelectKBest, which selects a fixed number $k$ of features, and SelectPercentile, which selects a fixed percentage of features.\nLet’s apply the feature selection for classification on the cancer dataset.\nTo make the task a bit harder, we’ll add some noninformative noise features to the data.\nWe expect the feature selection to be able to identify the features that are noninformative and remove them:", "from sklearn.datasets import load_breast_cancer\nfrom sklearn.feature_selection import SelectPercentile\nfrom sklearn.model_selection import train_test_split\n\ncancer = load_breast_cancer()\n\n# Get deterministic random numbers\nrng = np.random.RandomState(42)\nnoise = rng.normal(size=(len(cancer.data), 50))\n# Add noise features to the data.\n# The first 30 features are from the dataset.\n# The next 50 features are randomly generated noise.\nX_w_noise = np.hstack([cancer.data, noise])\nX_w_noise[0]\n\nX_train, X_test, y_train, y_test = train_test_split(\n X_w_noise, cancer.target, random_state=0, test_size=0.5)\n# Use f_classif (the default) and SelectPercentile to\n# select 50% of features:\nselect = SelectPercentile(percentile=50)\nselect.fit(X_train, y_train)\n# Transform training set:\nX_train_selected = select.transform(X_train)\n\nprint(\"X_train.shape: {}\".format(X_train.shape))\nprint(\"X_train_selected.shape: {}\".format(\n X_train_selected.shape))", "As you can see, the number of features was reduced from 80 to 40 (50 percent of the original features).\nWe can find out which features have been selected using the get_support() method, which returns a Boolean mask of the slected features (visualized in Figure 4-9):", "mask = select.get_support()\nprint(mask)", "Nice, but visualizing the mask may be a bit more helpful.\nBlack is true, white is False:", "plt.matshow(mask.reshape(1, -1), cmap=\"gray_r\")\nplt.xlabel(\"Sample Index\")\nplt.yticks(())", "As you can see from the visualization of the mask, most of the selected features are the original features, and most of the noise features were removed.\nHowever, the recovery of the original features is not perfect.\nLet’s compare the performance of logistic regression on all features against the performance using only the selected features:", "from sklearn.linear_model import LogisticRegression\n\n# Transform test data:\nX_test_selected = select.transform(X_test)\n\nlr = LogisticRegression()\n\nlr.fit(X_train, y_train)\nprint(\"Score with all features: \\n{:.3f}\".format(\n lr.score(X_test, y_test)))\n\nlr.fit(X_train_selected, y_train)\nprint(\"Score with only the selected features: \\n{:.3f}\".format(\n lr.score(X_test_selected, y_test)))", "In this case, removing the noise features improved performance, even though some of the original features were lost.\nThis was a very simple synthetic example, and outcomes on real data are usually mixed.\nUnivariate feature selection can still be very helpful, though, if there is such a large number of features that building a model on them is infeasible, or if you suspect that many features are completely uninformative.\nModel-Based Feature Selection\nModel-based feature selection uses a supervised machine learning model to judge the importance of each feature, and keeps only the most important ones.\nThe supervised model that is used for feature selection doesn’t need to be the same model that is used for the final supervised modeling.\nThe feature selection model needs to provide some measure of importance for each feature, so that they can be ranked by this measure.\nDecision trees and decision tree–based models provide a feature_importances_ attribute, which directly encodes the importance of each feature.\nLinear models have coefficients, which can also be used to capture feature importances by considering the absolute values.\nAs we saw in Chapter 2, linear models with L1 penalty learn sparse coefficients, which only use a small subset of features.\nThis can be viewed as a form of feature selection for the model itself, but can also be used as a preprocessing step to select features for another model.\nIn contrast to univariate selection, model-based selection considers all features at once, and so can capture interactions (if the model can capture them).\nTo use model-based feature selection, we need to use the SelectFromModel transformer:", "from sklearn.feature_selection import SelectFromModel\nfrom sklearn.ensemble import RandomForestClassifier\n\nselect = SelectFromModel(\n RandomForestClassifier(n_estimators=100, random_state=42),\n threshold=\"median\")\nprint(select)", "The SelectFromModel class selects all features that have an importance measure of the feature (as provided by the supervised model) greater than the provided threshold.\nTo get a comparable result to what we got with univariate feature selection, we used the median as a threshold, so that half of the features will be selected.\nWe use a random forest classifier with 100 trees to compute the feature importances.\nThis is a quite complex model and much more powerful than using univariate tests.\nNow let’s actually fit the model:", "select.fit(X_train, y_train)\nX_train_l1 = select.transform(X_train)\nprint(\"X_train.shape: {}\".format(X_train.shape))\nprint(\"X_train_l1.shape: {}\".format(X_train_l1.shape))", "Again, we can have a look at the features that were selected (Figure 4-10):", "mask = select.get_support()\n# Visualize the mask; black is True, white is False\nplt.matshow(mask.reshape(1, -1), cmap='gray_r')\nplt.xlabel(\"Sample Index\")\nplt.yticks(())", "This time, all but two of the original features were selected.\nBecause we told the machine learning classifier to select 40 features, some of the noise features are also selected.\nLet's take a look at the performance:", "X_test_l1 = select.transform(X_test)\nscore = LogisticRegression().fit(\n X_train_l1, y_train).score(X_test_l1, y_test)\nprint(\"Test score: {:.3f}\".format(score))", "With the better feature selection, we also gained some improvements here.\nIterative Feature Selection\nIn univariate testing we used no model, while in model-based selection we used a single model to select features.\nIn iterative feature selection, a series of models are built, with varying numbers of features.\nThere are two basic methods: starting with no features and adding features one by one until some stopping criterion is reached, or starting with all features and removing features one by one until some stopping criterion is reached.\nBecause a series of models are built, these methods are much more computationally expensive than the methods we discussed previously.\nOne particular method of this kind is recursive feature elimination (RFE), which starts with all features, builds a model, and discards the least important feature according to the model.\nThen a new model is built using all but the discarded feature, and so on until only a prespecified number of features are left.\nFor this to work, the model used for selection needs to provide some way to determine feature importance, as was the case for the model-based selection.\nHere, we use the same random forest model that we used earlier, and get the results shown in Figure 4-11:", "from sklearn.feature_selection import RFE\n\nselect = RFE(\n RandomForestClassifier(n_estimators=100, random_state=42),\n n_features_to_select=40)\nselect.fit(X_train, y_train)\n# Visualize the selected features:\nmask = select.get_support()\nplt.matshow(mask.reshape(1, -1), cmap='gray_r')\nplt.xlabel(\"Sample Index\")\nplt.yticks(())", "The feature selection got better compared to the univariate and model-based selection, but one feature was still missed.\nRunning this code also takes significantly longer than that for the model-based selection, because a random forest model is trained 40 times, once for each feature that is dropped.\nLet’s test the accuracy of the logistic regression model when using RFE for feature selection:", "X_train_rfe = select.transform(X_train)\nX_test_rfe = select.transform(X_test)\n\nscore = LogisticRegression().fit(\n X_train_rfe, y_train).score(X_test_rfe, y_test)\nprint(\"Test Score: {:.3f}\".format(score))", "We can also use the model used inside the RFE to make predictions.\nThis uses only the feature set that was selected:", "print(\"Test Score: {:.3f}\".format(select.score(X_test, y_test)))", "Here, the performance of the random forest used inside the RFE is the same as that achieved by training a logistic regression model on top of the selected features.\nIn other words, once we’ve selected the right features, the linear model performs as well as the random forest.\nIf you are unsure when selecting what to use as input to your machine learning algorithms, automatic feature selection can be quite helpful.\nIt is also great for reducing the amount of features needed—for example, to speed up prediction or to allow for more interpretable models.\nIn most real-world cases, applying feature selection is unlikely to provide large gains in performance.\nHowever, it is still a valuable tool in the toolbox of the feature engineer.\nUtilizing Expert Knowledge\nFeature engineering is often an important place to use expert knowledge for a particular application.\nWhile the purpose of machine learning in many cases is to avoid having to create a set of expert-designed rules, that doesn’t mean that prior knowledge of the application or domain should be discarded.\nOften, domain experts can help in identifying useful features that are much more informative than the initial representation of the data.\nImagine you work for a travel agency and want to predict flight prices.\nLet’s say you have a record of prices together with dates, airlines, start locations, and destinations.\nA machine learning model might be able to build a decent model from that.\nSome important factors in flight prices, however, cannot be learned.\nFor example, flights are usually more expensive during peak vacation months and around holidays.\nWhile the dates of some holidays (like Christmas) are fixed, and their effect can therefore be learned from the date, others might depend on the phases of the moon (like Hanukkah and Easter) or be set by authorities (like school holidays).\nThese events cannot be learned from the data if each flight is only recorded using the (Gregorian) date.\nHowever, it is easy to add a feature that encodes whether a flight was on, preceding, or following a public or school holiday.\nIn this way, prior knowledge about the nature of the task can be encoded in the features to aid a machine learning algorithm.\nAdding a feature does not force a machine learning algorithm to use it, and even if the holiday information turns out to be noninformative for flight prices, augmenting the data with this information doesn’t hurt.\nWe'll now look at one particular case of using expert knowledge -- though in this case it might be more rightfully called \"common sense\".\nThe task is predicting bicycle rentals in front of Andreas’s house.\nIn New York, Citi Bike operates a network of bicycle rental stations with a subscription system.\nThe stations are all over the city and provide a convenient way to get around.\nBike rental data is made public in an anonymized form and has been analyzed in various ways.\nThe task we want to solve is to predict for a given time and day how many people will rent a bike in front of Andreas’s house—so he knows if any bikes will be left for him.\nWe first load the data for August 2015 for this particular station as a pandas DataFrame.\nWe resample the data into three-hour intervals to obtain the main trends for each day:", "citibike = mglearn.datasets.load_citibike()\nprint(\"Citi Bike Data: \\n{}\".format(citibike.head()))", "The following example shows a visualization of the rental frequencies for the whole month (Figure 4-12):", "plt.figure(figsize=(10, 3))\nxticks = pd.date_range(start=citibike.index.min(),\n end=citibike.index.max(), freq='D')\nplt.xticks(xticks, xticks.strftime(\"%a %m-%d\"),\n rotation=90, ha=\"left\")\nplt.plot(citibike, linewidth=1)\nplt.xlabel(\"Date\")\nplt.ylabel(\"Rentals\")", "Looking at the data, we can clearly distinguish day and night for each 24-hour interval.\nThe patterns for weekdays and weekends also seem to be quite different.\nWhen evaluating a prediction task on a time series like this, we usually want to learn from the past and predict for the future.\nThis means when doing a split into a training and a test set, we want to use all the data up to a certain date as the training set and all the data past that date as the test set.\nThis is how we would usually use time series prediction: given everything that we know about rentals in the past, what do we think will happen tomorrow?\nWe will use the first 184 data points, corresponding to the first 23 days, as our training set, and the remaining 64 data points, corresponding to the remaining 8 days, as our test set.\nThe only feature that we are using in our prediction task is the date and time when a particular number of rentals occurred.\nSo, the input feature is the date and time—say, 2015-08-01 00:00:00 -- and the output is the number of rentals in the following three hours (three in this case, according to our DataFrame).\nA (surprisingly) common way that dates are stored on computers is using POSIX time, which is the number of seconds since January 1970 00:00:00 (aka the beginning of Unix time).\nAs a first try, we can use this single integer feature as our data representation:", "# Extract the target values (number of rentals):\ny = citibike.values\nprint(\"y[:5]: {}\".format(y[:5]))\n# Convert to POSIX time by dividing by 10**9:\nX = citibike.index.astype(\"int64\").values.reshape(-1, 1) // 10**9\nprint(\"X[:5]: \\n{}\".format(X[:5]))", "We first define a function to split the data into training and test sets, build the model, and visualize the result:", "# Use the first 184 data points for training,\n# and the rest for testing.\nn_train = 184\n\n# Function to evaluate and plot a regressor on\n# a given test set.\ndef eval_on_features(features, target, regressor):\n # Split the given features into train and test sets.\n X_train, X_test = features[:n_train], features[n_train:]\n # Split the target array as well.\n y_train, y_test = target[:n_train], target[N-train:]\n regressor.fit(X_train, y_train)\n print(\"Test-set R^2: {:.2f}\".format(\n regressor.score(X_test, y_test)))\n y_pred = regressor.predict(X_test)\n y_pred_train = regressor.predict(X_train)\n \n plt.figure(figsize=(10, 3))\n plt.xticks(range(0, len(X), 8), xticks.strftime(\n \"%a %m-%d\"), rotation=90, ha=\"left\")\n \n plt.plot(range(n_train), y_train, label=\"train\")\n plt.plot(range(n_train, len(y_test) + n_train), y_test,\n '-', label=\"test\")\n plt.plot(range(n_train), y_pred_train, '--',\n label=\"Training Prediction:\")\n plt.plot(range(n_train, len(y_test) + n_train), y_pred,\n '--', label=\"Testing Prediction:\")\n plt.legend(loc=(1.01, 0))\n plt.xlabel(\"Date\")\n plt.ylabel(\"Rentals\")", "We saw earlier that random forests require very little preprocessing of the data, which makes this seem like a good model to start with.\nWe use the POSIX time feature X and pass a random forest regressor to our eval_on_features function.\nFigure 4-13 shows the result:" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
letsgoexploring/teaching
winter2017/econ129/python/Econ129_Class_05_Complete.ipynb
mit
[ "import requests\nimport matplotlib.pyplot as plt\nimport numpy as np\n%matplotlib inline", "Class 5: Pandas\nPandas is a Python package for data analysis. Documentation and examples: http://pandas.pydata.org/\nPandas basics\nTo learn how Pandas works, we'll make use of a dataset containing long-run averages of inflation, money growth, and real GDP. The dataset is available here: http://www.briancjenkins.com/data/quantitytheory/csv/qtyTheoryData.csv. Recall that the quantity theory of money implies the following linear relationship between the long-run rate of money growth, the long-run rate of inflation, and the long-run rate of real GDP growth in a country:\n\\begin{align}\n\\text{inflation} & = \\text{money growth} - \\text{real GDP growth},\n\\end{align}\nGenerally, we treat real GDP growth and money supply growth as exogenous so this is a theory about the determination of inflation.\nNow, we could download the data manually, but we might as well use Python to do it. The requests module is good for this.", "# Use the requests module to download money growth and inflation data\nurl = 'http://www.briancjenkins.com/data/quantitytheory/csv/qtyTheoryData.csv'\nr = requests.get(url,verify=True)\n\nwith open('qtyTheoryData.csv','wb') as newFile:\n \n newFile.write(r.content)", "Import Pandas", "import pandas as pd", "Import data from a csv file\nPandas has a function called read_csv() for reading data from a csv file into a Pandas DataFrame object. Let's import the quantity thery data into a variable called df.", "# Import quantity theory data into a Pandas DataFrame called df with country names as the index.\ndf = pd.read_csv('qtyTheoryData.csv',index_col=0)\n\n# Print the first 5 rows\nprint(df.head(5))\n\n# Print the last 5 rows\nprint(df.tail())\n\n# Print the type of df\nprint(type(df))", "Properties of DataFrame objects\nLike entries in a spreadsheet file, elements in a DataFrame object have row and column coordinates. Column names are always strings.", "# Print the columns of df\nprint(df.columns)\n\n# Create a new variable called money equal to the 'money growth' column and print\nmoney = df['money growth']\nprint(money)\n\n# Print the type of the variable money\nprint(type(money))\n\n# Print the first 5 rows of just the inflation, money growth, and gdp growth columns\nprint(df[['inflation','money growth','gdp growth']].head())", "The set of row coordinates is the index. Index values can be strings, numbers, or dates.", "# Print the index of df\nprint(df.index)\n\n# Create a new variable called usa equal to the 'United States' row and print\nusa = df.loc['United States']\nprint(usa)\n\n# Print the inflation rate of the United States\nprint(df.loc['United States']['inflation'])\n\n# Print the inflation rate of the United States in a different way\nprint(df['inflation'].loc['United States'])\n\n# Create a new variable called first equal to the first row in the DataFrame and print\nfirst = df.iloc[0]\nprint(first)", "Create new columns by name.", "# Create a new column called 'difference' equal to the money growth column minus the inflation column and print the column\ndf['difference'] = df['money growth'] - df['inflation']\nprint(df['difference'])", "Methods\nA Pandas DataFrame has a bunch of useful methods defined for it. describe() returns some summary statistics.", "# Print the summary statistics for df\nprint(df.describe())", "While Pandas' describe function provides some good summary information, NumPy also has some useful functions for computing statistics. For example, the NumPy function corrcoef() computes the coefficient of correlation for two series.", "# Print the correlation coefficient for inflation and money growth\nprint('corr of inflation and money growth',np.corrcoef(df['inflation'],df['money growth'])[0][1])\n\n# Print the correlation coefficient for inflation and real GDP growth\nprint('corr of inflation and money growth',np.corrcoef(df['inflation'],df['gdp growth'])[0][1])\n\n# Print the correlation coefficient for money growth and real GDP growth\nprint('corr of inflation and money growth',np.corrcoef(df['money growth'],df['gdp growth'])[0][1])", "sort_values() returns a copy of the original DataFrame sorted along the given column. The optional argument ascending is set to True by default, but can be changed to False if you want to print the lowest first.", "# Print rows for the countries with the 10 lowest inflation rates\nprint(df.sort_values('inflation').head(10))\n\n# Print rows for the countries with the 10 lowest money growth rates\nprint(df.sort_values('money growth').head(10))\n\n# Print rows for the countries with the 10 highest inflation rates\nprint(df.sort_values('inflation',ascending=False).head(10))\n\n# Print rows for the countries with the 10 highest money growth rates\nprint(df.sort_values('money growth',ascending=False).head(10))", "sort_index() returns a copy of the original DataFrame sorted along the index. The optional argument ascending is set to True by default, but can be changed to False if you want to print the lowest first.", "# Print df with the index descending alphabetical order\nprint(df.sort_index(ascending=False))", "Quick plotting example\nConstruct a graph that visually confirms the quantity theory of money by making a scatter plot with average money growth on the horizontal axis and average inflation on the vertical axis. Add a 45 degree line and labels and a title.", "# Construct a well-labeled scatter plot of inflation against money growth\n\nplt.scatter(df['money growth'],df['inflation'],s=50,alpha = 0.25)\nplt.grid()\nplt.xlim([-0.2,1.2])\nplt.ylim([-0.2,1.2])\nplt.xlabel('money growth')\nplt.ylabel('inflation')\nplt.title('Average inflation against average money growth \\nfor '+str(len(df.index))+' countries.')" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
ComputationalModeling/spring-2017-danielak
past-semesters/fall_2016/day-by-day/day14-Schelling-1-dimensional-segregation-day1/Day_14_Pre_Class_Notebook.ipynb
agpl-3.0
[ "List manipulation in Python\nGoal for this assignment\nThe goal for this assignment is to learn to use the various methods for Python's list data type.\nYour name\n// put your name here!\nPart 1: working with lists in Python\nA list in Python is what is known as a compound data type, which is fundamentally used to group together other types of variables. It is possible for lists to have values of a variety of types (i.e., integers, strings, floating-point numbers, etc.) but in general people tend to create lists with a single data type. Lists are written as comma-separated values between square brackets, like so:\nodd_numbers = [1, 3, 5, 7, 9]\nand an empty list can be created by using square brackets with no values:\nempty_list = []\nThe number of elements of a list can be found by using the Python len() method: len(odd_numbers) would return 5, for example.\nLists are accessed using index values: odd_numbers[2] will return the 3rd element from the beginning of the list (since Python counts starting at 0). In this case, the value returned would be 5. Using negative numbers in the index gives you elements starting at the end. For example, odd_numbers[-1] gives you the last element in the list, and odd_numbers[-1] gives you the second-to-last number.\nLists can also be indexed by slicing the list, which gives you a sub-set of the list (which is also a list). A colon indicates that slicing is occurring, and you use the syntax my_array[start:end]. In this example, start is the index where you start, and end is the index after the one you want to end (in keeping with the rest of Python's syntax). If start or end are blank, the slice either begins at the beginning of the list or continues to the end of the list, respectively. \nYou can also add a third argument, which is the step. In other words, my_array[start:end:step] goes from start index to the index before end in steps of step. More concretely, my_array[1,6,2] will return a list composed of elements 1, 3, and 5 of that list, and my_array[::2] returns every second element in the list.\nIMPORTANT: you can do all of these things in Numpy, too!\nSome examples are below:", "even_numbers = [2, 4, 6, 8, 10, 12, 14]\n\ns1 = even_numbers[1:5] # returns the 2nd through 4th elements\nprint(\"s1:\", s1)\n\ns2 = even_numbers[2:] # returns the 3rd element thorugh the end\nprint(\"s2:\", s2)\n\ns3 = even_numbers[:-2] # returns everything but the last two elements\nprint(\"s3:\", s3)\n\ns4 = even_numbers[1:-2] # returns everything but the first element and the two elements on the end\nprint(\"s4:\", s4)\n\ns5 = even_numbers[1:-1:2] # returns every other element, starting with the second element and ending at the second-to-last\nprint(\"s5:\", s5)\n\ns6 = even_numbers[::-1] # starts at the end of the list and returns all elements in backwards order (reversing original list) \nprint(\"s6:\", s6)", "Now, try it yourself!\nUsing the array below, create and print out sub-arrays that do the following:\n\nprint out the first four elements (a-d)\nprint out the last three elements (g-i)\nstarting with the second element, print out every third element (b, e, h)", "some_letters = ['a','b','c','d','e','f','g','h','i']\n\n# put your code here!\n\n\n", "Part 2: list methods in Python\nThere are several useful methods that are built into lists in Python. A full explanation of all list methods can be found here. However, the most useful list methods are as follows:\nlist.append(x) - adds an item x to the end of your list.\nlist.extend(L) - extends the list by adding all items in the given list L. If you try to use the append() method, you will end up with a list that has an element that is another list - this creates a single, unified list made up of the two original lists.\nlist.insert(i, x) - insert item x at index position i. list.insert(0,x) inserts at the front of the list\nlist.pop(i) - removes the item at index i and returns it. If you don't give an index, list.pop() gives you the last item in the list.\nlist.reverse() - reverse the order of the elements of the list. This happens in place, and doesn't return anything.\nAn important note about copying lists in Python\nYou may try to copy a list so you can work with it:\nnew_list = old_list\nHowever, you'll find that if you modify new_list, you also modify old_list. That's because when you equate lists in the way shown above, you are creating a new list that \"points at\" the old values. To truly copy a list, you have to do the following: \nyou are still pointing at the old values, and can modify them. The (weird, but correct) way to copy a list is to say:\nnew_list = list(old_list)\nNow, try it yourself!\nUsing the arrays below, create new arrays, manipulate them as follows, and then print them out:\n\nCreate a new array C, which a copy of A, and append the numbers 7 and 8 to the end. (so the elements of C are 1,2,3,4,5,6,7,8)\nThen remove the third element of C and put it back into the array before the second element from the end (so its elements, in order, are 1, 2, 4, 5, 6, 3, 7, 8)\nMake a new array D that is a copy of A, and then extend it with the middle three elements of array B, using slicing to get the middle 3 elements of B, (so its elements, in order, are 1, 2, 3, 4, 5, 6, 'b', 'c', 'd').\nMake a new array E that is a copy of B, reverse the order of its elements, and then remove the first element (so its elements, in order, are 'd', 'c', 'b', 'a').", "A = [1,2,3,4,5,6]\nB = ['a','b','c','d','e']\n\n# put your code here!\n\n\n", "Assignment wrapup\nPlease fill out the form that appears when you run the code below. You must completely fill this out in order to receive credit for the assignment!", "from IPython.display import HTML\nHTML(\n\"\"\"\n<iframe \n\tsrc=\"https://goo.gl/forms/jXRNcKiQ8C3lvt8E2?embedded=true\" \n\twidth=\"80%\" \n\theight=\"1200px\" \n\tframeborder=\"0\" \n\tmarginheight=\"0\" \n\tmarginwidth=\"0\">\n\tLoading...\n</iframe>\n\"\"\"\n)", "Congratulations, you're done!\nSubmit this assignment by uploading it to the course Desire2Learn web page. Go to the \"Pre-class assignments\" folder, find the dropbox link for Day 14, and upload it there.\nSee you in class!" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
AllenDowney/ModSimPy
soln/chap03soln.ipynb
mit
[ "Modeling and Simulation in Python\nChapter 3\nCopyright 2017 Allen Downey\nLicense: Creative Commons Attribution 4.0 International", "# Configure Jupyter so figures appear in the notebook\n%matplotlib inline\n\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import functions from the modsim library\nfrom modsim import *\n\n# set the random number generator\nnp.random.seed(7)", "More than one State object\nHere's the code from the previous chapter, with two changes:\n\n\nI've added DocStrings that explain what each function does, and what parameters it takes.\n\n\nI've added a parameter named state to the functions so they work with whatever State object we give them, instead of always using bikeshare. That makes it possible to work with more than one State object.", "def step(state, p1, p2):\n \"\"\"Simulate one minute of time.\n \n state: bikeshare State object\n p1: probability of an Olin->Wellesley customer arrival\n p2: probability of a Wellesley->Olin customer arrival\n \"\"\"\n if flip(p1):\n bike_to_wellesley(state)\n \n if flip(p2):\n bike_to_olin(state)\n \ndef bike_to_wellesley(state):\n \"\"\"Move one bike from Olin to Wellesley.\n \n state: bikeshare State object\n \"\"\"\n state.olin -= 1\n state.wellesley += 1\n \ndef bike_to_olin(state):\n \"\"\"Move one bike from Wellesley to Olin.\n \n state: bikeshare State object\n \"\"\"\n state.wellesley -= 1\n state.olin += 1\n \ndef decorate_bikeshare():\n \"\"\"Add a title and label the axes.\"\"\"\n decorate(title='Olin-Wellesley Bikeshare',\n xlabel='Time step (min)', \n ylabel='Number of bikes')", "And here's run_simulation, which is a solution to the exercise at the end of the previous notebook.", "def run_simulation(state, p1, p2, num_steps):\n \"\"\"Simulate the given number of time steps.\n \n state: State object\n p1: probability of an Olin->Wellesley customer arrival\n p2: probability of a Wellesley->Olin customer arrival\n num_steps: number of time steps\n \"\"\"\n results = TimeSeries() \n for i in range(num_steps):\n step(state, p1, p2)\n results[i] = state.olin\n \n plot(results, label='Olin')", "Now we can create more than one State object:", "bikeshare1 = State(olin=10, wellesley=2)\n\nbikeshare2 = State(olin=2, wellesley=10)", "Whenever we call a function, we indicate which State object to work with:", "bike_to_olin(bikeshare1)\n\nbike_to_wellesley(bikeshare2)", "And you can confirm that the different objects are getting updated independently:", "bikeshare1\n\nbikeshare2", "Negative bikes\nIn the code we have so far, the number of bikes at one of the locations can go negative, and the number of bikes at the other location can exceed the actual number of bikes in the system.\nIf you run this simulation a few times, it happens often.", "bikeshare = State(olin=10, wellesley=2)\nrun_simulation(bikeshare, 0.4, 0.2, 60)\ndecorate_bikeshare()", "We can fix this problem using the return statement to exit the function early if an update would cause negative bikes.", "def bike_to_wellesley(state):\n \"\"\"Move one bike from Olin to Wellesley.\n \n state: bikeshare State object\n \"\"\"\n if state.olin == 0:\n return\n state.olin -= 1\n state.wellesley += 1\n \ndef bike_to_olin(state):\n \"\"\"Move one bike from Wellesley to Olin.\n \n state: bikeshare State object\n \"\"\"\n if state.wellesley == 0:\n return\n state.wellesley -= 1\n state.olin += 1", "Now if you run the simulation again, it should behave.", "bikeshare = State(olin=10, wellesley=2)\nrun_simulation(bikeshare, 0.4, 0.2, 60)\ndecorate_bikeshare()", "Comparison operators\nThe if statements in the previous section used the comparison operator ==. The other comparison operators are listed in the book.\nIt is easy to confuse the comparison operator == with the assignment operator =.\nRemember that = creates a variable or gives an existing variable a new value.", "x = 5", "Whereas == compares two values and returns True if they are equal.", "x == 5", "You can use == in an if statement.", "if x == 5:\n print('yes, x is 5')", "But if you use = in an if statement, you get an error.", "# If you remove the # from the if statement and run it, you'll get\n# SyntaxError: invalid syntax\n\n#if x = 5:\n# print('yes, x is 5')", "Exercise: Add an else clause to the if statement above, and print an appropriate message.\nReplace the == operator with one or two of the other comparison operators, and confirm they do what you expect.\nMetrics\nNow that we have a working simulation, we'll use it to evaluate alternative designs and see how good or bad they are. The metric we'll use is the number of customers who arrive and find no bikes available, which might indicate a design problem.\nFirst we'll make a new State object that creates and initializes additional state variables to keep track of the metrics.", "bikeshare = State(olin=10, wellesley=2, \n olin_empty=0, wellesley_empty=0)", "Next we need versions of bike_to_wellesley and bike_to_olin that update the metrics.", "def bike_to_wellesley(state):\n \"\"\"Move one bike from Olin to Wellesley.\n \n state: bikeshare State object\n \"\"\"\n if state.olin == 0:\n state.olin_empty += 1\n return\n state.olin -= 1\n state.wellesley += 1\n \ndef bike_to_olin(state):\n \"\"\"Move one bike from Wellesley to Olin.\n \n state: bikeshare State object\n \"\"\"\n if state.wellesley == 0:\n state.wellesley_empty += 1\n return\n state.wellesley -= 1\n state.olin += 1", "Now when we run a simulation, it keeps track of unhappy customers.", "run_simulation(bikeshare, 0.4, 0.2, 60)\ndecorate_bikeshare()", "After the simulation, we can print the number of unhappy customers at each location.", "bikeshare.olin_empty\n\nbikeshare.wellesley_empty", "Exercises\nExercise: As another metric, we might be interested in the time until the first customer arrives and doesn't find a bike. To make that work, we have to add a \"clock\" to keep track of how many time steps have elapsed:\n\n\nCreate a new State object with an additional state variable, clock, initialized to 0. \n\n\nWrite a modified version of step that adds one to the clock each time it is invoked.\n\n\nTest your code by running the simulation and check the value of clock at the end.", "bikeshare = State(olin=10, wellesley=2, \n olin_empty=0, wellesley_empty=0,\n clock=0)\n\n# Solution\n\ndef step(state, p1, p2):\n \"\"\"Simulate one minute of time.\n \n state: bikeshare State object\n p1: probability of an Olin->Wellesley customer arrival\n p2: probability of a Wellesley->Olin customer arrival\n \"\"\"\n state.clock += 1\n \n if flip(p1):\n bike_to_wellesley(state)\n \n if flip(p2):\n bike_to_olin(state)\n\n# Solution\n\nrun_simulation(bikeshare, 0.4, 0.2, 60)\ndecorate_bikeshare()\n\n# Solution\n\nbikeshare", "Exercise: Continuing the previous exercise, let's record the time when the first customer arrives and doesn't find a bike.\n\n\nCreate a new State object with an additional state variable, t_first_empty, initialized to -1 as a special value to indicate that it has not been set. \n\n\nWrite a modified version of step that checks whetherolin_empty and wellesley_empty are 0. If not, it should set t_first_empty to clock (but only if t_first_empty has not already been set).\n\n\nTest your code by running the simulation and printing the values of olin_empty, wellesley_empty, and t_first_empty at the end.", "# Solution\n\nbikeshare = State(olin=10, wellesley=2, \n olin_empty=0, wellesley_empty=0,\n clock=0, t_first_empty=-1)\n\n# Solution\n\ndef step(state, p1, p2):\n \"\"\"Simulate one minute of time.\n \n state: bikeshare State object\n p1: probability of an Olin->Wellesley customer arrival\n p2: probability of a Wellesley->Olin customer arrival\n \"\"\"\n state.clock += 1\n \n if flip(p1):\n bike_to_wellesley(state)\n \n if flip(p2):\n bike_to_olin(state)\n \n if state.t_first_empty != -1:\n return\n \n if state.olin_empty + state.wellesley_empty > 0:\n state.t_first_empty = state.clock\n\n# Solution\n\nrun_simulation(bikeshare, 0.4, 0.2, 60)\ndecorate_bikeshare()\n\n# Solution\n\nbikeshare" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
billzhao1990/CS231n-Spring-2017
assignment2/.ipynb_checkpoints/Dropout-checkpoint.ipynb
mit
[ "Dropout\nDropout [1] is a technique for regularizing neural networks by randomly setting some features to zero during the forward pass. In this exercise you will implement a dropout layer and modify your fully-connected network to optionally use dropout.\n[1] Geoffrey E. Hinton et al, \"Improving neural networks by preventing co-adaptation of feature detectors\", arXiv 2012", "# As usual, a bit of setup\nfrom __future__ import print_function\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom cs231n.classifiers.fc_net import *\nfrom cs231n.data_utils import get_CIFAR10_data\nfrom cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array\nfrom cs231n.solver import Solver\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\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\n\ndef rel_error(x, y):\n \"\"\" returns relative error \"\"\"\n return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))\n\n# Load the (preprocessed) CIFAR10 data.\n\ndata = get_CIFAR10_data()\nfor k, v in data.items():\n print('%s: ' % k, v.shape)", "Dropout forward pass\nIn the file cs231n/layers.py, implement the forward pass for dropout. Since dropout behaves differently during training and testing, make sure to implement the operation for both modes.\nOnce you have done so, run the cell below to test your implementation.", "np.random.seed(231)\nx = np.random.randn(500, 500) + 10\n\nfor p in [0.3, 0.6, 0.75]:\n out, _ = dropout_forward(x, {'mode': 'train', 'p': p})\n out_test, _ = dropout_forward(x, {'mode': 'test', 'p': p})\n\n print('Running tests with p = ', p)\n print('Mean of input: ', x.mean())\n print('Mean of train-time output: ', out.mean())\n print('Mean of test-time output: ', out_test.mean())\n print('Fraction of train-time output set to zero: ', (out == 0).mean())\n print('Fraction of test-time output set to zero: ', (out_test == 0).mean())\n print()", "Dropout backward pass\nIn the file cs231n/layers.py, implement the backward pass for dropout. After doing so, run the following cell to numerically gradient-check your implementation.", "np.random.seed(231)\nx = np.random.randn(10, 10) + 10\ndout = np.random.randn(*x.shape)\n\ndropout_param = {'mode': 'train', 'p': 0.8, 'seed': 123}\nout, cache = dropout_forward(x, dropout_param)\ndx = dropout_backward(dout, cache)\ndx_num = eval_numerical_gradient_array(lambda xx: dropout_forward(xx, dropout_param)[0], x, dout)\n\nprint('dx relative error: ', rel_error(dx, dx_num))", "Fully-connected nets with Dropout\nIn the file cs231n/classifiers/fc_net.py, modify your implementation to use dropout. Specificially, if the constructor the the net receives a nonzero value for the dropout parameter, then the net should add dropout immediately after every ReLU nonlinearity. After doing so, run the following to numerically gradient-check your implementation.", "np.random.seed(231)\nN, D, H1, H2, C = 2, 15, 20, 30, 10\nX = np.random.randn(N, D)\ny = np.random.randint(C, size=(N,))\n\nfor dropout in [0, 0.25, 0.5]:\n print('Running check with dropout = ', dropout)\n model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C,\n weight_scale=5e-2, dtype=np.float64,\n dropout=dropout, seed=123)\n\n loss, grads = model.loss(X, y)\n print('Initial loss: ', loss)\n\n for name in sorted(grads):\n f = lambda _: model.loss(X, y)[0]\n grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5)\n print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])))\n print()", "Regularization experiment\nAs an experiment, we will train a pair of two-layer networks on 500 training examples: one will use no dropout, and one will use a dropout probability of 0.75. We will then visualize the training and validation accuracies of the two networks over time.", "# Train two identical nets, one with dropout and one without\nnp.random.seed(231)\nnum_train = 500\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nsolvers = {}\ndropout_choices = [0, 0.5, 0.75]\nfor dropout in dropout_choices:\n model = FullyConnectedNet([500], dropout=dropout)\n print(dropout)\n\n solver = Solver(model, small_data,\n num_epochs=25, batch_size=100,\n update_rule='adam',\n optim_config={\n 'learning_rate': 5e-4,\n },\n verbose=True, print_every=100)\n solver.train()\n solvers[dropout] = solver\n\n# Plot train and validation accuracies of the two models\n\ntrain_accs = []\nval_accs = []\nfor dropout in dropout_choices:\n solver = solvers[dropout]\n train_accs.append(solver.train_acc_history[-1])\n val_accs.append(solver.val_acc_history[-1])\n\nplt.subplot(3, 1, 1)\nfor dropout in dropout_choices:\n plt.plot(solvers[dropout].train_acc_history, 'o', label='%.2f dropout' % dropout)\nplt.title('Train accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend(ncol=2, loc='lower right')\n \nplt.subplot(3, 1, 2)\nfor dropout in dropout_choices:\n plt.plot(solvers[dropout].val_acc_history, 'o', label='%.2f dropout' % dropout)\nplt.title('Val accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend(ncol=2, loc='lower right')\n\nplt.gcf().set_size_inches(15, 15)\nplt.show()", "Question\nExplain what you see in this experiment. What does it suggest about dropout?\nAnswer" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
sebastiandres/mat281
laboratorios/lab05-LinearRegression/LinearRegression.ipynb
cc0-1.0
[ "<header class=\"w3-container w3-teal\">\n<img src=\"images/utfsm.png\" alt=\"\" height=\"100px\" align=\"left\"/>\n<img src=\"images/mat.png\" alt=\"\" height=\"100px\" align=\"right\"/>\n</header>\n<br/><br/><br/><br/><br/>\nMAT281\nLaboratorio Aplicaciones de la Matemática en la Ingeniería\nRegresión Lineal\nINSTRUCCIONES\n\nAnoten su nombre y rol en la celda siguiente.\nDesarrollen los problemas de manera secuencial.\nGuarden constantemente con Ctr-S para evitar sorpresas.\nReemplacen en las celdas de código donde diga #FIX_ME por el código correspondiente.\nEjecuten cada celda de código utilizando Ctr-Enter", "# Configuracion para recargar módulos y librerías \n%reload_ext autoreload\n%autoreload 2\n\n# Si quieren graficos dentro del ipython notebook, sacar comentario a linea siguiente.\n#%matplotlib inline \n\nfrom IPython.core.display import HTML\n\nHTML(open(\"style/mat281.css\", \"r\").read())\n\nfrom mat281_code.lab import greetings\nalumno_1 = (\"Sebastian Flores\", \"2004001-7\")\nalumno_2 = (\"Maria Jose Vargas\", \"2004007-8\")\n\nHTML(greetings(alumno_1, alumno_2))", "Observación\nEste laboratorio utiliza la librería sklearn (oficialmente llamada scikit learn), puesto que buscamos aplicar la técnica de regresión lineal a datos tal como se haría en una aplicación real. \nEl laboratorio consiste de 2 secciones:\n\nExplicación de uso de regresión lineal en sklearn y análisis de residuos.\nAplicación a problema real.\n\n1. Regresión Lineal con sklearn\nGeneremos un conjunt de datos sintéticos para aplicar regresión lineal, utilizando numpy y sklearn. El modelo será inicialmente muy simple, del tipo\n$$ y = \\theta_0 + \\theta_1 \\ x_1 + \\theta_2 x_2 + \\varepsilon $$\ncon $x_i$, $\\theta_i$ e $y$ valores reales, y $\\varepsilon$ el error de medición.", "# Generando los datos\nimport numpy as np\n\n# Model\nm = 1000 # Number of data examples\ntrue_coefficients = np.array([27., 5.])\ntrue_intercept = 1982.\nn = len(true_coefficients) + 1\n\n# Data\nnx1, nx2 = 21, 26\nx1, x2 = np.meshgrid(np.linspace(-1.,1.,nx1), np.linspace(80.,120.,nx2))\nX = np.array([x1.flatten(), x2.flatten()]).T\nY = true_intercept + np.dot(X, true_coefficients)\n\n# Measurement contamination\nmeasurement_error = np.random.normal(size=Y.shape)\n\n# Mesured data\nY = Y + 200 * measurement_error/measurement_error.max()", "Visualicemos los datos que hemos generado.", "# Visualización de los datos\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n# Plot of data\nfig = plt.figure(figsize=(16,8))\nax = fig.add_subplot(111, projection='3d')\nax.scatter(X[:,0], X[:,1], Y, 'rs')\nplt.xlabel(\"X[:,0]\")\nplt.ylabel(\"X[:,1]\")\nplt.title(\"y\")\nplt.show()", "Apliquemos un modelo de regresión lineal, obteniendo el intercepto y coeficientes. Utilizando sklearn podemos obtener además la predicción bajo el modelo lineal de manera extremadamente sencilla.", "# Aplicando regresion lineal con sklearn a los datos\nfrom sklearn import linear_model\n\nregr = linear_model.LinearRegression(fit_intercept=True, normalize=False)\nregr.fit(X, Y) # No es necesario agregar la columna de 1s, el algooritmo lo hace por nosotros. \nprint \"Intercepto hallado: \", regr.intercept_\nprint \"Coeficientes hallados: \", regr.coef_\nY_pred = regr.predict(X) # Puedo verificar que valores daría el modelo en los puntos conocidos.", "Visualicemos simultáneamente los datos y la superficie generada con la regresión lineal.", "from matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n# Plot of data\nfig = plt.figure(figsize=(16,8))\nax = fig.add_subplot(111, projection='3d')\nax.scatter(X[:,0], X[:,1], Y, 'rs')\nax.plot_trisurf(X[:,0], X[:,1], Y_pred, color=\"r\", alpha=0.5, lw=0)\nplt.xlabel(\"X[:,0]\")\nplt.ylabel(\"X[:,1]\")\nplt.title(\"y\")\nplt.show()", "Hmm, se ve bastante bien. ¿Qué tal los residuos? ¿Responden a nuestra hipótesis de distribución normal? Realicemos una exploración visual.", "# Analisando gráfico de los residuos\nres = Y_pred - Y\nplt.figure(figsize=(16,8))\nplt.hist(res)\nplt.show()", "El gráfico anterior parece suficientemente normal. Utilicemos un test de normalidad para verificar que efectivamente los residuos tengan una distribución normal.", "# Analisis estadístico de residuos\nimport scipy.stats as stats\nz, pval = stats.normaltest(res)\nif pval < 0.05:\n print \"Not normal distribution\"\nprint \"p-value =\", pval", "Calculemos el error promedio en varias normas", "print \"Error promedio en norma 1:\\t\", np.linalg.norm(res,1)/len(res)\nprint \"Error promedio en norma 2:\\t\", np.linalg.norm(res,2)/len(res)\nprint \"Error promedio en norma inf:\\t\", np.linalg.norm(res,np.inf)", "Desafío 1\n[10%] Desafio 1.1\nUtilice el código anterior para generar los mismos datos, pero esta vez no contamine los datos con errores gausianos, sino con elija utilizar un error de tipo gamma, uniforme o poisson (o bien, alguna otra de las posibles). Utilice alguno de los siguientes códigos:\nPython\n gamma_measurement_error = np.random.gamma(1, size=Y.shape)\n uniform_measurement_error = np.random.uniform(size=Y.shape)-0.5\n weibull_measurement_error = np.random.weibull(1, size=Y.shape)", "# 1.1 Desafio \n# Codigo para generar datos con otro tipo de error de medicion\n# y para realizar regresión lineal y análisis de los datos.\n\n", "Desafío 1: Continuación\n[10%] 1.2 Indique el tipo de error introducido, y los valores obtenidos para el intercepto y los coeficientes.\nFIX ME: COMENTARIO AQUI \n[10%] 1.3 ¿Cómo se comparan los valores anteriores a los valores reales (conocidos) y los valores obtenidos para error normal?\nFIX ME: COMENTARIO AQUI \n[10%] 1.4 ¿Se logra reconocer que los residuos no corresponden a una distibución normal? ¿Cómo?\nFIX ME: COMENTARIO AQUI \n[10%] 1.5 Compare el error promedio (residuos) del modelo 1 (gausiano) con el modelo 2 (no gausiano), utilizando norma 1, norma 2 y norma infinito. ¿Que observa?\nFIX ME: COMENTARIO AQUI \nAplicación a datos reales\nUn conjunto de datos bastante interesante es el Motor Dataset, que contiene características de 392 automobiles, entre los años 1970 y 1982.\n<img src=\"images/delorean.jpg\" alt=\"\" width=\"600px\" align=\"middle\"/>\nEste conjunto de datos tiene los siguientes valores:\n\nRendimiento en millas por galon, mpg (real).\nCilindros del motor, cylinders (entero positivo).\nDisplazamiento del motor en pulgadas cúbicas, displacement (real).\nCaballos de fueza, horsepower (real).\nPeso en libras, weight (real).\nTiempo de aceleración de 0 a 100 km/h, acceleration (real).\nAño del modelo, model year (entero positivo).\nPais de origen, origin (entero positivo, categórico).\nNombre del Auto, car name (string, unico para cada dato).\n\nComo ya es tradición, exploraremos los datos utilizando head (o tail, o cat).", "%%bash\nhead data/auto-mpg.data.txt", "Desafío 2\n[10 %] Desafio 2.1\nRealice una regresión lineal a los datos, buscando predecir el rendimiento (en mpg) utilizando como predictores: el desplazamiento, los caballos de fuerza, el peso y la aceleración, correspondientes a las columnas 2, 3, 4 y 5. Utilice el código provisto anteriormente para ajustar un modelo de regresión lineal, obtener los coeficientes del modelo, realizar predicciones y analice los residuos. \nNo es necesario incluir gráficos (pero tampoco está prohibido).", "import numpy as np\n# Lectura de datos\nY = np.loadtxt(\"data/auto-mpg.data.txt\", delimiter=\" \", usecols=(0,))\nX = np.loadtxt(\"data/auto-mpg.data.txt\", delimiter=\" \", usecols=(2,3,4,5))\n\n# Procesamiento de datos", "Desafío 2 : Continuación\n2.2 [10%] ¿Qué valores se obtienen para el intercepto y los coeficientes de los datos?\nFIX ME: COMENTARIO AQUI \n2.3 [10%] ¿Cuál es el error de entrenamiento en las distintas normas?\nFIX ME: COMENTARIO AQUI \n2.4 [10%] ¿Qué tipo de residuo se obtienen? ¿Son gaussianos?\nFIX ME: COMENTARIO AQUI \nCalculo el rendimiento en mpg tendría el Delorean, si en base a cierta información sabemos que posee: \n\n6 cilindros\n174 pulgadas cúbicas desplazamiento. \n200 Caballos de fuerza.\n2712 libras de peso.\nUna aceleración de 10.5.\nSe construyó el año 1981.\n\nConsejo: Utilice el metodo .predict() apropiadamente.", "# Calcular el mpg aqui\nmpg = 0\nprint mpg", "Desafío 3\n[10%] 3.1 Indique el rendimiento del delorean. ¿Se corresponde con el valor medido de 21 mpg?\nFIX ME: COMENTARIO AQUI" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
felixcheung/spark-ml-streaming
ipython_notebook/Streaming k-means.ipynb
apache-2.0
[ "Visualizing Streaming k-means on IPython + Lightning\n<img src=\"http://lightning-viz.org/images/logo.png\" align=\"left\"><br><h1>Lightning</h1>DATA VISUALIZATION SERVER\n<br>\n<br>\nLightning is a data-visualization server providing API-based access to reproducible, web-based, interactive visualizations. It includes a core set of visualization types, but is built for extendability and customization. Lightning supports modern libraries like d3.js and three.js, and is designed for interactivity over large data sets and continuously updating data streams.\nhttp://lightning-viz.org\n<br>\nAPI: node.js, Python, Scala\nExtension support for custom chart (eg. d3.js)\n<br>\nLightning requirements:\n - Postgres recommended (SQLlite ok)\n - node.js (npm , gulp)", "from IPython.display import IFrame\nIFrame('https://lightning-docs.herokuapp.com/visualizations/4/iframe/', 1155, 673)", "The Freeman Lab at Janelia Research Campus uses Lightning to visualize large-scale neural recordings from zebrafish, in collaboration with the Ahrens Lab", "from IPython.display import Image\nImage('http://lightning-viz.org/images/featured-graphic.png')", "Let's get started\nSpark Streaming k-means demo\nEnvironment\nrequires: numpy, scipy, scikit-learn\n IPython/Python requires: lightning-python package\nDemo consists of 3 parts\n\nPython driver script, data generator\nScala job - Spark Streaming - Streaming k-means\nIPython client to process result, visualize with Lightning\n\nOriginally this was part of the Python driver script - it has been modified for this talk to run within IPython \nFirst, some helper functions", "import os\nimport glob\nfrom numpy import loadtxt\nfrom StringIO import StringIO\n\ndef loadrecent(filename, oldtime, oldoutput):\n try:\n fname = max(glob.iglob(filename), key=os.path.getctime)\n except:\n #print('No file found')\n return [], oldtime\n\n newtime = os.path.getctime(fname)\n if not (newtime > oldtime):\n #print('File is not new')\n return oldoutput, oldtime\n\n try:\n f = open(fname)\n if os.fstat(f.fileno()).st_size == 0:\n print('File is empty')\n return [], oldtime\n except:\n print('Cannot load file')\n return [], oldtime\n\n prediction = loadtxt(fname, delimiter=',')\n return prediction, newtime\n\ndef readcenters(i):\n \"\"\" Read integer labels \"\"\"\n #print (os.path.join(datainlabels, 'labels%g.txt' % i))\n try:\n centers = loadtxt(os.path.join(datainlabels, 'labels%g.txt' % i), dtype=int)\n except:\n print('Cannot load cluster membership labels', sys.exc_info())\n return array([])\n\n return centers\n \ndef readpts(i):\n \"\"\" Read original points \"\"\"\n try:\n with open (os.path.join(datain, 'batch%g.txt' % i), 'r') as ptsfile:\n ptscontent=ptsfile.read().replace('[', '').replace(']', '')\n\n pts = loadtxt(StringIO(ptscontent), delimiter=',')\n except:\n print('Cannot load points', sys.exc_info())\n return array([])\n\n return pts\n ", "Processing k-means model\n1. read model computed by Spark Streaming k-means\n2. compute results with numpy\n3. add to Lightning's streaming viz, displaying it as an iFrame in IPython", "\nimport time\nfrom numpy import asarray, array, vstack, hstack, size, random, argsort, ones, argmin, sin, cos, pi\nfrom IPython.display import display, IFrame, HTML\n\ndef run(dataout, nbatches, ncenters, ndims, lgn=None, npoints = 50):\n viz = None\n modeltime = 0\n model = []\n\n # loop over batches\n for i in range(1, nbatches):\n time.sleep(1)\n\n # get the latest model (after waiting)\n oldtime = modeltime\n model, modeltime = loadrecent(dataout + '/*-model.txt', modeltime, model)\n\n # plot an update (if we got a valid model)\n if len(model) == ncenters:\n\n if (oldtime != modeltime):\n centers = readcenters(i)\n pts = readpts(i)\n \n # pts.size should == len(pts) * 2\n if (len(centers) == npoints & len(pts) == npoints):\n\n clrs = centers\n order = argsort(centers)\n clrs = clrs[order]\n pts = pts[order]\n s = ones(npoints) * 10\n\n if ndims == 1:\n pts = vstack((pts, model[:,None]))\n else:\n pts = vstack((pts, model))\n clrs = hstack((clrs, ones(ncenters) * 5))\n s = hstack((s, ones(ncenters) * 10))\n\n # wait a few iterations before plotting\n if (i > 5):\n\n # scatter plot for two dimensions\n if ndims == 2:\n if viz is None:\n viz = lgn.scatterstreaming(pts[:, 0], pts[:, 1], label=clrs, size=s)\n display(IFrame(viz.get_permalink(), width=1280, height=1280))\n else:\n viz.append(pts[:, 0], pts[:, 1], label=clrs, size=s)\n\n # line plot for one dimension\n elif ndims == 1:\n if viz is None:\n viz = lgn.linestreaming(pts, label=clrs, size=s/2)\n display(IFrame(viz.get_permalink(), width=1280, height=1280))\n else:\n viz.append(pts, label=clrs, size=s/2)\n \n else:\n raise Exception('Plotting only supported with 1 or 2 dimensions')\n", "Now, let's create the Lightning session and kick start the loop above\nTo run,\n- ensure the Lightning server is running\n- start the Python driver script and wait 2-3 seconds for it to clean up the input/output data directory\n- then execute the cell below", "import os\nimport tempfile\nfrom lightning import Lightning\n\nncenters = 4 # 9\nndims = 2 # 1\nnbatches = 100 # nb 100, 40\nlightninghost = 'http://192.168.128.1:3000'\n\npath = os.path.join(tempfile.gettempdir(), 'streamkmeans')\ndataout = os.path.join(path, 'output')\ndatain = os.path.join(path, 'input')\ndatainlabels = os.path.join(path, 'inputlbl')\n\nlgn = Lightning(lightninghost) #, ipython=True)\nlgn.create_session('streaming-kmeans')\nrun(dataout, nbatches, ncenters, ndims, lgn)\n" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
kubeflow/pipelines
samples/contrib/e2e-outlier-drift-explainer/seldon/seldon_e2e_cifar10.ipynb
apache-2.0
[ "Seldon Deployment Pipeline For CIFAR10 Image Recognition\nIn this example (and Kale Kubeflow pipeline) we create a deployment pipeline for a pretrained CIFAR10 image model. \nThe following steps will be run:\n\nSetup Minio client\nDownload and test CIFAR10 model and train an Anchors Images explainer on it. Save both model and explainer to Minio.\nDeploy model and explainer using Seldon and test\nTrain outlier detector\nTrain drift detector\nDeploy knative eventing display to show asynchronous results from outlier and drift detectors. \nDeploy outlier detector and test\ndeploy drift detector and test\n\n### Setup\nYou will need a kubeflow cluster >= 1.0 with \n\nKnative eventing \nSeldon >= 1.2.1\n\n### Kubeflow Jupyter Notebook Server\nTo run this notebook inside kubeflow. Create a Jupyter notebook server using the image seldonio/jupyter-lab-alibi-kale:0.11\n### GCP Setup\nOn GCP If you use Kale to save this notebook as a pipeline you will need to add the storage_class of the VolumeOp to nfs-client if you have followed the steps to create a NFS RWX PV on GCP. e.g.:\nmarshal_vop = dsl.VolumeOp(\n name=\"kale-marshal-volume\",\n resource_name=\"kale-marshal-pvc\",\n storage_class=\"nfs-client\",\n modes=dsl.VOLUME_MODE_RWM,\n size=\"1Gi\"\n )", "import numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\nfrom alibi.explainers import AnchorImage\nfrom alibi.datasets import fetch_adult\nfrom minio import Minio\nfrom minio.error import ResponseError\nfrom joblib import dump, load\nimport dill\nfrom subprocess import run, Popen, PIPE\nfrom alibi_detect.utils.data import create_outlier_batch\nfrom alibi_detect.utils.fetching import fetch_tf_model\nimport json\nimport logging\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\ntf.keras.backend.clear_session()\nfrom tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Layer, Reshape, InputLayer\nfrom tqdm import tqdm\n\nfrom alibi_detect.models.losses import elbo\nfrom alibi_detect.od import OutlierVAE\nfrom alibi_detect.utils.fetching import fetch_detector\nfrom alibi_detect.utils.perturbation import apply_mask\nfrom alibi_detect.utils.saving import save_detector, load_detector\nfrom alibi_detect.utils.visualize import plot_instance_score, plot_feature_outlier_image\nimport time\n\nlogger = tf.get_logger()\nlogger.setLevel(logging.ERROR)", "Setup Pipeline Paramers\nThe following global variables can be set. These will be used as Pipeline parameters.", "MINIO_HOST=\"minio-service.kubeflow:9000\"\nMINIO_ACCESS_KEY=\"minio\"\nMINIO_SECRET_KEY=\"minio123\"\nMINIO_MODEL_BUCKET=\"seldon\"\nCIFAR10_MODEL_PATH=\"tfserving/cifar10/model\"\nEXPLAINER_MODEL_PATH=\"tfserving/cifar10/explainer\"\nOUTLIER_MODEL_PATH=\"tfserving/cifar10/outlier\"\nDRIFT_MODEL_PATH=\"tfserving/cifar10/drift\"\nDEPLOY_NAMESPACE=\"admin\"\nTRAIN_OUTLIER_DETECTOR=False\nTRAIN_DRIFT_DETECTOR=False\n\ndef get_minio():\n return Minio(MINIO_HOST,\n access_key=MINIO_ACCESS_KEY,\n secret_key=MINIO_SECRET_KEY,\n secure=False)\n\nminioClient = get_minio()\nbuckets = minioClient.list_buckets()\nfor bucket in buckets:\n print(bucket.name, bucket.creation_date)\n\nif not minioClient.bucket_exists(MINIO_MODEL_BUCKET):\n minioClient.make_bucket(MINIO_MODEL_BUCKET)", "Test and save Model\nFor simplicity we will use a pretrained Resnet32 CIFAR10 tensorflow model", "model = fetch_tf_model('cifar10', 'resnet32')\n\ntrain, test = tf.keras.datasets.cifar10.load_data()\nX_train, y_train = train\nX_test, y_test = test\n\nX_train = X_train.astype('float32') / 255\nX_test = X_test.astype('float32') / 255\nprint(X_train.shape, y_train.shape, X_test.shape, y_test.shape)\n\nclass_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n 'dog', 'frog', 'horse', 'ship', 'truck']", "Test model locally.", "idx = 1\nX = X_test[idx].reshape(1, 32, 32, 3)\nplt.imshow(X.reshape(32, 32, 3))\nplt.axis('off')\nplt.show()\nprint(\"class:\",class_names[y_test[idx][0]])\nprint(\"prediction:\",class_names[model.predict(X_test[idx:idx+1])[0].argmax()])\n\nmodelfilepath=\"resnet\"\ntf.saved_model.save(model, modelfilepath)\n\nfrom os import listdir\nfrom os.path import isfile, join\n\nmodel_filepath=\"resnet\"\nprint(get_minio().fput_object(MINIO_MODEL_BUCKET, f\"{CIFAR10_MODEL_PATH}/1/saved_model.pb\", modelfilepath+\"/saved_model.pb\"))\nvariable_filepath = modelfilepath+\"/variables\"\nonlyfiles = [f for f in listdir(variable_filepath) if isfile(join(variable_filepath, f))]\nfor filename in onlyfiles:\n print(filename)\n print(get_minio().fput_object(MINIO_MODEL_BUCKET, f\"{CIFAR10_MODEL_PATH}/1/variables/{filename}\", join(variable_filepath, filename)))", "Train Explainer", "def predict_fn(x):\n return model.predict(x)\n\n\nimage_shape = (32, 32, 3)\nsegmentation_fn = 'slic'\nkwargs = {'n_segments': 5, 'compactness': 20, 'sigma': .5}\nexplainer = AnchorImage(predict_fn, image_shape, segmentation_fn=segmentation_fn, \n segmentation_kwargs=kwargs, images_background=None)\n\nidx=0\nimage = X_test[0]\nnp.random.seed(0)\nexplanation = explainer.explain(image, threshold=.95, p_sample=.5, tau=0.25)\n\nX = X_test[idx].reshape(1, 32, 32, 3)\nplt.imshow(X.reshape(32, 32, 3))\nplt.axis('off')\nplt.show()\nprint(\"class:\",class_names[y_test[idx][0]])\nprint(\"prediction:\",class_names[model.predict(X_test[idx:idx+1])[0].argmax()])\n\nplt.imshow(explanation[\"anchor\"])\n\nwith open(\"explainer.dill\", \"wb\") as dill_file:\n dill.dump(explainer, dill_file) \n dill_file.close()\nprint(get_minio().fput_object(MINIO_MODEL_BUCKET, f\"{EXPLAINER_MODEL_PATH}/explainer.dill\", 'explainer.dill'))", "Train Outlier Detector\nFor further details and extended notebook see Alibi-Detect Documentation. These steps were derived from Alibi-Detect CIFAR10 Example", "import logging\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\ntf.keras.backend.clear_session()\nfrom tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Layer, Reshape, InputLayer\nfrom tqdm import tqdm\n\nfrom alibi_detect.models.losses import elbo\nfrom alibi_detect.od import OutlierVAE\nfrom alibi_detect.utils.fetching import fetch_detector\nfrom alibi_detect.utils.perturbation import apply_mask\nfrom alibi_detect.utils.saving import save_detector, load_detector\nfrom alibi_detect.utils.visualize import plot_instance_score, plot_feature_outlier_image\n\nlogger = tf.get_logger()\nlogger.setLevel(logging.ERROR)\n\nif TRAIN_OUTLIER_DETECTOR:\n latent_dim = 1024\n \n encoder_net = tf.keras.Sequential(\n [\n InputLayer(input_shape=(32, 32, 3)),\n Conv2D(64, 4, strides=2, padding='same', activation=tf.nn.relu),\n Conv2D(128, 4, strides=2, padding='same', activation=tf.nn.relu),\n Conv2D(512, 4, strides=2, padding='same', activation=tf.nn.relu)\n ])\n\n decoder_net = tf.keras.Sequential(\n [\n InputLayer(input_shape=(latent_dim,)),\n Dense(4*4*128),\n Reshape(target_shape=(4, 4, 128)),\n Conv2DTranspose(256, 4, strides=2, padding='same', activation=tf.nn.relu),\n Conv2DTranspose(64, 4, strides=2, padding='same', activation=tf.nn.relu),\n Conv2DTranspose(3, 4, strides=2, padding='same', activation='sigmoid')\n ])\n \n # initialize outlier detector\n od = OutlierVAE(threshold=.015, # threshold for outlier score\n score_type='mse', # use MSE of reconstruction error for outlier detection\n encoder_net=encoder_net, # can also pass VAE model instead\n decoder_net=decoder_net, # of separate encoder and decoder\n latent_dim=latent_dim,\n samples=2)\n # train\n od.fit(X_train, \n loss_fn=elbo,\n cov_elbo=dict(sim=.05),\n epochs=50,\n verbose=True)\nelse:\n od = load_detector(\"/home/models/samples/od/cifar10\")\n\nidx = 8\nX = X_train[idx].reshape(1, 32, 32, 3)\nX_recon = od.vae(X)\nplt.imshow(X.reshape(32, 32, 3))\nplt.axis('off')\nplt.show()\nplt.imshow(X_recon.numpy().reshape(32, 32, 3))\nplt.axis('off')\nplt.show()\n\nX = X_train[:500]\nprint(X.shape)\nod_preds = od.predict(X,\n outlier_type='instance', # use 'feature' or 'instance' level\n return_feature_score=True, # scores used to determine outliers\n return_instance_score=True)\nprint(list(od_preds['data'].keys()))\ntarget = np.zeros(X.shape[0],).astype(int) # all normal CIFAR10 training instances\nlabels = ['normal', 'outlier']\nplot_instance_score(od_preds, target, labels, od.threshold)\n\nfrom alibi_detect.utils.saving import save_detector, load_detector\nfrom os import listdir\nfrom os.path import isfile, join\n\nfilepath=\"cifar10outlier\"\nsave_detector(od, filepath) \nonlyfiles = [f for f in listdir(filepath) if isfile(join(filepath, f))]\nfor filename in onlyfiles:\n print(filename)\n print(get_minio().fput_object(MINIO_MODEL_BUCKET, f\"{OUTLIER_MODEL_PATH}/{filename}\", join(filepath, filename)))\nfilepath=\"cifar10outlier/model\"\nonlyfiles = [f for f in listdir(filepath) if isfile(join(filepath, f))]\nfor filename in onlyfiles:\n print(filename)\n print(get_minio().fput_object(MINIO_MODEL_BUCKET, f\"{OUTLIER_MODEL_PATH}/model/{filename}\", join(filepath, filename)))", "Train a Drift Detector", "import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Conv2D, Dense, Flatten, InputLayer, Reshape\n\nfrom alibi_detect.cd import KSDrift\nfrom alibi_detect.cd.preprocess import uae, hidden_output\nfrom alibi_detect.models.resnet import scale_by_instance\nfrom alibi_detect.utils.fetching import fetch_tf_model, fetch_detector\nfrom alibi_detect.utils.prediction import predict_batch\nfrom alibi_detect.utils.saving import save_detector, load_detector\nfrom alibi_detect.datasets import fetch_cifar10c, corruption_types_cifar10c\n\ntf.random.set_seed(0)\n\nif True:\n np.random.seed(0)\n n_test = X_test.shape[0]\n idx = np.random.choice(n_test, size=n_test // 2, replace=False)\n idx_h0 = np.delete(np.arange(n_test), idx, axis=0)\n X_ref,y_ref = X_test[idx], y_test[idx]\n X_h0, y_h0 = X_test[idx_h0], y_test[idx_h0]\n print(X_ref.shape, X_h0.shape)\n # define encoder\n encoding_dim = 32\n encoder_net = tf.keras.Sequential(\n [\n InputLayer(input_shape=(32, 32, 3)),\n Conv2D(64, 4, strides=2, padding='same', activation=tf.nn.relu),\n Conv2D(128, 4, strides=2, padding='same', activation=tf.nn.relu),\n Conv2D(512, 4, strides=2, padding='same', activation=tf.nn.relu),\n Flatten(),\n Dense(encoding_dim,)\n ]\n )\n\n # initialise drift detector\n p_val = .05\n cd = KSDrift(\n p_val=p_val, # p-value for K-S test\n X_ref=X_ref, # test against original test set\n preprocess_fn=uae, # UAE for dimensionality reduction\n preprocess_kwargs={'encoder_net': encoder_net, 'batch_size': 128},\n alternative='two-sided' # other options: 'less', 'greater'\n )\nelse:\n cd = load_detector(\"/home/models/samples/cd/cifar10\")\n\nfrom alibi_detect.utils.saving import save_detector, load_detector\nfrom os import listdir\nfrom os.path import isfile, join\n\nfilepath=\"cifar10Drift\"\nsave_detector(cd, filepath) \nonlyfiles = [f for f in listdir(filepath) if isfile(join(filepath, f))]\nfor filename in onlyfiles:\n print(filename)\n print(get_minio().fput_object(MINIO_MODEL_BUCKET, f\"{DRIFT_MODEL_PATH}/{filename}\", join(filepath, filename)))\nfilepath=\"cifar10Drift/model\"\nonlyfiles = [f for f in listdir(filepath) if isfile(join(filepath, f))]\nfor filename in onlyfiles:\n print(filename)\n print(get_minio().fput_object(MINIO_MODEL_BUCKET, f\"{DRIFT_MODEL_PATH}/model/{filename}\", join(filepath, filename)))", "Deploy Seldon Core Model", "secret = f\"\"\"apiVersion: v1\nkind: Secret\nmetadata:\n name: seldon-init-container-secret\n namespace: {DEPLOY_NAMESPACE}\ntype: Opaque\nstringData:\n AWS_ACCESS_KEY_ID: {MINIO_ACCESS_KEY}\n AWS_SECRET_ACCESS_KEY: {MINIO_SECRET_KEY}\n AWS_ENDPOINT_URL: http://{MINIO_HOST}\n USE_SSL: \"false\"\n\"\"\"\nwith open(\"secret.yaml\",\"w\") as f:\n f.write(secret)\nrun(\"cat secret.yaml | kubectl apply -f -\", shell=True)\n\nsa = f\"\"\"apiVersion: v1\nkind: ServiceAccount\nmetadata:\n name: minio-sa\n namespace: {DEPLOY_NAMESPACE}\nsecrets:\n - name: seldon-init-container-secret\n\"\"\"\nwith open(\"sa.yaml\",\"w\") as f:\n f.write(sa)\nrun(\"kubectl apply -f sa.yaml\", shell=True)\n\nmodel_yaml=f\"\"\"apiVersion: machinelearning.seldon.io/v1\nkind: SeldonDeployment\nmetadata:\n name: cifar10-classifier\n namespace: {DEPLOY_NAMESPACE}\nspec:\n protocol: tensorflow\n predictors:\n - componentSpecs:\n graph:\n implementation: TENSORFLOW_SERVER\n modelUri: s3://{MINIO_MODEL_BUCKET}/{CIFAR10_MODEL_PATH}\n envSecretRefName: seldon-init-container-secret\n name: classifier\n logger:\n mode: all\n explainer:\n type: AnchorImages\n name: default\n replicas: 1\n\"\"\"\nwith open(\"model.yaml\",\"w\") as f:\n f.write(model_yaml)\nrun(\"kubectl apply -f model.yaml\", shell=True)\n\nrun(f\"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/$(kubectl get deploy -l seldon-deployment-id=cifar10-classifier -o jsonpath='{{.items[0].metadata.name}}' -n {DEPLOY_NAMESPACE})\", shell=True)\n\nrun(f\"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/$(kubectl get deploy -l seldon-deployment-id=cifar10-classifier -o jsonpath='{{.items[1].metadata.name}}' -n {DEPLOY_NAMESPACE})\", shell=True)", "Make a prediction request", "def test_model():\n idx=10\n test_example=X_test[idx:idx+1].tolist()\n payload='{\"instances\":'+f\"{test_example}\"+' }'\n cmd=f\"\"\"curl -d '{payload}' \\\n http://cifar10-classifier-default.{DEPLOY_NAMESPACE}:8000/v1/models/classifier/:predict \\\n -H \"Content-Type: application/json\"\n \"\"\"\n ret = Popen(cmd, shell=True,stdout=PIPE)\n raw = ret.stdout.read().decode(\"utf-8\")\n print(raw)\n res=json.loads(raw)\n arr=np.array(res[\"predictions\"])\n X = X_test[idx].reshape(1, 32, 32, 3)\n plt.imshow(X.reshape(32, 32, 3))\n plt.axis('off')\n plt.show()\n print(\"class:\",class_names[y_test[idx][0]])\n print(\"prediction:\",class_names[arr[0].argmax()])\n\nok = False\nwhile not ok:\n try:\n test_model()\n ok = True\n except:\n print(\"Failed calling model, sleeping\")\n time.sleep(2)", "Make an explanation request", "idx=10\ntest_example=X_test[idx:idx+1].tolist()\npayload='{\"instances\":'+f\"{test_example}\"+' }'\ncmd=f\"\"\"curl -d '{payload}' \\\n http://cifar10-classifier-default-explainer.{DEPLOY_NAMESPACE}:9000/v1/models/cifar10-classifier/:explain \\\n -H \"Content-Type: application/json\"\n\"\"\"\nret = Popen(cmd, shell=True,stdout=PIPE)\nraw = ret.stdout.read().decode(\"utf-8\")\nprint(raw)", "Deploy KNative Eventing Event Display", "event_display=f\"\"\"apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: event-display\n namespace: {DEPLOY_NAMESPACE} \nspec:\n replicas: 1\n selector:\n matchLabels: &labels\n app: event-display\n template:\n metadata:\n labels: *labels\n spec:\n containers:\n - name: helloworld-go\n # Source code: https://github.com/knative/eventing-contrib/tree/master/cmd/event_display\n image: gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display@sha256:f4628e97a836c77ed38bd3b6fd3d0b06de4d5e7db6704772fe674d48b20bd477\n---\nkind: Service\napiVersion: v1\nmetadata:\n name: event-display\n namespace: {DEPLOY_NAMESPACE}\nspec:\n selector:\n app: event-display\n ports:\n - protocol: TCP\n port: 80\n targetPort: 8080\n---\napiVersion: eventing.knative.dev/v1alpha1\nkind: Trigger\nmetadata:\n name: cifar10-outlier-display\n namespace: {DEPLOY_NAMESPACE}\nspec:\n broker: default\n filter:\n attributes:\n type: io.seldon.serving.inference.outlier\n subscriber:\n ref:\n apiVersion: v1\n kind: Service\n name: event-display\n---\napiVersion: eventing.knative.dev/v1alpha1\nkind: Trigger\nmetadata:\n name: cifar10-drift-display\n namespace: {DEPLOY_NAMESPACE}\nspec:\n broker: default\n filter:\n attributes:\n type: io.seldon.serving.inference.drift\n subscriber:\n ref:\n apiVersion: v1\n kind: Service\n name: event-display\n\"\"\"\nwith open(\"event_display.yaml\",\"w\") as f:\n f.write(event_display)\nrun(\"kubectl apply -f event_display.yaml\", shell=True)\n\nrun(f\"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/event-display -n {DEPLOY_NAMESPACE}\", shell=True)", "Deploy Seldon Outlier Detector", "outlier_yaml=f\"\"\"apiVersion: serving.knative.dev/v1\nkind: Service\nmetadata:\n name: cifar10-outlier\n namespace: {DEPLOY_NAMESPACE}\nspec:\n template:\n metadata:\n annotations:\n autoscaling.knative.dev/minScale: \"1\"\n spec:\n containers:\n - image: seldonio/alibi-detect-server:1.2.1\n imagePullPolicy: IfNotPresent\n args:\n - --model_name\n - cifar10od\n - --protocol\n - tensorflow.http\n - --storage_uri\n - s3://{MINIO_MODEL_BUCKET}/{OUTLIER_MODEL_PATH}\n - --reply_url\n - http://default-broker \n - --event_type\n - io.seldon.serving.inference.outlier\n - --event_source\n - io.seldon.serving.cifar10od\n - OutlierDetector\n envFrom:\n - secretRef:\n name: seldon-init-container-secret\n\"\"\"\nwith open(\"outlier.yaml\",\"w\") as f:\n f.write(outlier_yaml)\nrun(\"kubectl apply -f outlier.yaml\", shell=True)\n\ntrigger_outlier_yaml=f\"\"\"apiVersion: eventing.knative.dev/v1alpha1\nkind: Trigger\nmetadata:\n name: cifar10-outlier-trigger\n namespace: {DEPLOY_NAMESPACE}\nspec:\n filter:\n sourceAndType:\n type: io.seldon.serving.inference.request\n subscriber:\n ref:\n apiVersion: serving.knative.dev/v1\n kind: Service\n name: cifar10-outlier\n\"\"\"\nwith open(\"outlier_trigger.yaml\",\"w\") as f:\n f.write(trigger_outlier_yaml)\nrun(\"kubectl apply -f outlier_trigger.yaml\", shell=True)\n\nrun(f\"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/$(kubectl get deploy -l serving.knative.dev/service=cifar10-outlier -o jsonpath='{{.items[0].metadata.name}}' -n {DEPLOY_NAMESPACE})\", shell=True)", "Test Seldon Outlier Detection", "idx = 1\nX = X_train[idx:idx+1]\n\nnp.random.seed(0) \nX_mask, mask = apply_mask(X.reshape(1, 32, 32, 3),\n mask_size=(10,10),\n n_masks=1,\n channels=[0,1,2],\n mask_type='normal',\n noise_distr=(0,1),\n clip_rng=(0,1))\n\n\ndef predict():\n test_example=X_mask.tolist()\n payload='{\"instances\":'+f\"{test_example}\"+' }'\n cmd=f\"\"\"curl -d '{payload}' \\\n http://cifar10-classifier-default.{DEPLOY_NAMESPACE}:8000/v1/models/classifier/:predict \\\n -H \"Content-Type: application/json\"\n \"\"\"\n ret = Popen(cmd, shell=True,stdout=PIPE)\n raw = ret.stdout.read().decode(\"utf-8\")\n print(raw)\n res=json.loads(raw)\n arr=np.array(res[\"predictions\"])\n plt.imshow(X_mask.reshape(32, 32, 3))\n plt.axis('off')\n plt.show()\n print(\"class:\",class_names[y_train[idx][0]])\n print(\"prediction:\",class_names[arr[0].argmax()])\n\ndef get_outlier_event_display_logs():\n cmd=f\"kubectl logs $(kubectl get pod -l app=event-display -o jsonpath='{{.items[0].metadata.name}}' -n {DEPLOY_NAMESPACE}) -n {DEPLOY_NAMESPACE}\"\n ret = Popen(cmd, shell=True,stdout=PIPE)\n res = ret.stdout.read().decode(\"utf-8\").split(\"\\n\")\n data= []\n for i in range(0,len(res)):\n if res[i] == 'Data,':\n j = json.loads(json.loads(res[i+1]))\n if \"is_outlier\"in j[\"data\"].keys():\n data.append(j)\n if len(data) > 0:\n return data[-1]\n else:\n return None\nj = None\nwhile j is None:\n predict()\n print(\"Waiting for outlier logs, sleeping\")\n time.sleep(2)\n j = get_outlier_event_display_logs()\n \nprint(j)\nprint(\"Outlier\",j[\"data\"][\"is_outlier\"]==[1])", "Deploy Seldon Drift Detector", "drift_yaml=f\"\"\"apiVersion: serving.knative.dev/v1\nkind: Service\nmetadata:\n name: cifar10-drift\n namespace: {DEPLOY_NAMESPACE}\nspec:\n template:\n metadata:\n annotations:\n autoscaling.knative.dev/minScale: \"1\"\n spec:\n containers:\n - image: seldonio/alibi-detect-server:1.2.2-dev\n imagePullPolicy: IfNotPresent\n args:\n - --model_name\n - cifar10cd\n - --protocol\n - tensorflow.http\n - --storage_uri\n - s3://{MINIO_MODEL_BUCKET}/{DRIFT_MODEL_PATH}\n - --reply_url\n - http://default-broker\n - --event_type\n - io.seldon.serving.inference.drift\n - --event_source\n - io.seldon.serving.cifar10cd\n - DriftDetector\n - --drift_batch_size\n - '500'\n envFrom:\n - secretRef:\n name: seldon-init-container-secret\n\"\"\"\nwith open(\"drift.yaml\",\"w\") as f:\n f.write(drift_yaml)\nrun(\"kubectl apply -f drift.yaml\", shell=True)\n\ntrigger_outlier_yaml=f\"\"\"apiVersion: eventing.knative.dev/v1alpha1\nkind: Trigger\nmetadata:\n name: cifar10-drift-trigger\n namespace: {DEPLOY_NAMESPACE}\nspec:\n filter:\n sourceAndType:\n type: io.seldon.serving.inference.request\n subscriber:\n ref:\n apiVersion: serving.knative.dev/v1\n kind: Service\n name: cifar10-drift\n\"\"\"\nwith open(\"outlier_trigger.yaml\",\"w\") as f:\n f.write(trigger_outlier_yaml)\nrun(\"kubectl apply -f outlier_trigger.yaml\", shell=True)\n\nrun(f\"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/$(kubectl get deploy -l serving.knative.dev/service=cifar10-drift -o jsonpath='{{.items[0].metadata.name}}' -n {DEPLOY_NAMESPACE})\", shell=True)", "Test Seldon Drift Detector", "def show(X):\n plt.imshow(X.reshape(32, 32, 3))\n plt.axis('off')\n plt.show()\n\nfrom alibi_detect.datasets import fetch_cifar10c, corruption_types_cifar10c\ncorruption = ['motion_blur']\nX_corr, y_corr = fetch_cifar10c(corruption=corruption, severity=5, return_X_y=True)\nX_corr = X_corr.astype('float32') / 255\n\nshow(X_corr[0])\nshow(X_corr[1])\nshow(X_corr[2])\n\n\ndef predict(X):\n test_example=X.tolist()\n payload='{\"instances\":'+f\"{test_example}\"+' }'\n with open(\"payload.json\",\"w\") as f:\n f.write(payload)\n cmd=f\"\"\"curl -d @./payload.json \\\n http://cifar10-classifier-default.{DEPLOY_NAMESPACE}:8000/v1/models/classifier/:predict \\\n -H \"Content-Type: application/json\"\n \"\"\"\n run(cmd, shell=True)\n\ndef get_drift_event_display_logs():\n cmd=f\"kubectl logs $(kubectl get pod -l app=event-display -o jsonpath='{{.items[0].metadata.name}}' -n {DEPLOY_NAMESPACE}) -n {DEPLOY_NAMESPACE}\"\n ret = Popen(cmd, shell=True,stdout=PIPE)\n res = ret.stdout.read().decode(\"utf-8\").split(\"\\n\")\n data= []\n for i in range(0,len(res)):\n if res[i] == 'Data,':\n j = json.loads(json.loads(res[i+1]))\n if \"is_drift\"in j[\"data\"].keys():\n data.append(j)\n if len(data) > 0:\n return data[-1]\n else:\n return None\nj = None\nfor i in range(0,1000,50):\n X = X_corr[i:i+50]\n predict(X)\n print(\"Waiting for drift logs, sleeping\")\n time.sleep(2)\n j = get_drift_event_display_logs()\n if j is not None:\n break\n \nprint(j)\nprint(\"Drift\",j[\"data\"][\"is_drift\"]==1)", "Clean up", "run(f\"kubectl delete sdep cifar10-classifier -n {DEPLOY_NAMESPACE}\", shell=True)\nrun(f\"kubectl delete ksvc cifar10-outlier -n {DEPLOY_NAMESPACE}\", shell=True)\nrun(f\"kubectl delete ksvc cifar10-drift -n {DEPLOY_NAMESPACE}\", shell=True)\nrun(f\"kubectl delete trigger --all -n {DEPLOY_NAMESPACE}\", shell=True)\nrun(f\"kubectl delete sa minio-sa -n {DEPLOY_NAMESPACE}\", shell=True)\nrun(f\"kubectl delete secret seldon-init-container-secret -n {DEPLOY_NAMESPACE}\", shell=True)\nrun(f\"kubectl delete deployment event-display -n {DEPLOY_NAMESPACE}\", shell=True)\nrun(f\"kubectl delete svc event-display -n {DEPLOY_NAMESPACE}\", shell=True)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
kmorel/kmorel.github.io
images/better-plots/Bar_Basic.ipynb
mit
[ "from __future__ import print_function", "When analyzing data, I usually use the following three modules. I use pandas for data management, filtering, grouping, and processing. I use numpy for basic array math. I use toyplot for rendering the charts.", "import pandas\nimport numpy\nimport toyplot\nimport toyplot.pdf\nimport toyplot.png\nimport toyplot.svg\n\nprint('Pandas version: ', pandas.__version__)\nprint('Numpy version: ', numpy.__version__)\nprint('Toyplot version: ', toyplot.__version__)", "Load in the \"auto\" dataset. This is a fun collection of data on cars manufactured between 1970 and 1982. The source for this data can be found at https://archive.ics.uci.edu/ml/datasets/Auto+MPG.\nThe data are stored in a text file containing columns of data. We use the pandas.read_table() method to parse the data and load it in a pandas DataFrame. The file does not contain a header row, so we need to specify the names of the columns manually.", "column_names = ['MPG',\n 'Cylinders',\n 'Displacement',\n 'Horsepower',\n 'Weight',\n 'Acceleration',\n 'Model Year',\n 'Origin',\n 'Car Name']\ndata = pandas.read_table('auto-mpg.data',\n delim_whitespace=True,\n names=column_names,\n index_col=False)", "For this analysis I am going to group data by the car maker. The make is not directly stored in the data, but all the names start with the make, so extract the first word in that column.", "data['Make'] = data['Car Name'].str.split().str.get(0)", "The data has some inconsistencies with the make strings (misspellings or alternate spellings). Do some simple fixes.", "data.ix[data['Make'] == 'chevroelt', 'Make'] = 'chevrolet'\ndata.ix[data['Make'] == 'chevy', 'Make'] = 'chevrolet'\ndata.ix[data['Make'] == 'maxda', 'Make'] = 'mazda'\ndata.ix[data['Make'] == 'mercedes-benz', 'Make'] = 'mercedes'\ndata.ix[data['Make'] == 'vokswagen', 'Make'] = 'volkswagen'\ndata.ix[data['Make'] == 'vw', 'Make'] = 'volkswagen'", "In this plot we are going to show the average miles per gallon (MPG) rating for each car maker, and to be super cool we are going to order by average MPG. We can use the pivot_table feature of pandas to get this information from the data. (Excel and other spreadsheets have similar functionality.)", "average_mpg_per_make = data.pivot_table(columns='Make',\n values='MPG',\n aggfunc='mean')\nlen(average_mpg_per_make.index)", "There are many different makers represented in this data set, but several have only a few cars and perhaps are therefore not a signficant sample. Filter out the car makers that have fewer than 10 entries in the data. (Mostly I'm doing this to make these examples fit better even though it works OK with all the data, too.)", "count_mpg_per_make = data.pivot_table(columns='Make',\n values='MPG',\n aggfunc='count')\nfiltered_mpg = average_mpg_per_make[count_mpg_per_make >= 10]\nfiltered_mpg", "Now use toyplot to plot 1D histograms for each of these makes.", "canvas = toyplot.Canvas('4in', '2.6in')\n\naxes = canvas.cartesian(bounds=(41,-2,2,-58),\n ylabel = 'Average MPG')\n\naxes.plot(filtered_mpg)\n\n# Label the x axis on the make. This is a bit harder than it should be.\naxes.x.ticks.locator = \\\n toyplot.locator.Explicit(labels=filtered_mpg.index)\naxes.x.ticks.labels.angle = 45\n\n# It's usually best to make the y-axis 0-based.\naxes.y.domain.min = 0\n\ntoyplot.pdf.render(canvas, 'XY_Trend_Bad.pdf')\ntoyplot.svg.render(canvas, 'XY_Trend_Bad.svg')\ntoyplot.png.render(canvas, 'XY_Trend_Bad.png', scale=5)", "A better approach for this data is to use a bar chart.", "canvas = toyplot.Canvas('4in', '2.6in')\n\naxes = canvas.cartesian(bounds=(41,-2,2,-58),\n ylabel = 'Average MPG')\n\naxes.bars(filtered_mpg)\n\n# Label the x axis on the make. This is a bit harder than it should be.\naxes.x.ticks.locator = \\\n toyplot.locator.Explicit(labels=filtered_mpg.index)\naxes.x.ticks.labels.angle = 45\n\n# It's usually best to make the y-axis 0-based.\naxes.y.domain.min = 0\n\ntoyplot.pdf.render(canvas, 'Bar.pdf')\ntoyplot.svg.render(canvas, 'Bar.svg')\ntoyplot.png.render(canvas, 'Bar.png', scale=5)", "That is good, but the ordering is arbitrary (alphebetical). It would be even better if the bars were sorted by size.", "sorted_mpg = filtered_mpg.sort_values(ascending=False)\n\ncanvas = toyplot.Canvas('4in', '2.6in')\n\naxes = canvas.cartesian(bounds=(41,-2,2,-58),\n ylabel = 'Average MPG')\n\naxes.bars(sorted_mpg)\n\n# Label the x axis on the make. This is a bit harder than it should be.\naxes.x.ticks.locator = \\\n toyplot.locator.Explicit(labels=sorted_mpg.index)\naxes.x.ticks.labels.angle = 45\n\n# It's usually best to make the y-axis 0-based.\naxes.y.domain.min = 0\n\ntoyplot.pdf.render(canvas, 'Bar_Sorted.pdf')\ntoyplot.svg.render(canvas, 'Bar_Sorted.svg')\ntoyplot.png.render(canvas, 'Bar_Sorted.png', scale=5)", "Bar charts also afford the ability to change the orientation, which can help with layout, labels, and space utilization.", "sorted_mpg = filtered_mpg.sort_values(ascending=True)\n\ncanvas = toyplot.Canvas('4in', '2.6in')\n\naxes = canvas.cartesian(bounds=(70,-2,2,-44),\n xlabel = 'Average MPG')\n\naxes.bars(sorted_mpg,\n along='y')\n\n# Label the y axis on the make. This is a bit harder than it should be.\naxes.y.ticks.locator = \\\n toyplot.locator.Explicit(labels=sorted_mpg.index)\naxes.y.ticks.labels.angle = -90\n\n# It's usually best to make the y-axis 0-based.\naxes.x.domain.min = 0\n\ntoyplot.pdf.render(canvas, 'Bar_Rotated.pdf')\ntoyplot.svg.render(canvas, 'Bar_Rotated.svg')\ntoyplot.png.render(canvas, 'Bar_Rotated.png', scale=5)" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
informatics-isi-edu/deriva-py
docs/derivapy-catalog.ipynb
apache-2.0
[ "Deriva Ermrest Catalog Examples\nThis notebook gives examples of creating and connecting to ERMrest catalogs.", "from deriva.core import DerivaServer, get_credential", "Fill in your desired scheme, hostname and catalog number.", "scheme = 'https'\nhostname = 'dev.isrd.isi.edu'\ncatalog_number = 1", "Use DERIVA-Auth to get a credential or use None if your catalog allows anonymous access.", "#credential = None\ncredential = get_credential(hostname)", "Get a handle representing your server.", "server = DerivaServer(scheme, hostname, credential)", "Connect to a catalog, and list its schemas.", "catalog = server.connect_ermrest(catalog_number)\npb = catalog.getPathBuilder()\nlist(pb.schemas)", "Create a new catalog.", "new_catalog = server.create_ermrest_catalog()\nnew_catalog_pb = new_catalog.getPathBuilder()\nlist(new_catalog_pb.schemas)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
sraejones/phys202-2015-work
assignments/assignment03/NumpyEx04.ipynb
mit
[ "Numpy Exercise 4\nImports", "import numpy as np\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns", "Complete graph Laplacian\nIn discrete mathematics a Graph is a set of vertices or nodes that are connected to each other by edges or lines. If those edges don't have directionality, the graph is said to be undirected. Graphs are used to model social and communications networks (Twitter, Facebook, Internet) as well as natural systems such as molecules.\nA Complete Graph, $K_n$ on $n$ nodes has an edge that connects each node to every other node.\nHere is $K_5$:", "import networkx as nx\nK_5=nx.complete_graph(5)\nnx.draw(K_5)", "The Laplacian Matrix is a matrix that is extremely important in graph theory and numerical analysis. It is defined as $L=D-A$. Where $D$ is the degree matrix and $A$ is the adjecency matrix. For the purpose of this problem you don't need to understand the details of these matrices, although their definitions are relatively simple.\nThe degree matrix for $K_n$ is an $n \\times n$ diagonal matrix with the value $n-1$ along the diagonal and zeros everywhere else. Write a function to compute the degree matrix for $K_n$ using NumPy.", "def complete_deg(n):\n \"\"\"Return the integer valued degree matrix D for the complete graph K_n.\"\"\"\n return np.diag([n-1]*n) \n\nD = complete_deg(5)\nassert D.shape==(5,5)\nassert D.dtype==np.dtype(int)\nassert np.all(D.diagonal()==4*np.ones(5))\nassert np.all(D-np.diag(D.diagonal())==np.zeros((5,5),dtype=int))", "The adjacency matrix for $K_n$ is an $n \\times n$ matrix with zeros along the diagonal and ones everywhere else. Write a function to compute the adjacency matrix for $K_n$ using NumPy.", "def complete_adj(n):\n \"\"\"Return the integer valued adjacency matrix A for the complete graph K_n.\"\"\"\n # YOUR CODE HERE\n# raise NotImplementedError()\n return np.ones((n,n), dtype=int)-np.diag([1]*n)\n\nA = complete_adj(5)\nassert A.shape==(5,5)\nassert A.dtype==np.dtype(int)\nassert np.all(A+np.eye(5,dtype=int)==np.ones((5,5),dtype=int))", "Use NumPy to explore the eigenvalues or spectrum of the Laplacian L of $K_n$. What patterns do you notice as $n$ changes? Create a conjecture about the general Laplace spectrum of $K_n$.", "# YOUR CODE HERE\n# raise NotImplementedError()\nnp.linalg.eigvals(complete_deg(1)-complete_adj(1))\nnp.linalg.eigvals(complete_deg(2)-complete_adj(2))", "Some accuracy is lost as the sizw of the array increces" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
weleen/mxnet
example/notebooks/moved-from-mxnet/class_active_maps.ipynb
apache-2.0
[ "This demo shows the method proposed in \"Zhou, Bolei, et al. \"Learning Deep Features for Discriminative Localization.\" arXiv preprint arXiv:1512.04150 (2015)\".\nThe proposed method can automatically localize the discriminative regions in an image using global average pooling\n(GAP) in CNNs.\nYou can download the pretrained Inception-V3 network from here. Other networks with similar structure(use global average pooling after the last conv feature map) should also work.", "# -*- coding: UTF-8 –*-\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom IPython import display\n\nimport os\nROOT_DIR = '.'\nimport sys\nsys.path.insert(0, os.path.join(ROOT_DIR, 'lib'))\nimport cv2\nimport numpy as np\nimport mxnet as mx\nimport matplotlib.pyplot as plt", "Set the image you want to test and the classification network you want to use. Notice \"conv_layer\" should be the last conv layer before the average pooling layer.", "im_file = os.path.join(ROOT_DIR, 'sample_pics/barbell.jpg')\n\nsynset_file = os.path.join(ROOT_DIR, 'models/inception-v3/synset.txt')\nnet_json = os.path.join(ROOT_DIR, 'models/inception-v3/Inception-7-symbol.json')\nconv_layer = 'ch_concat_mixed_10_chconcat_output'\nprob_layer = 'softmax_output'\narg_fc = 'fc1'\nparams = os.path.join(ROOT_DIR, 'models/inception-v3/Inception-7-0001.params')\nmean = (128, 128, 128)\nraw_scale = 1.0\ninput_scale = 1.0/128\nwidth = 299\nheight = 299\nresize_size = 340\ntop_n = 5\nctx = mx.cpu(1)", "Load the label name of each class.", "synset = [l.strip() for l in open(synset_file).readlines()]", "Build network symbol and load network parameters.", "symbol = mx.sym.load(net_json)\ninternals = symbol.get_internals()\nsymbol = mx.sym.Group([internals[prob_layer], internals[conv_layer]])\n\nsave_dict = mx.nd.load(params)\narg_params = {}\naux_params = {}\nfor k, v in save_dict.items():\n l2_tp, name = k.split(':', 1)\n if l2_tp == 'arg':\n arg_params[name] = v\n if l2_tp == 'aux':\n aux_params[name] = v\n\nmod = mx.model.FeedForward(symbol,\n arg_params=arg_params,\n aux_params=aux_params,\n ctx=ctx,\n allow_extra_params=False,\n numpy_batch_size=1)", "Read the weight of the fc layer in softmax classification layer. Bias can be neglected since it does not really affect the result.\nLoad the image you want to test and convert it from BGR to RGB(opencv use BGR by default).", "weight_fc = arg_params[arg_fc+'_weight'].asnumpy()\n# bias_fc = arg_params[arg_fc+'_bias'].asnumpy()\n\nim = cv2.imread(im_file)\nrgb = cv2.cvtColor(cv2.resize(im, (width, height)), cv2.COLOR_BGR2RGB)", "Feed the image data to our network and get the outputs.\nWe select the top 5 classes for visualization by default.", "def im2blob(im, width, height, mean=None, input_scale=1.0, raw_scale=1.0, swap_channel=True):\n blob = cv2.resize(im, (height, width)).astype(np.float32)\n blob = blob.reshape((1, height, width, 3))\n\n # from nhwc to nchw\n blob = np.swapaxes(blob, 2, 3)\n blob = np.swapaxes(blob, 1, 2)\n\n if swap_channel:\n blob[:, [0, 2], :, :] = blob[:, [2, 0], :, :]\n\n if raw_scale != 1.0:\n blob *= raw_scale\n\n if isinstance(mean, np.ndarray):\n blob -= mean\n elif isinstance(mean, tuple) or isinstance(mean, list):\n blob[:, 0, :, :] -= mean[0]\n blob[:, 1, :, :] -= mean[1]\n blob[:, 2, :, :] -= mean[2]\n elif mean is None:\n pass\n else:\n raise TypeError, 'mean should be either a tuple or a np.ndarray'\n\n if input_scale != 1.0:\n blob *= input_scale\n\n return blob\n\nblob = im2blob(im, width, height, mean=mean, swap_channel=True, raw_scale=raw_scale, input_scale=input_scale)\noutputs = mod.predict(blob)\nscore = outputs[0][0]\nconv_fm = outputs[1][0]\n\nscore_sort = -np.sort(-score)[:top_n]\ninds_sort = np.argsort(-score)[:top_n]", "Localize the discriminative regions by analysing the class's response in the network's last conv feature map.", "def get_cam(conv_feat_map, weight_fc):\n assert len(weight_fc.shape) == 2\n if len(conv_feat_map.shape) == 3:\n C, H, W = conv_feat_map.shape\n assert weight_fc.shape[1] == C\n detection_map = weight_fc.dot(conv_feat_map.reshape(C, H*W))\n detection_map = detection_map.reshape(-1, H, W)\n elif len(conv_feat_map.shape) == 4:\n N, C, H, W = conv_feat_map.shape\n assert weight_fc.shape[1] == C\n M = weight_fc.shape[0]\n detection_map = np.zeros((N, M, H, W))\n for i in xrange(N):\n tmp_detection_map = weight_fc.dot(conv_feat_map[i].reshape(C, H*W))\n detection_map[i, :, :, :] = tmp_detection_map.reshape(-1, H, W)\n return detection_map\n\nplt.figure(figsize=(18, 6))\nplt.subplot(1, 1+top_n, 1)\nplt.imshow(rgb)\ncam = get_cam(conv_fm, weight_fc[inds_sort, :])\nfor k in xrange(top_n):\n detection_map = np.squeeze(cam.astype(np.float32)[k, :, :])\n heat_map = cv2.resize(detection_map, (width, height))\n max_response = detection_map.mean()\n heat_map /= heat_map.max()\n\n im_show = rgb.astype(np.float32)/255*0.3 + plt.cm.jet(heat_map/heat_map.max())[:, :, :3]*0.7\n plt.subplot(1, 1+top_n, k+2)\n plt.imshow(im_show)\n print 'Top %d: %s(%.6f), max_response=%.4f' % (k+1, synset[inds_sort[k]], score_sort[k], max_response)\n\nplt.show()" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
alexandrejaguar/strata-sv-2015-tutorial
resources/Vis1.ipynb
bsd-3-clause
[ "Visualization 1: Matplotlib Basics\nImports\nThe following imports should be used in all of your notebooks where Matplotlib in used:", "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np", "Basic plotting\nFor now, we will work with basic x, y plots to show how the Matplotlib plotting API works.", "t = np.linspace(0,4*np.pi,100)\nplt.plot(t, np.sin(t))\nplt.xlabel('Time')\nplt.ylabel('Signal')\nplt.title('My Plot')", "Quick series styling\nWith a third argument you can provide the series color and line/marker style:", "plt.plot(t, np.sin(t), 'm-.*')", "Here is a list of the single character color strings:\nb: blue\n g: green\n r: red\n c: cyan\n m: magenta\n y: yellow\n k: black\n w: white\nThe following will show all of the line and marker styles:", "from matplotlib import lines\nlines.lineStyles.keys()\n\nfrom matplotlib import markers\nmarkers.MarkerStyle.markers.keys()", "To change the plot's viewport, use plt.axis([xmin,xmax,ymin,ymax]):", "plt.plot(t, np.sin(t)*np.exp(-0.1*t),'bo')\nplt.axis([-1,3,0,1.])", "Multiple series\nYou can provide multiple series in a single call to plot:", "plt.plot(t, np.sin(t), 'r.', t, np.cos(t), 'g-')", "Or you can make multiple calls to plot:", "plt.plot(t, np.sin(t))\nplt.plot(t, np.cos(t))", "Subplots\nYou can use the subplot function to create a grid of plots in a single figure.", "plt.subplot(1,2,1)\nplt.plot(t, np.exp(0.1*t))\nplt.ylabel('Exponential')\nplt.subplot(1,2,2)\nplt.plot(t, np.sin(t))\nplt.ylabel('Quadratic')\nplt.xlabel('x')", "More line styling\nAll plot commands, including plot, accept keyword arguments that can be used to style the lines in more detail. See Controlling line properties for more details:", "plt.plot(t, np.sin(t), marker='o', color='darkblue',\n linestyle='--', alpha=0.3, markersize=10)", "Other plot types\nHere are some of the other important plot types we will be using in this course:\n\nScatter plots (plt.scatter)\nBar plots (plt.bar and plt.barh)\nBox plots (plt.boxplot)\nHistogram (plt.hist)\n\nResources\n\nMatplotlib Documentation, Matplotlib developers.\nMatplotlib Gallery, Matplotlib developers.\nMatplotlib List of Plotting Commands, Matplotlib developers.\nMatplotlib Tutorial, J.R. Johansson." ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
doc/notebooks/automaton.shortest.ipynb
gpl-3.0
[ "automaton.shortest(num = None, len = None)\nReturn a (finite) approximation of the behavior of the automaton controled by the length of the words. In other words, compute the polynomial of the first accepted words (according to the shortlex order), and their associated weight.\nArguments:\n- num the number of words to find (there might be fewer). None stands for $\\infty$ if len is specified, 1 otherwise.\n- len the maximum length of the words to find. None stands for $\\infty$.\nDefault values are handled as follows:\n<table>\n <tr>\n <td></td>\n <td>len = None</td>\n <td>len = $\\ell$</td>\n </tr>\n <tr>\n <td>num = None</td>\n <td>$1, \\infty$</td>\n <td>$\\infty, \\ell$</td>\n </tr>\n <tr>\n <td>num = $n$</td>\n <td>$n, \\infty$</td>\n <td>$n, \\ell$</td>\n </tr>\n</table>\n\nPreconditions:\n- the automaton must not have spontaneous cycles\nSee also:\n- automaton.eval\n- automaton.lightest\n- expression.shortest\nExamples", "import vcsn", "Boolean Automata", "a = vcsn.context('lal_char(ab), b').de_bruijn(1)\na", "Calling a.shortest() is equivalent to a.shortest(1) which is equivalent to a.shortest(1, 0): find the shortest word, whatever its length:", "a.shortest()", "To get the first four words, use a.shortest(4) (or a.shortest(len = 4)):", "a.shortest(4)", "The words with at most four letters:", "a.shortest(len = 4)", "At most 10 words of at most 4 letters:", "a.shortest(num = 10, len = 4)", "At most 10 words of at most 3 letters:", "a.shortest(num = 10, len = 3)", "Weighted Automata\nThe following automaton decodes binary numbers.", "%%automaton -s bin\ncontext = \"lal_char(01), z\"\n$ -> 0\n0 -> 0 0, 1\n0 -> 1 1\n1 -> $\n1 -> 1 <2>0, <2>1\n\nbin.shortest(len = 3)\n\nbin.shortest(num = 10)", "Transducers\nThe following automaton maps words to words. The length of a multitape words is the largest length of its components: $\\mathsf{len}(abc|x) = 3$.", "%%automaton -s t\ncontext = \"lat<law<char>, law<char>>, q\"\n$ -> 0\n0 -> 1 <1>one|un\n0 -> 2 <2>two|deux\n0 -> 3 <3>three|trois\n1 -> 0 \\e|\\e\n2 -> 0 \\e|\\e\n3 -> 0 \\e|\\e\n1 -> $\n2 -> $\n3 -> $\n\nt.shortest(num = 10, len = 9)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
IS-ENES-Data/submission_forms
test/prov/old/prov-test1.ipynb
apache-2.0
[ "Representation of data submission workflow components based on W3C-PROV", "%load_ext autoreload\n%autoreload 2\n\nfrom prov.model import ProvDocument\nd1 = ProvDocument()\nd1.deserialize?\n", "Model is along the concept described in https://www.w3.org/TR/prov-primer/", "from IPython.display import display, Image\nImage(filename='key-concepts.png')\n\n\nfrom dkrz_forms import form_handler\n#from project_cordex import cordex_dict\n#from project_cordex import name_space\n\n# add namespaces for submission provenance capture\n\n#for key,value in name_space.iteritems():\n# d1.add_namespace(key,value)\n\n#d1.add_namespace()\n# to do: look into some predefined vocabs, e.g. dublin core, iso19139,foaf etc.\n\nd1.add_namespace(\"enes_entity\",'http://www.enes.org/enes_entitiy#')\nd1.add_namespace('enes_agent','http://www.enes.org/enes_agent#')\nd1.add_namespace('data_collection','http://www.enes.org/enes_entity/file_collection')\nd1.add_namespace('data_manager','http://www.enes.org/enes_agent/data_manager')\nd1.add_namespace('data_provider','http://www.enes.org/enes_agent/data_provider')\nd1.add_namespace('subm','http://www.enes.org/enes_entity/data_submsission')\nd1.add_namespace('foaf','http://xmlns.com/foaf/0.1/')", "Example name spaces\n(from DOI: 10.3390/ijgi5030038 , mehr unter https://github.com/tsunagun/vocab/blob/master/all_20130125.csv)\nowl Web Ontology Language http://www.w3.org/2002/07/owl#\ndctype DCMI Type Vocabulary http://purl.org/dc/dcmitype/\ndco DCO Ontology http://info.deepcarbon.net/schema#\nprov PROV Ontology http://www.w3.org/ns/prov#\nskos Simple Knowledge\n Organization System http://www.w3.org/2004/02/skos/core#\nfoaf FOAF Ontology http://xmlns.com/foaf/0.1/\nvivo VIVO Ontology http://vivoweb.org/ontology/core#\nbibo Bibliographic Ontology http://purl.org/ontology/bibo/\nxsd XML Schema Datatype http://www.w3.org/2001/XMLSchema#\nrdf Resource Description\n Framework http://www.w3.org/1999/02/22-rdf-syntax-ns#\nrdfs Resource Description\n Framework Schema http://www.w3.org/2000/01/rdf-schema#", "# later: organize things in bundles\ndata_manager_ats = {'foaf:givenName':'Peter','foaf:mbox':'lenzen@dkzr.de'}\n\nd1.entity('sub:empty')\ndef add_stage(agent,activity,in_state,out_state):\n # in_stage exists, out_stage is generated\n d1.agent(agent, data_manager_ats)\n d1.activity(activity)\n d1.entity(out_state)\n \n d1.wasGeneratedBy(out_state,activity)\n d1.used(activity,in_state)\n d1.wasAssociatedWith(activity,agent)\n d1.wasDerivedFrom(out_state,in_state)\n\nimport json\nform_file = open('/home/stephan/tmp/CORDEX/Kindermann_test1.json',\"r\")\njson_info = form_file.read()\n#json_info[\"__type__\"] = \"sf\",\nform_file.close()\nsf_dict = json.loads(json_info)\n\nsf = form_handler.dict_to_form(sf_dict)\n\nprint sf.__dict__\n\n\ndata_provider = sf.first_name+'_'+sf.last_name\nsubmission_manager = sf.sub['responsible_person']\ningest_manager = sf.ing['responsible_person']\nqa_manager = sf.ing['responsible_person']\npublication_manager = sf.pub['responsible_person']\n\nadd_stage(agent='data_provider:test_user_id',activity='subm:submit',in_state=\"subm:empty\",out_state='subm:out1_sub')\nadd_stage(agent='data_manager:peter_lenzen_id',activity='subm:review',in_state=\"subm:out1_sub\",out_state='subm:out1_rev')\nadd_stage(agent='data_manager:peter_lenzen_id',activity='subm:ingest',in_state=\"subm:out1_rev\",out_state='subm:out1_ing')\nadd_stage(agent='data_manager:hdh_id',activity='subm:check',in_state=\"subm:out1_ing\",out_state='subm:out1_che')\nadd_stage(agent='data_manager:katharina_b_id',activity='subm:publish',in_state=\"subm:out1_che\",out_state='subm:out1_pub')\nadd_stage(agent='data_manager:lta_id',activity='subm:archive',in_state=\"subm:out1_pub\",out_state='subm:out1_arch')", "assign information to provenance graph nodes and edges", "%matplotlib inline\nd1.plot()\n\n\n\nd1.wasAttributedTo(data_submission,'????')", "Transform submission object to a provenance graph", "#d1.get_records()\nsubmission = d1.get_record('subm:out1_sub')[0]\nreview = d1.get_record('subm:out1_rev')[0]\ningest = d1.get_record('subm:out1_ing')[0]\ncheck = d1.get_record('subm:out1_che')[0]\npublication = d1.get_record('subm:out1_pub')[0]\nlta = d1.get_record('subm:out1_arch')[0]\n\n\nres = form_handler.prefix_dict(sf.sub,'sub',sf.sub.keys())\nres['sub:status']=\"fertig\"\nprint res\ning = form_handler.prefix_dict(sf.ing,'ing',sf.ing.keys())\nche = form_handler.prefix_dict(sf.che,'che',sf.che.keys())\npub = form_handler.prefix_dict(sf.pub,'pub',sf.pub.keys())\n\nsubmission.add_attributes(res)\ningest.add_attributes(ing)\ncheck.add_attributes(che)\npublication.add_attributes(pub)\n\nche_act = d1.get_record('subm:check') \ntst = che_act[0]\ntest_dict = {'subm:test':'test'}\ntst.add_attributes(test_dict)\n\nprint tst\ntst.FORMAL_ATTRIBUTES\ntst.\n\nche_act = d1.get_record('subm:check') \n#tst.formal_attributes\n#tst.FORMAL_ATTRIBUTES\ntst.add_attributes({'foaf:name':'tst'})\nprint tst.attributes\n#for i in tst:\n # print i\n#tst.insert([('subm:givenName','sk')])\n\nimport sys\nsys.path.append('/home/stephan/Repos/ENES-EUDAT/submission_forms')\nfrom dkrz_forms import form_handler\nsf,repo = form_handler.init_form(\"CORDEX\")\n\n\n\ninit_dict = sf.__dict__ \nsub_form = form_handler.prefix(sf,'subm',sf.__dict__.keys()) \n\nsub_dict = sub_form.__dict__\n\n#init_state = d1.get_record('subm:empty')[0]\n#init_state.add_attributes(init_dict)\n\nsub_state = d1.get_record('subm:out1_sub')[0]\ninit_state.add_attributes(sub_dict)\n\n\ntst_dict = {'test1':'val1','test2':'val2'}\ntst = form_handler.submission_form(tst_dict) \nprint tst.__dict__\n\n\nprint result.__dict__\n\ndict_from_class(sf)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
nitin-cherian/LifeLongLearning
Python/Python_Morsels_Revised/11.lstrip/redo_with_Trey/lstrip.ipynb
mit
[ "Using the iterator protocol\n======================\nLoop through the iterator, skip the items in iterator until an item that does not match the skip_value is found.", "def lstrip(iterable, strip_value):\n \"\"\" Return iterable with strip_value removed from the beginnning\"\"\"\n stripped = []\n iterator = iter(iterable)\n for item in iterator:\n if not item == strip_value:\n stripped.append(item)\n break\n \n for item in iterator:\n stripped.append(item)\n \n return stripped\n\nimport unittest\n\nclass LStripTests(unittest.TestCase):\n\n \"\"\"Tests for lstrip.\"\"\"\n\n def assertIterableEqual(self, iterable1, iterable2):\n self.assertEqual(list(iterable1), list(iterable2))\n\n def test_list(self):\n self.assertIterableEqual(lstrip([1, 1, 2, 3], 1), [2, 3])\n\n def test_nothing_to_strip(self):\n self.assertIterableEqual(lstrip([1, 2, 3], 0), [1, 2, 3])\n\n def test_string(self):\n self.assertIterableEqual(lstrip(' hello', ' '), 'hello')\n\n def test_empty_iterable(self):\n self.assertIterableEqual(lstrip([], 1), [])\n\n def test_strip_all(self):\n self.assertIterableEqual(lstrip([1, 1, 1], 1), [])\n\n def test_none_values(self):\n self.assertIterableEqual(lstrip([None, 1, 2, 3], 0), [None, 1, 2, 3])\n\n def test_iterator(self):\n squares = (n**2 for n in [0, 0, 1, 2, 3])\n self.assertIterableEqual(lstrip(squares, 0), [1, 4, 9])\n\n # To test the Bonus part of this exercise, comment out the following line\n @unittest.expectedFailure\n def test_returns_iterator(self):\n stripped = lstrip((1, 2, 3), 1)\n self.assertEqual(iter(stripped), iter(stripped))\n\n # To test the Bonus part of this exercise, comment out the following line\n @unittest.expectedFailure\n def test_function_given(self):\n numbers = [0, 2, 4, 1, 3, 5, 6]\n def is_even(n): return n % 2 == 0\n self.assertIterableEqual(lstrip(numbers, is_even), [1, 3, 5, 6])\n\n\nif __name__ == \"__main__\":\n unittest.main(argv=['ignore-first-arg'], exit=False)", "Bonus1: The lstrip function should return an iterator", "def lstrip(iterable, strip_value):\n \"\"\" Return iterable with strip_value removed from the beginnning\"\"\"\n iterator = iter(iterable)\n for item in iterator:\n if not item == strip_value:\n yield item\n break\n \n for item in iterator:\n yield item\n\n\nimport unittest\n\nclass LStripTests(unittest.TestCase):\n\n \"\"\"Tests for lstrip.\"\"\"\n\n def assertIterableEqual(self, iterable1, iterable2):\n self.assertEqual(list(iterable1), list(iterable2))\n\n def test_list(self):\n self.assertIterableEqual(lstrip([1, 1, 2, 3], 1), [2, 3])\n\n def test_nothing_to_strip(self):\n self.assertIterableEqual(lstrip([1, 2, 3], 0), [1, 2, 3])\n\n def test_string(self):\n self.assertIterableEqual(lstrip(' hello', ' '), 'hello')\n\n def test_empty_iterable(self):\n self.assertIterableEqual(lstrip([], 1), [])\n\n def test_strip_all(self):\n self.assertIterableEqual(lstrip([1, 1, 1], 1), [])\n\n def test_none_values(self):\n self.assertIterableEqual(lstrip([None, 1, 2, 3], 0), [None, 1, 2, 3])\n\n def test_iterator(self):\n squares = (n**2 for n in [0, 0, 1, 2, 3])\n self.assertIterableEqual(lstrip(squares, 0), [1, 4, 9])\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_returns_iterator(self):\n stripped = lstrip((1, 2, 3), 1)\n self.assertEqual(iter(stripped), iter(stripped))\n\n # To test the Bonus part of this exercise, comment out the following line\n @unittest.expectedFailure\n def test_function_given(self):\n numbers = [0, 2, 4, 1, 3, 5, 6]\n def is_even(n): return n % 2 == 0\n self.assertIterableEqual(lstrip(numbers, is_even), [1, 3, 5, 6])\n\n\nif __name__ == \"__main__\":\n unittest.main(argv=['ignore-first-arg'], exit=False)", "Experiments : Testing iterator", "my_list = [1, 2, 3, 4]\niterator1 = iter(my_list)\niterator2 = iter(my_list)\niterator1 == iterator2\n\nmy_list = [1, 2, 3, 4]\niterator = iter(my_list)\niterator1 = iter(iterator)\niterator2 = iter(iterator)\niterator1 == iterator2", "Bonus2: We're supposed to optionally accept a function as our strip value and call that function to determine whether values should be removed", "def lstrip(iterable, strip_value):\n \"\"\"Return iterable with strip_value items removed from beginning.\"\"\"\n iterator = iter(iterable)\n for item in iterator:\n if (callable(strip_value) and not strip_value(item)\n or item != strip_value):\n yield item\n break\n for item in iterator:\n yield item\n\nimport unittest\n\nclass LStripTests(unittest.TestCase):\n\n \"\"\"Tests for lstrip.\"\"\"\n\n def assertIterableEqual(self, iterable1, iterable2):\n self.assertEqual(list(iterable1), list(iterable2))\n\n def test_list(self):\n self.assertIterableEqual(lstrip([1, 1, 2, 3], 1), [2, 3])\n\n def test_nothing_to_strip(self):\n self.assertIterableEqual(lstrip([1, 2, 3], 0), [1, 2, 3])\n\n def test_string(self):\n self.assertIterableEqual(lstrip(' hello', ' '), 'hello')\n\n def test_empty_iterable(self):\n self.assertIterableEqual(lstrip([], 1), [])\n\n def test_strip_all(self):\n self.assertIterableEqual(lstrip([1, 1, 1], 1), [])\n\n def test_none_values(self):\n self.assertIterableEqual(lstrip([None, 1, 2, 3], 0), [None, 1, 2, 3])\n\n def test_iterator(self):\n squares = (n**2 for n in [0, 0, 1, 2, 3])\n self.assertIterableEqual(lstrip(squares, 0), [1, 4, 9])\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_returns_iterator(self):\n stripped = lstrip((1, 2, 3), 1)\n self.assertEqual(iter(stripped), iter(stripped))\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_function_given(self):\n numbers = [0, 2, 4, 1, 3, 5, 6]\n def is_even(n): return n % 2 == 0\n self.assertIterableEqual(lstrip(numbers, is_even), [1, 3, 5, 6])\n\n\nif __name__ == \"__main__\":\n unittest.main(argv=['ignore-first-arg'], exit=False)\n\ndef lstrip(iterable, strip_value):\n \"\"\"Return iterable with strip_value items removed from beginning.\"\"\"\n iterator = iter(iterable)\n if callable(strip_value):\n predicate = strip_value\n else:\n def predicate(value): return value == strip_value\n \n for item in iterator:\n if not predicate(item):\n yield item\n break\n for item in iterator:\n yield item\n\nimport unittest\n\nclass LStripTests(unittest.TestCase):\n\n \"\"\"Tests for lstrip.\"\"\"\n\n def assertIterableEqual(self, iterable1, iterable2):\n self.assertEqual(list(iterable1), list(iterable2))\n\n def test_list(self):\n self.assertIterableEqual(lstrip([1, 1, 2, 3], 1), [2, 3])\n\n def test_nothing_to_strip(self):\n self.assertIterableEqual(lstrip([1, 2, 3], 0), [1, 2, 3])\n\n def test_string(self):\n self.assertIterableEqual(lstrip(' hello', ' '), 'hello')\n\n def test_empty_iterable(self):\n self.assertIterableEqual(lstrip([], 1), [])\n\n def test_strip_all(self):\n self.assertIterableEqual(lstrip([1, 1, 1], 1), [])\n\n def test_none_values(self):\n self.assertIterableEqual(lstrip([None, 1, 2, 3], 0), [None, 1, 2, 3])\n\n def test_iterator(self):\n squares = (n**2 for n in [0, 0, 1, 2, 3])\n self.assertIterableEqual(lstrip(squares, 0), [1, 4, 9])\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_returns_iterator(self):\n stripped = lstrip((1, 2, 3), 1)\n self.assertEqual(iter(stripped), iter(stripped))\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_function_given(self):\n numbers = [0, 2, 4, 1, 3, 5, 6]\n def is_even(n): return n % 2 == 0\n self.assertIterableEqual(lstrip(numbers, is_even), [1, 3, 5, 6])\n\n\nif __name__ == \"__main__\":\n unittest.main(argv=['ignore-first-arg'], exit=False)", "Using dropwhile helper function in itertools module\n========================================\nThe dropwhile function in the itertools module will give us an iterable that has our original iterable's values except it drops any at the beginning that pass a certain test.\nBonus1: The lstrip function should return an iterator", "from itertools import dropwhile\ndef lstrip(iterable, strip_value):\n \"\"\"Return iterable with strip_value items removed from beginning.\"\"\"\n def is_strip_value(item): return item == strip_value\n \n return dropwhile(is_strip_value, iterable)\n\nimport unittest\n\nclass LStripTests(unittest.TestCase):\n\n \"\"\"Tests for lstrip.\"\"\"\n\n def assertIterableEqual(self, iterable1, iterable2):\n self.assertEqual(list(iterable1), list(iterable2))\n\n def test_list(self):\n self.assertIterableEqual(lstrip([1, 1, 2, 3], 1), [2, 3])\n\n def test_nothing_to_strip(self):\n self.assertIterableEqual(lstrip([1, 2, 3], 0), [1, 2, 3])\n\n def test_string(self):\n self.assertIterableEqual(lstrip(' hello', ' '), 'hello')\n\n def test_empty_iterable(self):\n self.assertIterableEqual(lstrip([], 1), [])\n\n def test_strip_all(self):\n self.assertIterableEqual(lstrip([1, 1, 1], 1), [])\n\n def test_none_values(self):\n self.assertIterableEqual(lstrip([None, 1, 2, 3], 0), [None, 1, 2, 3])\n\n def test_iterator(self):\n squares = (n**2 for n in [0, 0, 1, 2, 3])\n self.assertIterableEqual(lstrip(squares, 0), [1, 4, 9])\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_returns_iterator(self):\n stripped = lstrip((1, 2, 3), 1)\n self.assertEqual(iter(stripped), iter(stripped))\n\n # To test the Bonus part of this exercise, comment out the following line\n @unittest.expectedFailure\n def test_function_given(self):\n numbers = [0, 2, 4, 1, 3, 5, 6]\n def is_even(n): return n % 2 == 0\n self.assertIterableEqual(lstrip(numbers, is_even), [1, 3, 5, 6])\n\n\nif __name__ == \"__main__\":\n unittest.main(argv=['ignore-first-arg'], exit=False)", "Bonus2: We're supposed to optionally accept a function as our strip value and call that function to determine whether values should be removed", "from itertools import dropwhile\ndef lstrip(iterable, strip_value):\n \"\"\"Return iterable with strip_value items removed from beginning.\"\"\"\n if callable(strip_value):\n predicate = strip_value\n else:\n def predicate(item): return item == strip_value\n \n return dropwhile(predicate, iterable)\n\nimport unittest\n\nclass LStripTests(unittest.TestCase):\n\n \"\"\"Tests for lstrip.\"\"\"\n\n def assertIterableEqual(self, iterable1, iterable2):\n self.assertEqual(list(iterable1), list(iterable2))\n\n def test_list(self):\n self.assertIterableEqual(lstrip([1, 1, 2, 3], 1), [2, 3])\n\n def test_nothing_to_strip(self):\n self.assertIterableEqual(lstrip([1, 2, 3], 0), [1, 2, 3])\n\n def test_string(self):\n self.assertIterableEqual(lstrip(' hello', ' '), 'hello')\n\n def test_empty_iterable(self):\n self.assertIterableEqual(lstrip([], 1), [])\n\n def test_strip_all(self):\n self.assertIterableEqual(lstrip([1, 1, 1], 1), [])\n\n def test_none_values(self):\n self.assertIterableEqual(lstrip([None, 1, 2, 3], 0), [None, 1, 2, 3])\n\n def test_iterator(self):\n squares = (n**2 for n in [0, 0, 1, 2, 3])\n self.assertIterableEqual(lstrip(squares, 0), [1, 4, 9])\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_returns_iterator(self):\n stripped = lstrip((1, 2, 3), 1)\n self.assertEqual(iter(stripped), iter(stripped))\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_function_given(self):\n numbers = [0, 2, 4, 1, 3, 5, 6]\n def is_even(n): return n % 2 == 0\n self.assertIterableEqual(lstrip(numbers, is_even), [1, 3, 5, 6])\n\n\nif __name__ == \"__main__\":\n unittest.main(argv=['ignore-first-arg'], exit=False)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
mintcloud/deep-learning
seq2seq/sequence_to_sequence_implementation.ipynb
mit
[ "Character Sequence to Sequence\nIn this notebook, we'll build a model that takes in a sequence of letters, and outputs a sorted version of that sequence. We'll do that using what we've learned so far about Sequence to Sequence models.\n<img src=\"images/sequence-to-sequence.jpg\"/>\nDataset\nThe dataset lives in the /data/ folder. At the moment, it is made up of the following files:\n * letters_source.txt: The list of input letter sequences. Each sequence is its own line. \n * letters_target.txt: The list of target sequences we'll use in the training process. Each sequence here is a response to the input sequence in letters_source.txt with the same line number.", "import helper\n\nsource_path = 'data/letters_source.txt'\ntarget_path = 'data/letters_target.txt'\n\nsource_sentences = helper.load_data(source_path)\ntarget_sentences = helper.load_data(target_path)", "Let's start by examining the current state of the dataset. source_sentences contains the entire input sequence file as text delimited by newline symbols.", "source_sentences[:50].split('\\n')", "target_sentences contains the entire output sequence file as text delimited by newline symbols. Each line corresponds to the line from source_sentences. target_sentences contains a sorted characters of the line.", "target_sentences[:50].split('\\n')", "Preprocess\nTo do anything useful with it, we'll need to turn the characters into a list of integers:", "def extract_character_vocab(data):\n special_words = ['<pad>', '<unk>', '<s>', '<\\s>']\n\n set_words = set([character for line in data.split('\\n') for character in line])\n int_to_vocab = {word_i: word for word_i, word in enumerate(special_words + list(set_words))}\n vocab_to_int = {word: word_i for word_i, word in int_to_vocab.items()}\n\n return int_to_vocab, vocab_to_int\n\n# Build int2letter and letter2int dicts\nsource_int_to_letter, source_letter_to_int = extract_character_vocab(source_sentences)\ntarget_int_to_letter, target_letter_to_int = extract_character_vocab(target_sentences)\n\n# Convert characters to ids\nsource_letter_ids = [[source_letter_to_int.get(letter, source_letter_to_int['<unk>']) for letter in line] for line in source_sentences.split('\\n')]\ntarget_letter_ids = [[target_letter_to_int.get(letter, target_letter_to_int['<unk>']) for letter in line] for line in target_sentences.split('\\n')]\n\nprint(\"Example source sequence\")\nprint(source_letter_ids[:3])\nprint(\"\\n\")\nprint(\"Example target sequence\")\nprint(target_letter_ids[:3])", "The last step in the preprocessing stage is to determine the the longest sequence size in the dataset we'll be using, then pad all the sequences to that length.", "def pad_id_sequences(source_ids, source_letter_to_int, target_ids, target_letter_to_int, sequence_length):\n new_source_ids = [sentence + [source_letter_to_int['<pad>']] * (sequence_length - len(sentence)) \\\n for sentence in source_ids]\n new_target_ids = [sentence + [target_letter_to_int['<pad>']] * (sequence_length - len(sentence)) \\\n for sentence in target_ids]\n\n return new_source_ids, new_target_ids\n\n\n# Use the longest sequence as sequence length\nsequence_length = max(\n [len(sentence) for sentence in source_letter_ids] + [len(sentence) for sentence in target_letter_ids])\n\n# Pad all sequences up to sequence length\nsource_ids, target_ids = pad_id_sequences(source_letter_ids, source_letter_to_int, \n target_letter_ids, target_letter_to_int, sequence_length)\n\nprint(\"Sequence Length\")\nprint(sequence_length)\nprint(\"\\n\")\nprint(\"Input sequence example\")\nprint(source_ids[:3])\nprint(\"\\n\")\nprint(\"Target sequence example\")\nprint(target_ids[:3])", "This is the final shape we need them to be in. We can now proceed to building the model.\nModel\nCheck the Version of TensorFlow\nThis will check to make sure you have the correct version of TensorFlow", "from distutils.version import LooseVersion\nimport tensorflow as tf\n\n# Check TensorFlow Version\nassert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer'\nprint('TensorFlow Version: {}'.format(tf.__version__))", "Hyperparameters", "# Number of Epochs\nepochs = 60\n# Batch Size\nbatch_size = 128\n# RNN Size\nrnn_size = 50\n# Number of Layers\nnum_layers = 2\n# Embedding Size\nencoding_embedding_size = 13\ndecoding_embedding_size = 13\n# Learning Rate\nlearning_rate = 0.001", "Input", "input_data = tf.placeholder(tf.int32, [batch_size, sequence_length])\ntargets = tf.placeholder(tf.int32, [batch_size, sequence_length])\nlr = tf.placeholder(tf.float32)", "Sequence to Sequence\nThe decoder is probably the most complex part of this model. We need to declare a decoder for the training phase, and a decoder for the inference/prediction phase. These two decoders will share their parameters (so that all the weights and biases that are set during the training phase can be used when we deploy the model).\nFirst, we'll need to define the type of cell we'll be using for our decoder RNNs. We opted for LSTM.\nThen, we'll need to hookup a fully connected layer to the output of decoder. The output of this layer tells us which word the RNN is choosing to output at each time step.\nLet's first look at the inference/prediction decoder. It is the one we'll use when we deploy our chatbot to the wild (even though it comes second in the actual code).\n<img src=\"images/sequence-to-sequence-inference-decoder.png\"/>\nWe'll hand our encoder hidden state to the inference decoder and have it process its output. TensorFlow handles most of the logic for us. We just have to use tf.contrib.seq2seq.simple_decoder_fn_inference and tf.contrib.seq2seq.dynamic_rnn_decoder and supply them with the appropriate inputs.\nNotice that the inference decoder feeds the output of each time step as an input to the next.\nAs for the training decoder, we can think of it as looking like this:\n<img src=\"images/sequence-to-sequence-training-decoder.png\"/>\nThe training decoder does not feed the output of each time step to the next. Rather, the inputs to the decoder time steps are the target sequence from the training dataset (the orange letters).\nEncoding\n\nEmbed the input data using tf.contrib.layers.embed_sequence\nPass the embedded input into a stack of RNNs. Save the RNN state and ignore the output.", "source_vocab_size = len(source_letter_to_int)\n\n# Encoder embedding\nenc_embed_input = tf.contrib.layers.embed_sequence(input_data, source_vocab_size, encoding_embedding_size)\n\n# Encoder\nenc_cell = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.BasicLSTMCell(rnn_size)] * num_layers)\n_, enc_state = tf.nn.dynamic_rnn(enc_cell, enc_embed_input, dtype=tf.float32)", "Process Decoding Input", "import numpy as np\n\n# Process the input we'll feed to the decoder\nending = tf.strided_slice(targets, [0, 0], [batch_size, -1], [1, 1])\ndec_input = tf.concat([tf.fill([batch_size, 1], target_letter_to_int['<s>']), ending], 1)\n\ndemonstration_outputs = np.reshape(range(batch_size * sequence_length), (batch_size, sequence_length))\n\nsess = tf.InteractiveSession()\nprint(\"Targets\")\nprint(demonstration_outputs[:2])\nprint(\"\\n\")\nprint(\"Processed Decoding Input\")\nprint(sess.run(dec_input, {targets: demonstration_outputs})[:2])", "Decoding\n\nEmbed the decoding input\nBuild the decoding RNNs\nBuild the output layer in the decoding scope, so the weight and bias can be shared between the training and inference decoders.", "target_vocab_size = len(target_letter_to_int)\n\n# Decoder Embedding\ndec_embeddings = tf.Variable(tf.random_uniform([target_vocab_size, decoding_embedding_size]))\ndec_embed_input = tf.nn.embedding_lookup(dec_embeddings, dec_input)\n\n# Decoder RNNs\ndec_cell = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.BasicLSTMCell(rnn_size)] * num_layers)\n\nwith tf.variable_scope(\"decoding\") as decoding_scope:\n # Output Layer\n output_fn = lambda x: tf.contrib.layers.fully_connected(x, target_vocab_size, None, scope=decoding_scope)", "Decoder During Training\n\nBuild the training decoder using tf.contrib.seq2seq.simple_decoder_fn_train and tf.contrib.seq2seq.dynamic_rnn_decoder.\nApply the output layer to the output of the training decoder", "with tf.variable_scope(\"decoding\") as decoding_scope:\n # Training Decoder\n train_decoder_fn = tf.contrib.seq2seq.simple_decoder_fn_train(enc_state)\n train_pred, _, _ = tf.contrib.seq2seq.dynamic_rnn_decoder(\n dec_cell, train_decoder_fn, dec_embed_input, sequence_length, scope=decoding_scope)\n \n # Apply output function\n train_logits = output_fn(train_pred)", "Decoder During Inference\n\nReuse the weights the biases from the training decoder using tf.variable_scope(\"decoding\", reuse=True)\nBuild the inference decoder using tf.contrib.seq2seq.simple_decoder_fn_inference and tf.contrib.seq2seq.dynamic_rnn_decoder.\nThe output function is applied to the output in this step", "with tf.variable_scope(\"decoding\", reuse=True) as decoding_scope:\n # Inference Decoder\n infer_decoder_fn = tf.contrib.seq2seq.simple_decoder_fn_inference(\n output_fn, enc_state, dec_embeddings, target_letter_to_int['<s>'], target_letter_to_int['<\\s>'], \n sequence_length - 1, target_vocab_size)\n inference_logits, _, _ = tf.contrib.seq2seq.dynamic_rnn_decoder(dec_cell, infer_decoder_fn, scope=decoding_scope)", "Optimization\nOur loss function is tf.contrib.seq2seq.sequence_loss provided by the tensor flow seq2seq module. It calculates a weighted cross-entropy loss for the output logits.", "# Loss function\ncost = tf.contrib.seq2seq.sequence_loss(\n train_logits,\n targets,\n tf.ones([batch_size, sequence_length]))\n\n# Optimizer\noptimizer = tf.train.AdamOptimizer(lr)\n\n# Gradient Clipping\ngradients = optimizer.compute_gradients(cost)\ncapped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None]\ntrain_op = optimizer.apply_gradients(capped_gradients)", "Train\nWe're now ready to train our model. If you run into OOM (out of memory) issues during training, try to decrease the batch_size.", "import numpy as np\n\ntrain_source = source_ids[batch_size:]\ntrain_target = target_ids[batch_size:]\n\nvalid_source = source_ids[:batch_size]\nvalid_target = target_ids[:batch_size]\n\nsess.run(tf.global_variables_initializer())\n\nfor epoch_i in range(epochs):\n for batch_i, (source_batch, target_batch) in enumerate(\n helper.batch_data(train_source, train_target, batch_size)):\n _, loss = sess.run(\n [train_op, cost],\n {input_data: source_batch, targets: target_batch, lr: learning_rate})\n batch_train_logits = sess.run(\n inference_logits,\n {input_data: source_batch})\n batch_valid_logits = sess.run(\n inference_logits,\n {input_data: valid_source})\n\n train_acc = np.mean(np.equal(target_batch, np.argmax(batch_train_logits, 2)))\n valid_acc = np.mean(np.equal(valid_target, np.argmax(batch_valid_logits, 2)))\n print('Epoch {:>3} Batch {:>4}/{} - Train Accuracy: {:>6.3f}, Validation Accuracy: {:>6.3f}, Loss: {:>6.3f}'\n .format(epoch_i, batch_i, len(source_ids) // batch_size, train_acc, valid_acc, loss))", "Prediction", "input_sentence = 'you good'\n\n\ninput_sentence = [source_letter_to_int.get(word, source_letter_to_int['<unk>']) for word in input_sentence.lower()]\ninput_sentence = input_sentence + [0] * (sequence_length - len(input_sentence))\nbatch_shell = np.zeros((batch_size, sequence_length))\nbatch_shell[0] = input_sentence\nchatbot_logits = sess.run(inference_logits, {input_data: batch_shell})[0]\n\nprint('Input')\nprint(' Word Ids: {}'.format([i for i in input_sentence]))\nprint(' Input Words: {}'.format([source_int_to_letter[i] for i in input_sentence]))\n\nprint('\\nPrediction')\nprint(' Word Ids: {}'.format([i for i in np.argmax(chatbot_logits, 1)]))\nprint(' Chatbot Answer Words: {}'.format([target_int_to_letter[i] for i in np.argmax(chatbot_logits, 1)]))" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
sbussmann/sleep-bit
notebooks/sbussmann_get-fitbit-data.ipynb
mit
[ "Summary\nUse python-fitbit to interact with the Fitbit API and get sleep and intraday activity data. Store as json files in data/raw.", "%load_ext pypath_magic\n\n%pypath -a /Users/rbussman/Projects/sleep-bit\n\nfrom src.data import get_fitbit\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport seaborn as sns\nsns.set_context('poster')\n\nimport pandas as pd\nimport time\n\ndaterange = pd.date_range('2017-03-30', '2017-08-10')", "Intraday steps", "# fitbit limits API calls to 150 per hour\nrate_limit = 140\napi_calls = 0\nfor date in daterange:\n fitbit_data = get_fitbit.FitbitData(date, 'intraday')\n sleep_log = fitbit_data.download_from_fitbit()\n fitbit_data.write_to_disk(sleep_log)\n api_calls += 1\n if api_calls > rate_limit:\n print(\"We've exceeded the fitbit rate limit. Pausing for 1 hour.\")\n time.sleep(3600)\n api_calls = 0\n ", "Sleep logs", "# fitbit limits API calls to 150 per hour\nrate_limit = 140\napi_calls = 0\nfor date in daterange:\n fitbit_data = get_fitbit.FitbitData(date, 'sleep')\n sleep_log = fitbit_data.download_from_fitbit()\n fitbit_data.write_to_disk(sleep_log)\n api_calls += 1\n if api_calls > rate_limit:\n print(\"We've exceeded the fitbit rate limit. Pausing for 1 hour.\")\n time.sleep(3600)\n api_calls = 0\n " ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
luofan18/deep-learning
dcgan-svhn/DCGAN.ipynb
mit
[ "Deep Convolutional GANs\nIn this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a Deep Convolutional GAN, or DCGAN for short. The DCGAN architecture was first explored last year and has seen impressive results in generating new images, you can read the original paper here.\nYou'll be training DCGAN on the Street View House Numbers (SVHN) dataset. These are color images of house numbers collected from Google street view. SVHN images are in color and much more variable than MNIST. \n\nSo, we'll need a deeper and more powerful network. This is accomplished through using convolutional layers in the discriminator and generator. It's also necessary to use batch normalization to get the convolutional networks to train. The only real changes compared to what you saw previously are in the generator and discriminator, otherwise the rest of the implementation is the same.", "%matplotlib inline\n\nimport pickle as pkl\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.io import loadmat\nimport tensorflow as tf\n\n!mkdir data", "Getting the data\nHere you can download the SVHN dataset. Run the cell above and it'll download to your machine.", "from urllib.request import urlretrieve\nfrom os.path import isfile, isdir\nfrom tqdm import tqdm\n\ndata_dir = 'data/'\n\nif not isdir(data_dir):\n raise Exception(\"Data directory doesn't exist!\")\n\nclass DLProgress(tqdm):\n last_block = 0\n\n def hook(self, block_num=1, block_size=1, total_size=None):\n self.total = total_size\n self.update((block_num - self.last_block) * block_size)\n self.last_block = block_num\n\nif not isfile(data_dir + \"train_32x32.mat\"):\n with DLProgress(unit='B', unit_scale=True, miniters=1, desc='SVHN Training Set') as pbar:\n urlretrieve(\n 'http://ufldl.stanford.edu/housenumbers/train_32x32.mat',\n data_dir + 'train_32x32.mat',\n pbar.hook)\n\nif not isfile(data_dir + \"test_32x32.mat\"):\n with DLProgress(unit='B', unit_scale=True, miniters=1, desc='SVHN Testing Set') as pbar:\n urlretrieve(\n 'http://ufldl.stanford.edu/housenumbers/test_32x32.mat',\n data_dir + 'test_32x32.mat',\n pbar.hook)", "These SVHN files are .mat files typically used with Matlab. However, we can load them in with scipy.io.loadmat which we imported above.", "trainset = loadmat(data_dir + 'train_32x32.mat')\ntestset = loadmat(data_dir + 'test_32x32.mat')", "Here I'm showing a small sample of the images. Each of these is 32x32 with 3 color channels (RGB). These are the real images we'll pass to the discriminator and what the generator will eventually fake.", "idx = np.random.randint(0, trainset['X'].shape[3], size=36)\nfig, axes = plt.subplots(6, 6, sharex=True, sharey=True, figsize=(5,5),)\nfor ii, ax in zip(idx, axes.flatten()):\n ax.imshow(trainset['X'][:,:,:,ii], aspect='equal')\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\nplt.subplots_adjust(wspace=0, hspace=0)", "Here we need to do a bit of preprocessing and getting the images into a form where we can pass batches to the network. First off, we need to rescale the images to a range of -1 to 1, since the output of our generator is also in that range. We also have a set of test and validation images which could be used if we're trying to identify the numbers in the images.", "def scale(x, feature_range=(-1, 1)):\n # scale to (0, 1)\n x = ((x - x.min())/(255 - x.min()))\n \n # scale to feature_range\n min, max = feature_range\n x = x * (max - min) + min\n return x\n\nclass Dataset:\n def __init__(self, train, test, val_frac=0.5, shuffle=False, scale_func=None):\n split_idx = int(len(test['y'])*(1 - val_frac))\n self.test_x, self.valid_x = test['X'][:,:,:,:split_idx], test['X'][:,:,:,split_idx:]\n self.test_y, self.valid_y = test['y'][:split_idx], test['y'][split_idx:]\n self.train_x, self.train_y = train['X'], train['y']\n \n self.train_x = np.rollaxis(self.train_x, 3)\n self.valid_x = np.rollaxis(self.valid_x, 3)\n self.test_x = np.rollaxis(self.test_x, 3)\n \n if scale_func is None:\n self.scaler = scale\n else:\n self.scaler = scale_func\n self.shuffle = shuffle\n \n def batches(self, batch_size):\n if self.shuffle:\n idx = np.arange(len(dataset.train_x))\n np.random.shuffle(idx)\n self.train_x = self.train_x[idx]\n self.train_y = self.train_y[idx]\n \n n_batches = len(self.train_y)//batch_size\n for ii in range(0, len(self.train_y), batch_size):\n x = self.train_x[ii:ii+batch_size]\n y = self.train_y[ii:ii+batch_size]\n \n yield self.scaler(x), y", "Network Inputs\nHere, just creating some placeholders like normal.", "def model_inputs(real_dim, z_dim):\n inputs_real = tf.placeholder(tf.float32, (None, *real_dim), name='input_real')\n inputs_z = tf.placeholder(tf.float32, (None, z_dim), name='input_z')\n \n return inputs_real, inputs_z", "Generator\nHere you'll build the generator network. The input will be our noise vector z as before. Also as before, the output will be a $tanh$ output, but this time with size 32x32 which is the size of our SVHN images.\nWhat's new here is we'll use convolutional layers to create our new images. The first layer is a fully connected layer which is reshaped into a deep and narrow layer, something like 4x4x1024 as in the original DCGAN paper. Then we use batch normalization and a leaky ReLU activation. Next is a transposed convolution where typically you'd halve the depth and double the width and height of the previous layer. Again, we use batch normalization and leaky ReLU. For each of these layers, the general scheme is convolution > batch norm > leaky ReLU.\nYou keep stacking layers up like this until you get the final transposed convolution layer with shape 32x32x3. Below is the archicture used in the original DCGAN paper:\n\nNote that the final layer here is 64x64x3, while for our SVHN dataset, we only want it to be 32x32x3.", "def generator(z, output_dim, reuse=False, alpha=0.2, training=True):\n with tf.variable_scope('generator', reuse=reuse):\n # First fully connected layer\n x1 = tf.layers.dense(z, 4*4*512)\n # Reshape it to start the convolutional stack\n x1 = tf.reshape(x1, (-1, 4, 4, 512))\n x1 = tf.layers.batch_normalization(x1, training=training)\n x1 = tf.maximum(alpha * x1, x1)\n # 4x4x512 now\n \n x2 = tf.layers.conv2d_transpose(x1, 256, 5, strides=2, padding='same')\n x2 = tf.layers.batch_normalization(x2, training=training)\n x2 = tf.maximum(alpha * x2, x2)\n # 8x8x256 now\n \n x3 = tf.layers.conv2d_transpose(x2, 128, 5, strides=2, padding='same')\n x3 = tf.layers.batch_normalization(x3, training=training)\n x3 = tf.maximum(alpha * x3, x3)\n # 16x16x128 now\n \n # Output layer\n logits = tf.layers.conv2d_transpose(x3, output_dim, 5, strides=2, padding='same')\n # 32x32x3 now\n \n out = tf.tanh(logits)\n \n return out", "Discriminator\nHere you'll build the discriminator. This is basically just a convolutional classifier like you've build before. The input to the discriminator are 32x32x3 tensors/images. You'll want a few convolutional layers, then a fully connected layer for the output. As before, we want a sigmoid output, and you'll need to return the logits as well. For the depths of the convolutional layers I suggest starting with 16, 32, 64 filters in the first layer, then double the depth as you add layers. Note that in the DCGAN paper, they did all the downsampling using only strided convolutional layers with no maxpool layers.\nYou'll also want to use batch normalization with tf.layers.batch_normalization on each layer except the first convolutional and output layers. Again, each layer should look something like convolution > batch norm > leaky ReLU. \nNote: in this project, your batch normalization layers will always use batch statistics. (That is, always set training to True.) That's because we are only interested in using the discriminator to help train the generator. However, if you wanted to use the discriminator for inference later, then you would need to set the training parameter appropriately.", "def discriminator(x, reuse=False, alpha=0.2):\n with tf.variable_scope('discriminator', reuse=reuse):\n # Input layer is 32x32x3\n x1 = tf.layers.conv2d(x, 64, 5, strides=2, padding='same')\n relu1 = tf.maximum(alpha * x1, x1)\n # 16x16x64\n \n x2 = tf.layers.conv2d(relu1, 128, 5, strides=2, padding='same')\n bn2 = tf.layers.batch_normalization(x2, training=True)\n relu2 = tf.maximum(alpha * bn2, bn2)\n # 8x8x128\n \n x3 = tf.layers.conv2d(relu2, 256, 5, strides=2, padding='same')\n bn3 = tf.layers.batch_normalization(x3, training=True)\n relu3 = tf.maximum(alpha * bn3, bn3)\n # 4x4x256\n\n # Flatten it\n flat = tf.reshape(relu3, (-1, 4*4*256))\n logits = tf.layers.dense(flat, 1)\n out = tf.sigmoid(logits)\n \n return out, logits", "Model Loss\nCalculating the loss like before, nothing new here.", "def model_loss(input_real, input_z, output_dim, alpha=0.2):\n \"\"\"\n Get the loss for the discriminator and generator\n :param input_real: Images from the real dataset\n :param input_z: Z input\n :param out_channel_dim: The number of channels in the output image\n :return: A tuple of (discriminator loss, generator loss)\n \"\"\"\n g_model = generator(input_z, output_dim, alpha=alpha)\n d_model_real, d_logits_real = discriminator(input_real, alpha=alpha)\n d_model_fake, d_logits_fake = discriminator(g_model, reuse=True, alpha=alpha)\n\n d_loss_real = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, labels=tf.ones_like(d_model_real)))\n d_loss_fake = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.zeros_like(d_model_fake)))\n g_loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.ones_like(d_model_fake)))\n\n d_loss = d_loss_real + d_loss_fake\n\n return d_loss, g_loss", "Optimizers\nNot much new here, but notice how the train operations are wrapped in a with tf.control_dependencies block so the batch normalization layers can update their population statistics.", "def model_opt(d_loss, g_loss, learning_rate, beta1):\n \"\"\"\n Get optimization operations\n :param d_loss: Discriminator loss Tensor\n :param g_loss: Generator loss Tensor\n :param learning_rate: Learning Rate Placeholder\n :param beta1: The exponential decay rate for the 1st moment in the optimizer\n :return: A tuple of (discriminator training operation, generator training operation)\n \"\"\"\n # Get weights and bias to update\n t_vars = tf.trainable_variables()\n d_vars = [var for var in t_vars if var.name.startswith('discriminator')]\n g_vars = [var for var in t_vars if var.name.startswith('generator')]\n\n # Optimize\n with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n d_train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(d_loss, var_list=d_vars)\n g_train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(g_loss, var_list=g_vars)\n\n return d_train_opt, g_train_opt", "Building the model\nHere we can use the functions we defined about to build the model as a class. This will make it easier to move the network around in our code since the nodes and operations in the graph are packaged in one object.", "class GAN:\n def __init__(self, real_size, z_size, learning_rate, alpha=0.2, beta1=0.5):\n tf.reset_default_graph()\n \n self.input_real, self.input_z = model_inputs(real_size, z_size)\n \n self.d_loss, self.g_loss = model_loss(self.input_real, self.input_z,\n real_size[2], alpha=0.2)\n \n self.d_opt, self.g_opt = model_opt(self.d_loss, self.g_loss, learning_rate, beta1)", "Here is a function for displaying generated images.", "def view_samples(epoch, samples, nrows, ncols, figsize=(5,5)):\n fig, axes = plt.subplots(figsize=figsize, nrows=nrows, ncols=ncols, \n sharey=True, sharex=True)\n for ax, img in zip(axes.flatten(), samples[epoch]):\n ax.axis('off')\n img = ((img - img.min())*255 / (img.max() - img.min())).astype(np.uint8)\n ax.set_adjustable('box-forced')\n im = ax.imshow(img, aspect='equal')\n \n plt.subplots_adjust(wspace=0, hspace=0)\n return fig, axes", "And another function we can use to train our network. Notice when we call generator to create the samples to display, we set training to False. That's so the batch normalization layers will use the population statistics rather than the batch statistics. Also notice that we set the net.input_real placeholder when we run the generator's optimizer. The generator doesn't actually use it, but we'd get an error without it because of the tf.control_dependencies block we created in model_opt.", "def train(net, dataset, epochs, batch_size, print_every=10, show_every=100, figsize=(5,5)):\n saver = tf.train.Saver()\n sample_z = np.random.uniform(-1, 1, size=(72, z_size))\n\n samples, losses = [], []\n steps = 0\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for e in range(epochs):\n for x, y in dataset.batches(batch_size):\n steps += 1\n\n # Sample random noise for G\n batch_z = np.random.uniform(-1, 1, size=(batch_size, z_size))\n\n # Run optimizers\n _ = sess.run(net.d_opt, feed_dict={net.input_real: x, net.input_z: batch_z})\n _ = sess.run(net.g_opt, feed_dict={net.input_z: batch_z, net.input_real: x})\n\n if steps % print_every == 0:\n # At the end of each epoch, get the losses and print them out\n train_loss_d = net.d_loss.eval({net.input_z: batch_z, net.input_real: x})\n train_loss_g = net.g_loss.eval({net.input_z: batch_z})\n\n print(\"Epoch {}/{}...\".format(e+1, epochs),\n \"Discriminator Loss: {:.4f}...\".format(train_loss_d),\n \"Generator Loss: {:.4f}\".format(train_loss_g))\n # Save losses to view after training\n losses.append((train_loss_d, train_loss_g))\n\n if steps % show_every == 0:\n gen_samples = sess.run(\n generator(net.input_z, 3, reuse=True, training=False),\n feed_dict={net.input_z: sample_z})\n samples.append(gen_samples)\n _ = view_samples(-1, samples, 6, 12, figsize=figsize)\n plt.show()\n\n saver.save(sess, './checkpoints/generator.ckpt')\n\n with open('samples.pkl', 'wb') as f:\n pkl.dump(samples, f)\n \n return losses, samples", "Hyperparameters\nGANs are very sensitive to hyperparameters. A lot of experimentation goes into finding the best hyperparameters such that the generator and discriminator don't overpower each other. Try out your own hyperparameters or read the DCGAN paper to see what worked for them.", "real_size = (32,32,3)\nz_size = 100\nlearning_rate = 0.0002\nbatch_size = 128\nepochs = 25\nalpha = 0.2\nbeta1 = 0.5\n\n# Create the network\nnet = GAN(real_size, z_size, learning_rate, alpha=alpha, beta1=beta1)\n\ndataset = Dataset(trainset, testset)\n\nlosses, samples = train(net, dataset, epochs, batch_size, figsize=(10,5))\n\nfig, ax = plt.subplots()\nlosses = np.array(losses)\nplt.plot(losses.T[0], label='Discriminator', alpha=0.5)\nplt.plot(losses.T[1], label='Generator', alpha=0.5)\nplt.title(\"Training Losses\")\nplt.legend()\n\nfig, ax = plt.subplots()\nlosses = np.array(losses)\nplt.plot(losses.T[0], label='Discriminator', alpha=0.5)\nplt.plot(losses.T[1], label='Generator', alpha=0.5)\nplt.title(\"Training Losses\")\nplt.legend()\n\n_ = view_samples(-1, samples, 6, 12, figsize=(10,5))\n\n_ = view_samples(-1, samples, 6, 12, figsize=(10,5))" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
ealogar/curso-python
basic/0_What_is_python.ipynb
apache-2.0
[ "Run the following:", "#Run this from command line\n!python -c \"import this\"\n\n#Inside a python console\nimport this", "From official website ( http://www.python.org/ ):\nPython is a programming language that lets you work more quickly and integrate\nyour systems more effectively. You can learn to use Python and see almost\nimmediate gains in productivity and lower maintenance costs.\nExecutive summary from official website ( http://www.python.org/doc/essays/blurb.html )\nPython is an interpreted, object-oriented, high-level programming language\n with dynamic semantics. Its high-level built in data structures, combined\n with dynamic typing and dynamic binding, make it very attractive for Rapid\n Application Development, as well as for use as a scripting or glue language\n to connect existing components together. Python's simple, easy to learn syntax\n emphasizes readability and therefore reduces the cost of program maintenance.\n Python supports modules and packages, which encourages program modularity and\n code reuse. The Python interpreter and the extensive standard library are\n available in source or binary form without charge for all major platforms,\n and can be freely distributed.\nTO SUM UP\n\nquick development\nsimple, readable, easy to learn syntax\ngeneral purpose\ninterpreted (not compiled)\nobject-oriented\nhigh-level\ndynamic semantics (aka execution semantics)\nfully dynamic typing\ndynamic binding\nlow programs manteinance cost\nmodularity and code reuse\nno licensing costs\nextensive standard library, \"batteries included\"\nimperative and functional programming\nautomatic memory management", "# execution semantics\nfor i in range(10):\n print i**2\nprint \"Outside for loop\"\n\n# dynamic binding\nmy_str = \"hola\"\ntype(my_str)\n\n# dynamic binding\nmy_str = 90\ntype(my_str)\n\n# fully dynamic typing\n4 +5 +6\n\n# fully dynamic typing\n4 + \"hola\"", "HISTORY\n\nhttp://docs.python.org/2/license.html\nhttp://en.wikipedia.org/wiki/History_of_Python\nhttp://en.wikipedia.org/wiki/Benevolent_Dictator_For_Life\nhttp://www.python.org/dev/peps/pep-0001/\nhttp://docs.python.org/3.0/whatsnew/3.0.html\n\nTOOLS\nCPython is the real name of default standard Python implementation\n - The interpreter is deployed together with standard library\n - It can take a file as argument to run. Otherwise it opens and interactive console\n - With '-m' parameter you can execute directly certain modules (debugging, profiling)\n - Implemented in C\nThere are Python implementations in other languages:\n - Jython: Python 2.5 interpreter written in Java which runs bytecode in the JVM\n - IronPython: Similar approach for .NET Common Language Runtime\n - JS, C++, CIL...\n - Stackless Python: CPython fork with microthreads concurrency\n - PyPy: Python 2.7 interpreter implemented in Python. Really fast, multi-core...!!!\nIPython: create a comprehensive environment for interactive and exploratory computing\nAn enhanced interactive Python shell\nAn architecture for interactive parallel computing:\n - Other powerful interactive shells (terminal and Qt-based)\n - A browser-based notebook with support for code, text, mathematical expressions\n inline plots and other rich media\n - Support for interactive data visualization and use of GUI toolkits\n - Flexible, embeddable interpreters to load into your own projects\n - Easy to use, high performance tools for parallel computing\n - Recently funded with $1.15M from the Alfred P. Sloan Foundation\nvirtualenv: a tool to create isolated Python environments\nIt simply changes your PATH environment var to point to a different folder\nPyPi: The Python Package Index is a repository of software for the Python programming language.\nThere are currently 89324 packages here.\nThe packages are 'eggs'.\npip: A tool for installing and managing Python packages\nIt installs packages from PyPi, local folders or Git and other repositories\nIt can read a list of packages from a file or generate the list of installed packages\nInstalling pip and virtualenv for a python interpreter\n```sh\nwget https://bootstrap.pypa.io/get-pip.py\npython get-pip.py\npip install virtualenv\nvirtualenv env\nsource env/bin/activate\nfinish virtualenv running deactivate\n```\nIDE?\n - PyCharm (we have licenses, ask EPG)\n - Eclipse + Pydev\n - NetBeans\n - Eric\n - NINJA IDE\n - Aptana Studio 3\n - SPE\n - Python's IDLE (not recommendable at all)\n - ...\n - Emacs\n - Vi\nhttp://wiki.python.org/moin/IntegratedDevelopmentEnvironments\nLots of good IDEs, it's up to you!" ]
[ "markdown", "code", "markdown", "code", "markdown" ]
rrbb014/data_science
fastcampus_dss/2016_05_25/0525_06__확률 밀도 함수의 독립.ipynb
mit
[ "확률 밀도 함수의 독립\n만약 두 확률 변수 $X$, $Y$의 결합 확률 밀도 함수(joint pdf)가 주변 확률 밀도 함수(marginal pdf)의 곱으로 나타나면 두 확률 변수가 서로 독립(independent)이라고 한다.\n$$ f_{XY}(x, y) = f_X(x)f_Y(y) $$\n이 함수 식에서 볼 수 있듯이 독립인 경우에는 각각의 주변 확률 밀도 함수만으로 결합 확률 밀도 함수가 결정된다. 즉, $Y$가 어떤 값을 가지더라도 $X$의 주변 확률 밀도 함수는 변하지 않는다.\n독립 확률 변수의 기댓값\n독립 확률 변수들의 기댓값은 다음 성질을 만족한다. \n$$ \\text{E}[XY] = \\text{E}[X]\\text{E}[Y] $$\n(증명)\n$$ \n\\begin{eqnarray}\n\\text{E}[XY] \n&=& \\int xy \\;f_{XY}(x, y) \\; dx dy \\\n&=& \\int xy \\;f_{X}(x)f_{Y}(y) \\; dx dy \\\n&=& \\int x \\;f_{X}(x) \\; dx \\int y \\;f_{Y}(y) \\; dy \\\n&=& \\text{E}[X] \\text{E}[Y] \\\n\\end{eqnarray}\n$$\n독립 확률 변수들의 분산\n또한 독립 확률 변수들의 분산은 다음 성질을 만족한다. \n$$ \\text{Var}[X+Y] = \\text{Var}[X] + \\text{Var}[Y] $$\n(증명)\n$$ \n\\begin{eqnarray}\n\\text{Var}[X + Y] \n&=& \\text{E}[((X + Y) - (\\mu_X + \\mu_Y))^2] \\\n&=& \\text{E}[(X+Y)^2 - 2(X+Y)(\\mu_X + \\mu_Y) + (\\mu_X + \\mu_Y)^2] \\\n&=& \\text{E}[X^2+2XY+Y^2] - 2(\\mu_X + \\mu_Y)\\text{E}[X+Y] + (\\mu_X + \\mu_Y)^2 \\\n&=& \\text{E}[X^2+2XY+Y^2] - 2(\\mu_X + \\mu_Y)^2 + (\\mu_X + \\mu_Y)^2 \\\n&=& \\text{E}[X^2]+2\\text{E}[XY]+\\text{E}[Y^2] - (\\mu_X + \\mu_Y)^2 \\\n&=& \\text{E}[X^2]+2\\text{E}[X]\\text{E}[Y]+\\text{E}[Y^2] - (\\mu_X^2 + 2\\mu_X\\mu_Y + \\mu_Y^2) \\\n&=& \\text{E}[X^2]-\\mu_X^2+\\text{E}[Y^2]-\\mu_Y^2+2\\text{E}[X]\\text{E}[Y] - 2\\mu_X\\mu_Y \\\n&=& \\text{Var}[X]+\\text{Var}[Y] \\\n\\end{eqnarray}\n$$\n조건부 확률 분포\n또한 조건부 확률 밀도 함수에는 다음과 같은 관계가 성립한다.\n$$ f_{X \\mid Y} (x | y_0) = \\dfrac{f_{XY}(x, y=y_0)}{f_{Y}(y_0)} = \\dfrac{f_{X}(x) f_{Y}(y_0)}{f_{Y}(y_0)} = f_{X}(x) $$\n$$ f_{Y \\mid X} (y | x_0) = \\dfrac{f_{XY}(x=x_0, y)}{f_{X}(x_0)} = \\dfrac{f_{X}(x_0) f_{Y}(y)}{f_{X}(x_0)} = f_{Y}(y) $$\n확률 변수 $X$가 다른 확률 변수 $Y$에 독립이면 조건부 확률 분포가 조건이 되는 확률 변수의 값에 영향을 받지 않는다. 즉, $Y$ 값이 $y_1$일 때와 $y_2$일 때의 조건부 확률 분포 $f(x \\mid y_1)$과 $f(x \\mid y_2)$이 같다는 의미이다. \n예를 들어 다음과 같은 두 이산 확률 변수의 결합 확률 분포를 보자.", "np.set_printoptions(precision=4)\npmf1 = np.array([[0, 1, 2, 3, 2, 1],\n [0, 2, 4, 6, 4, 2],\n [0, 4, 8,12, 8, 4],\n [0, 2, 4, 6, 4, 2],\n [0, 1, 2, 3, 2, 1]])\npmf1 = pmf1/pmf1.sum()\npmf1\n\nsns.heatmap(pmf1)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Joint Probability (Independent)\")\nplt.show()", "이 확률 분포는 다음 식에서 보다시피 주변 확률 분포의 곱으로 표현된다.", "pmf1_marginal_x = pmf1.sum(axis=0)\npmf1_marginal_y = pmf1.sum(axis=1)\npmf = pmf1_marginal_x * pmf1_marginal_y[:, np.newaxis]\npmf/pmf.sum()", "여러 가지 Y값을 바꾸어도 조건부 확률은 변하지 않는 것을 확인할 수 있다.", "cond_x_y0 = pmf1[0, :]/pmf1_marginal_y[0]\ncond_x_y0\n\ncond_x_y1 = pmf1[1, :]/pmf1_marginal_y[1]\ncond_x_y1\n\ncond_x_y2 = pmf1[2, :]/pmf1_marginal_y[2]\ncond_x_y2", "이번에는 다음과 같은 결합 확률 분포를 보자. 이 경우에는 독립 조건이 성립하지 않는다.", "pmf2 = np.array([[0, 0, 0, 0, 1, 1],\n [0, 0, 1, 2, 1, 0],\n [0, 1, 3, 3, 1, 0],\n [0, 1, 2, 1, 0, 0],\n [1, 1, 0, 0, 0, 0]])\npmf2 = pmf2/pmf2.sum()\npmf2\n\nsns.heatmap(pmf2)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Joint Probability (Dependent)\")\nplt.show()", "이 경우에는 y값에 따라 x의 조건부 확률 분포가 달라지는 것을 확인할 수 있다.", "pmf2_marginal_x = pmf2.sum(axis=0)\npmf2_marginal_y = pmf2.sum(axis=1)\n\ncond_x_y0 = pmf2[0, :]/pmf2_marginal_y[0]\ncond_x_y0\n\ncond_x_y1 = pmf2[1, :]/pmf2_marginal_y[1]\ncond_x_y1\n\ncond_x_y2 = pmf2[2, :]/pmf2_marginal_y[2]\ncond_x_y2", "두 확률 변수가 독립이 아닌 경우, 즉 결합 확률 분포(확률 밀도 함수 또는 확률 질량 함수)가 두 개의 주변 분포의 곱으로 나누어지지 않는 경우에는 두 확률 변수가 서로 의존(dependent)한다고 한다. \n예를 들어 5명이 있는 어떤 반에서 한 명을 대표로 뽑아 시험을 보아야 한다고 하자. \n위 확률 분포 $X$, $Y$에서 $Y$가 학생의 번호가 되고 $X \\mid Y$는 반 대표가 된 학생의 시험 점수이다. \n첫번째(독립) 경우에는 어떤 학생이 대표가 된다고 하더라도 시험 점수의 분포가 동일하지만 두번째(의존) 경우에는 0번 학생이 뽑인다면 4점, 혹은 5점을 받고 4번 학생이 뽑이면 0점 또는 1점을 받게 되므로 조건부 시험 점수 $X \\mid Y$ 는 $Y$ 값에 의존한다고 말할 수 있다." ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
mbuchove/notebook-wurk-b
stats/astro283_hw4.ipynb
mit
[ "<h1>HW 4</h1>\nMatt Buchovecky\nAstro 283 \n<h3>Reperform the fit and do a source subtraction again</h3>\nI will first do a quick repeat of the fit from last time. I then subtract the best fit of the star from the original data in each bin to get a subtracted map", "import numpy\nfrom astropy.io import fits \nfrom scipy import optimize, ndimage\nfrom matplotlib import pyplot, cm\n%matplotlib inline \n\n\n\nstar_fits = fits.open(\"./hw3prob1-data.fits\")\nstar_data = star_fits[0].data\nstar_rav = star_data.ravel()\n\n", "Note: The flux parameter we got last time more corresponded to a flux density that fit into this function: \n$$ f\\left(x,y,\\vec z\\right) = Fexp{\\left[-\\frac{\\left(x-x_c\\right)^2+\\left(y-y_c\\right)^2}{2\\sigma_{PSF}^2}\\right]} $$\nHowever the total flux of the star would be this function integrated over all space, which would essentially multiply the parameter $F$ by the integral of the gaussian, which for a symmetric 2-D space gives:\n$$ F_{tot} = F * \\left(2\\pi\\sigma^2\\right) $$\nI think to do the whole thing correctly, the predicted flux in each bin will be the flux density $F$ integrated over the bounds of the cell. It seems the method used before worked well because the bins are very small, so the gaussian function is roughly constant over their area, and we're working in spatial units of bins, so their area happens to be 1. The results may come out better if this is done more rigorously, perhaps with 64 bit floats. The subtraction and the chi square come out nicely though, so this is something I will investigate after turning this in :/", "def symm_2d_gaussian(pos, F, xc, yc, sigma, B):\n return F*numpy.exp(-((pos[0]-xc)**2+(pos[1]-yc)**2)/(2*sigma**2)) + B\n \n\nx_bins = star_data.shape[0]\ny_bins = star_data.shape[1]\n\n# Create x and y indices\nx_arr = numpy.linspace(0, x_bins-1, x_bins)\ny_arr = numpy.linspace(0, y_bins-1, y_bins)\nx_arr, y_arr = numpy.meshgrid(x_arr, y_arr)\ncoords = x_arr, y_arr\n\nx_rav = x_arr.ravel()\ny_rav = y_arr.ravel()\n\npi = numpy.pi\n\ninit_guess = (50, 130, 130, 20, 100)\nsigma_array = numpy.sqrt(star_data)\np_opt_singl, p_cov_singl = optimize.curve_fit(symm_2d_gaussian, (x_rav, y_rav), star_rav, init_guess, sigma_array.ravel())\n\n\nsingl_subt = star_data - symm_2d_gaussian((x_arr,y_arr), *p_opt_singl)\nsmoothed_sub = ndimage.gaussian_filter(singl_subt, 3)\npyplot.imshow(smoothed_sub, origin='lower')\nsub_plot = pyplot.imshow(smoothed_sub)\npyplot.xlabel('x')\npyplot.ylabel('y')\npyplot.title(\"subtracted map\")\ncbar = pyplot.colorbar(label='DN')\n#cbar.solids.set_edgecolors('face')\n", "Looking at the gaussian smoothed map of the residual, it does appear that this could very well be a binary star system!\n<h4>Chi squared test on subtraction</h4>\n$$\\chi^2 = \\sum_{x,y} \\frac{\\left(D_{xy}-f_{xy}\\right)^2}{2\\sigma^2}$$\n$$\\chi^2_{red} = \\frac{\\chi^2}{\\nu}$$", "def chi_square_(function, params, x_vals, data_vals, var_vals):\n residuals = (data_vals - function(x_vals, *params))\n chis = (residuals**2)/abs(var_vals)\n chi_sum = numpy.sum(chis)\n d_o_f = len(x_vals[0]) - len(params)\n return (chi_sum, d_o_f)\n\n\ncs_singl, dof_singl = chi_square_(symm_2d_gaussian, p_opt_singl, (x_rav,y_rav), star_rav, star_rav)\nred_cs_singl = cs_singl / dof_singl\nprint(red_cs_singl)\n", "<h4>Try to fit binary star</h4>\n\n$$f_{bin}(x,y,\\vec{z}) = F_1\\exp\\left[-\\frac{(x-x_c-\\frac{1}{2}r\\sin\\theta)^2 + (y-y_c-\\frac{1}{2}r\\cos\\theta)^2}{2\\sigma_{PSF}^2}\\right] + F_2\\exp\\left[-\\frac{(x-x_c+\\frac{1}{2}r\\sin\\theta)^2 + (y-y_c+\\frac{1}{2}r\\cos\\theta)^2}{2\\sigma_{PSF}^2}\\right] + B$$", "def binary_star(pos, F1, F2, xc, yc, rad, theta, sigma, B):\n f1 = F1*numpy.exp(-((pos[0]-(xc+rad*numpy.cos(theta)))**2+(pos[1]-(yc+rad*numpy.sin(theta)))**2)/(2*sigma**2))\n f2 = F2*numpy.exp(-((pos[0]-(xc-rad*numpy.cos(theta)))**2+(pos[1]-(yc-rad*numpy.sin(theta)))**2)/(2*sigma**2))\n return f1 + f2 + B\n# should my radius be double this ?\n\n\nsigma_array = numpy.sqrt(star_data)\nsigma_rav = sigma_array.ravel()\nbin_guess = (p_opt_singl[0]/2, p_opt_singl[0]/2, p_opt_singl[1], p_opt_singl[2], 5., numpy.pi/4., p_opt_singl[3], p_opt_singl[4])\np_opt_bin, p_cov_bin = optimize.curve_fit(binary_star, (x_rav,y_rav), star_rav, bin_guess, sigma_rav)\n\nprint(p_opt_bin)\nprint(p_cov_bin)\n\n\nbin_subt = star_data - binary_star((x_arr,y_arr), *p_opt_bin)\nsmoothed_sub = ndimage.gaussian_filter(bin_subt, 3)\npyplot.imshow(smoothed_sub, origin='lower')\nsub_plot = pyplot.imshow(smoothed_sub)\npyplot.xlabel('x')\npyplot.ylabel('y')\npyplot.title(\"subtracted map\")\ncbar = pyplot.colorbar(label='DN')\n\ncs_bin, dof_bin = chi_square_(binary_star, p_opt_bin, (x_rav,y_rav), star_rav, star_rav)\nred_cs_bin = cs_bin / dof_bin\nprint( red_cs_bin)\n", "The subtracted map looks much better and the chi square value goes down a bit, now let's do the likelihood ratio test to be more sure\n<h3>Likelihood ratio test</h3>\n\nWe would like to compare the likelihoods of the two models, over a range of possible parameters, not just the best fit parameters. From the notes:\n$$\\frac{P\\left(B \\mid {D_{x,y}}\\right)}{P\\left(S \\mid {D_{x,y}}\\right)} = \\frac{P\\left({D_{x,y}}\\mid B\\right)P\\left(B\\right)}{P\\left({D_{x,y}}\\mid S\\right)P\\left(S\\right)}$$\nThe prior terms, $P\\left(\\left{D_{x,y}\\right}\\right)$, are the same in numerator and denominator, and cancel, since we're talking about the same data set.\nThe likelihood terms for each model are found by integrating over the parameter space for that model:\n\\begin{eqnarray}\nP\\left({D_{x,y}}\\mid M\\right) &=& \\int P\\left({D_{x,y}},{\\vec{z}M}\\mid M\\right)d\\vec{z}_M\\\n&=& \\int P\\left({D{x,y}}\\mid {\\vec{z}M}, M\\right)P\\left({\\vec{z}_M}\\mid M\\right)d\\vec{z}_M\n\\end{eqnarray}\nThe first term in the integrand, the probability of the data given a set of parameters, can be approximated as being a gaussian distributed centered around the best fit parameters, $\\vec{z}_0$, in $n$-space where $n$ is the number of parameters for the model, and $\\Sigma$ is the best-fit covariance matrix:\n\\begin{eqnarray}\nP\\left({D{x,y}}, \\vec{z}M\\mid M\\right) &\\approx& P\\left({D{x,y}},{\\vec{z}_0}\\mid M\\right)\\exp{\\left[-\\frac{1}{2}\\left(\\vec{z}_M-\\vec{z}_0\\right)^T\\Sigma^{-1}\\left(\\vec{z}_M-\\vec{z}_0\\right)\\right]}\\\n\\end{eqnarray}\nTo make this integral workable for this case, we can use uniform priors. I think a more rigorous treatment of the priors would have super high fluxes become less and less probable, considering an extreme case, the probability of having a star flux be greater than the sun, or even Sirius for that matter, would quickly descend to 0. For now, we will just assume a uniform distribution up to a reasonable flux density, and cut it off after that.\n$$P({\\vec{z}}\\mid M) = \\prod_i P(z_i\\mid M) = \\prod_i\\frac{1}{z_i^{\\text{max}} - z_i^{\\text{min}}}$$\nThis constant term can be pulled out of the integral, leaving:\n\\begin{eqnarray}\nP\\left({D_{x,y}}\\mid M\\right) &=& P\\left({D_{x,y}},\\vec{z}0\\mid M\\right)\\prod_i\\frac{1}{z_i^{\\text{max}} - z_i^{\\text{min}}}\\int \\exp\\left[-\\frac{1}{2}(\\lambda-\\lambda_0)^T\\Sigma^{-1}(\\lambda-\\lambda_0)\\right]d\\vec{z}\\\n&=& P\\left({D{x,y}},\\vec{z}_0\\mid M\\right)\\prod_i\\frac{1}{z_i^{\\text{max}} - z_i^{\\text{min}}} \\sqrt{(2\\pi)^{n}\\det\\Sigma}\n\\end{eqnarray}\nThe probability of the optimal fit is the chi squared factor, where the constants will cancel in the ratio:\n$$P\\left({D_{x,y}},\\vec{z}_0\\mid M\\right) \\propto \\exp{\\left(\\chi^2_M\\right)}$$\nSome of the widths will be constant for both models: the background, center coordinates, PSF width\nNow, enumerating all these terms:\n$n_S = 5$\n$n_B = 8$\n$\\Delta r = 256$ - might want a factor of $\\sqrt{2}$ but it's probably not important\n$\\Delta \\theta = \\pi$\n$\\Delta F = 300$ \nPutting this all together gives:\n$$\\frac{P(B \\mid {D_{x,y}})}{P(S \\mid {D_{x,y}})} = \\frac{(2\\pi)^{3/2}}{300\\cdot256\\cdot\\pi}\\sqrt{\\frac{\\det\\Sigma_B}{\\det\\Sigma_S}}\\exp\\left[-\\frac{1}{2}(\\chi_B^2-\\chi_S^2)\\right]$$", "F_max = 300 # DN\npix_width = len(x_arr[0])\nparam_diff = len(p_opt_bin) - len(p_opt_singl)\nchi_s_diff = cs_singl - cs_bin\ndet_pcov_bin = numpy.linalg.det(p_cov_bin)\ndet_pcov_singl = numpy.linalg.det(p_cov_singl)\n\nlikelihood_ratio = numpy.power(2*pi, param_diff/2) / (pi * F_max * pix_width) * numpy.sqrt(det_pcov_bin/det_pcov_singl) * numpy.exp(chi_s_diff/2)\nprint(likelihood_ratio)\nprint(chi_s_diff)\nprint(det_pcov_bin)\nprint(det_pcov_singl)", "<h3>Find the joint marginal distributions</h4>", "def joint_marginal_dist(param_vals, opt_param_vals, cov_mat):\n for obj in [param_vals, opt_param_vals, cov_mat]:\n if type(cov_mat) is not numpy.matrix:\n cov_mat = numpy.matrix(cov_mat)\n vec = numpy.matrix(param_vals - opt_param_vals)\n return 1/((2*numpy.pi)*numpy.sqrt(numpy.linalg.det(cov_mat)))*numpy.exp(-0.5*vec.T*cov_mat.I*vec)\n# mat1 * mat2 equivalent to numpy.dot(mat1, mat2)", "<h5>Fluxes</h5>", "F_points = 100\nF1_arr = numpy.linspace(p_opt_bin[0]-5*p_cov_bin[0][0], p_opt_bin[0]+5*p_cov_bin[0][0], F_points)\nF2_arr = numpy.linspace(p_opt_bin[1]-5*p_cov_bin[1][1], p_opt_bin[1]+5*p_cov_bin[1][1], F_points)\n\nF1_arr, F2_arr = numpy.meshgrid(F1_arr, F2_arr)\ncoords = F1_arr, F2_arr\n\nF1_rav = F1_arr.ravel()\nF2_rav = F2_arr.ravel()\n\n\nF0_matrix = numpy.matrix([[p_opt_bin[0]], [p_opt_bin[1]]])\nsigma_F = p_cov_bin[0:2,0:2] # gets the mini 2x2 subarray \nF_rav_len = len(F1_rav)\n\nif len(F1_rav) == F_points**2:\n fluxes_jm_prob_rav = numpy.zeros(F_rav_len)\n for i in range(0, F_rav_len):\n fluxes_jm_prob_rav[i] = joint_marginal_dist([[F1_rav[i]], [F2_rav[i]]], F0_matrix, sigma_F)\n\n\next = [F1_arr.min(), F1_arr.max(), F2_arr.min(), F2_arr.max()]\npyplot.imshow(fluxes_jm_prob_rav.reshape(F_points, F_points), origin='lower', extent=ext) \n# origin='lower' to make standard x and y indices \npyplot.title(\"Joint marginal dist for fluxes\")\npyplot.xlabel(\"F1\")\npyplot.ylabel(\"F2\")\npyplot.colorbar()\n\nl_points = 100\ntheta_arr = numpy.linspace(p_opt_bin[4]-5*p_cov_bin[4][4], p_opt_bin[4]+5*p_cov_bin[4][4], l_points)\nr_arr = numpy.linspace(p_opt_bin[5]-5*p_cov_bin[5][5], p_opt_bin[5]+5*p_cov_bin[5][5], l_points)\n\ntheta_arr, r_arr = numpy.meshgrid(theta_arr, r_arr)\n\ntheta_rav = theta_arr.ravel()\nr_rav = r_arr.ravel()\n\n\nrtheta_matrix = numpy.matrix([[p_opt_bin[4]], [p_opt_bin[5]]])\nsigma_rtheta = p_cov_bin[4:6,4:6] # gets the mini 2x2 subarray \ntheta_rav_len = len(theta_rav)\n\nif len(theta_rav) == l_points**2:\n rtheta_jm_prob_rav = numpy.zeros(theta_rav_len)\n for i in range(0, theta_rav_len):\n rtheta_jm_prob_rav[i] = joint_marginal_dist([[theta_rav[i]], [r_rav[i]]], rtheta_matrix, sigma_rtheta)\n\n\next = [theta_arr.min(), theta_arr.max(), r_arr.min(), r_arr.max()]\nprint(ext)\nfluxes_jm_prob = fluxes_jm_prob_rav.reshape(l_points, l_points)\npyplot.imshow(fluxes_jm_prob, origin='lower') # , extent=ext\n# origin='lower' to make standard x and y indices \npyplot.title(\"Joint marginal dist for angle and rad\")\npyplot.xlabel(\"theta\")\npyplot.ylabel(\"r\")\npyplot.colorbar()\n\n\nax = pyplot.subplot(111, polar=True)\nax.set_yticklabels([])\nctf = ax.contourf(theta_arr, r_arr, fluxes_jm_prob, cmap=cm.jet)\npyplot.colorbar(ctf)", "Gain stuff", "k = 3.0 # gain \nstar_data_pe = k * star_data\n", "Other: the binary fit was really poor when done in cartesian coords", "def binary_star_0(pos, F1, xc1, yc1, sigma1, F2, xc2, yc2, sigma2, B):\n return F1*numpy.exp(-((pos[0]-xc1)**2+(pos[1]-yc1)**2)/(2*sigma1**2)) + F2*numpy.exp(-((pos[0]-xc2)**2+(pos[1]-yc2)**2)/(2*sigma2**2)) + B\n \ninit_guess_0 = (11., 130, 130, 15, 25., 130, 130, 15, 100)\np_opt_bin_0, p_cov_bin_0 = optimize.curve_fit(binary_star_0, (x_rav, y_rav), star_rav, init_guess_0, sigma_rav)\n\nprint(p_opt_bin_0)\n\nfrom functools import partial\n#part_func = partial(symm_2d_gaussian, pos)\n\n# do it the simple way \nchi_s = numpy.sum(blank_sky**2/star_data)\ndof = len(x_rav) - len(p_opt_singl)\nprint(chi_s / dof)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
turbomanage/training-data-analyst
courses/machine_learning/deepdive/03_tensorflow/b_estimator.ipynb
apache-2.0
[ "<h1>2b. Machine Learning using tf.estimator </h1>\n\nIn this notebook, we will create a machine learning model using tf.estimator and evaluate its performance. The dataset is rather small (7700 samples), so we can do it all in-memory. We will also simply pass the raw data in as-is.", "import tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport shutil\n\nprint(tf.__version__)", "Read data created in the previous chapter.", "# In CSV, label is the first column, after the features, followed by the key\nCSV_COLUMNS = ['fare_amount', 'pickuplon','pickuplat','dropofflon','dropofflat','passengers', 'key']\nFEATURES = CSV_COLUMNS[1:len(CSV_COLUMNS) - 1]\nLABEL = CSV_COLUMNS[0]\n\ndf_train = pd.read_csv('./taxi-train.csv', header = None, names = CSV_COLUMNS)\ndf_valid = pd.read_csv('./taxi-valid.csv', header = None, names = CSV_COLUMNS)\ndf_test = pd.read_csv('./taxi-test.csv', header = None, names = CSV_COLUMNS)", "<h2> Train and eval input functions to read from Pandas Dataframe </h2>", "def make_train_input_fn(df, num_epochs):\n return tf.estimator.inputs.pandas_input_fn(\n x = df,\n y = df[LABEL],\n batch_size = 128,\n num_epochs = num_epochs,\n shuffle = True,\n queue_capacity = 1000\n )\n\ndef make_eval_input_fn(df):\n return tf.estimator.inputs.pandas_input_fn(\n x = df,\n y = df[LABEL],\n batch_size = 128,\n shuffle = False,\n queue_capacity = 1000\n )", "Our input function for predictions is the same except we don't provide a label", "def make_prediction_input_fn(df):\n return tf.estimator.inputs.pandas_input_fn(\n x = df,\n y = None,\n batch_size = 128,\n shuffle = False,\n queue_capacity = 1000\n )", "Create feature columns for estimator", "def make_feature_cols():\n input_columns = [tf.feature_column.numeric_column(k) for k in FEATURES]\n return input_columns", "<h3> Linear Regression with tf.Estimator framework </h3>", "tf.logging.set_verbosity(tf.logging.INFO)\n\nOUTDIR = 'taxi_trained'\nshutil.rmtree(OUTDIR, ignore_errors = True) # start fresh each time\n\nmodel = tf.estimator.LinearRegressor(\n feature_columns = make_feature_cols(), model_dir = OUTDIR)\n\nmodel.train(input_fn = make_train_input_fn(df_train, num_epochs = 10))", "Evaluate on the validation data (we should defer using the test data to after we have selected a final model).", "def print_rmse(model, df):\n metrics = model.evaluate(input_fn = make_eval_input_fn(df))\n print('RMSE on dataset = {}'.format(np.sqrt(metrics['average_loss'])))\nprint_rmse(model, df_valid)", "This is nowhere near our benchmark (RMSE of $6 or so on this data), but it serves to demonstrate what TensorFlow code looks like. Let's use this model for prediction.", "predictions = model.predict(input_fn = make_prediction_input_fn(df_test))\nfor items in predictions:\n print(items)", "This explains why the RMSE was so high -- the model essentially predicts the same amount for every trip. Would a more complex model help? Let's try using a deep neural network. The code to do this is quite straightforward as well.\n<h3> Deep Neural Network regression </h3>", "tf.logging.set_verbosity(tf.logging.INFO)\nshutil.rmtree(OUTDIR, ignore_errors = True) # start fresh each time\nmodel = tf.estimator.DNNRegressor(hidden_units = [32, 8, 2],\n feature_columns = make_feature_cols(), model_dir = OUTDIR)\nmodel.train(input_fn = make_train_input_fn(df_train, num_epochs = 100));\nprint_rmse(model, df_valid)", "We are not beating our benchmark with either model ... what's up? Well, we may be using TensorFlow for Machine Learning, but we are not yet using it well. That's what the rest of this course is about!\nBut, for the record, let's say we had to choose between the two models. We'd choose the one with the lower validation error. Finally, we'd measure the RMSE on the test data with this chosen model.\n<h2> Benchmark dataset </h2>\n\nLet's do this on the benchmark dataset.", "from google.cloud import bigquery\nimport numpy as np\nimport pandas as pd\n\ndef create_query(phase, EVERY_N):\n \"\"\"\n phase: 1 = train 2 = valid\n \"\"\"\n base_query = \"\"\"\nSELECT\n (tolls_amount + fare_amount) AS fare_amount,\n EXTRACT(DAYOFWEEK FROM pickup_datetime) * 1.0 AS dayofweek,\n EXTRACT(HOUR FROM pickup_datetime) * 1.0 AS hourofday,\n pickup_longitude AS pickuplon,\n pickup_latitude AS pickuplat,\n dropoff_longitude AS dropofflon,\n dropoff_latitude AS dropofflat,\n passenger_count*1.0 AS passengers,\n CONCAT(CAST(pickup_datetime AS STRING), CAST(pickup_longitude AS STRING), CAST(pickup_latitude AS STRING), CAST(dropoff_latitude AS STRING), CAST(dropoff_longitude AS STRING)) AS key\nFROM\n `nyc-tlc.yellow.trips`\nWHERE\n trip_distance > 0\n AND fare_amount >= 2.5\n AND pickup_longitude > -78\n AND pickup_longitude < -70\n AND dropoff_longitude > -78\n AND dropoff_longitude < -70\n AND pickup_latitude > 37\n AND pickup_latitude < 45\n AND dropoff_latitude > 37\n AND dropoff_latitude < 45\n AND passenger_count > 0\n \"\"\"\n\n if EVERY_N == None:\n if phase < 2:\n # Training\n query = \"{0} AND ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 4)) < 2\".format(base_query)\n else:\n # Validation\n query = \"{0} AND ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 4)) = {1}\".format(base_query, phase)\n else:\n query = \"{0} AND ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), {1})) = {2}\".format(base_query, EVERY_N, phase)\n \n return query\n\nquery = create_query(2, 100000)\ndf = bigquery.Client().query(query).to_dataframe()\n\nprint_rmse(model, df)", "RMSE on benchmark dataset is <b>9.41</b> (your results will vary because of random seeds).\nThis is not only way more than our original benchmark of 6.00, but it doesn't even beat our distance-based rule's RMSE of 8.02.\nFear not -- you have learned how to write a TensorFlow model, but not to do all the things that you will have to do to your ML model performant. We will do this in the next chapters. In this chapter though, we will get our TensorFlow model ready for these improvements.\nIn a software sense, the rest of the labs in this chapter will be about refactoring the code so that we can improve it.\nChallenge Exercise\nCreate a neural network that is capable of finding the volume of a cylinder given the radius of its base (r) and its height (h). Assume that the radius and height of the cylinder are both in the range 0.5 to 2.0. Simulate the necessary training dataset.\n<p>\nHint (highlight to see):\n<p style='color:white'>\nThe input features will be r and h and the label will be $\\pi r^2 h$\nCreate random values for r and h and compute V.\nYour dataset will consist of r, h and V.\nThen, use a DNN regressor.\nMake sure to generate enough data.\n</p>\n\nCopyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
GoogleCloudPlatform/asl-ml-immersion
notebooks/ml_fairness_explainability/inclusive_ml/solution/1_inclusive_ml.ipynb
apache-2.0
[ "Inclusive ML - Understanding Bias\nLearning Objectives\n\nInvoke the What-if Tool against a deployed Model\nExplore attributes of the dataset\nExamine aspects of bias in model results\nEvaluate how the What-if Tool provides suggestions to remediate bias\n\nIntroduction\nThis notebook shows use of the What-If Tool inside of a Jupyter notebook. The What-If Tool, among many other things, allows you to explore the impacts of Fairness in model design and deployment.\nThe notebook invokes a previously deployed XGBoost classifier model on the UCI census dataset which predicts whether a person earns more than $50K based on their census information.\nYou will then visualize the results of the trained classifier on test data using the What-If Tool. \nFirst, you will import various libaries and settings that are required to complete the lab.", "!pip freeze | grep httplib2==0.18.1 || pip install httplib2==0.18.1\n\nimport os\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\nimport numpy as np\nimport pandas as pd\nimport witwidget\nfrom witwidget.notebook.visualization import WitConfigBuilder, WitWidget\n\npd.options.display.max_columns = 50\n\nPROJECT = !(gcloud config list --format=\"value(core.project)\")\nPROJECT = PROJECT[0]\n\nBUCKET = f\"gs://{PROJECT}\"\nMODEL = \"xgboost_model\"\nVERSION = \"v1\"\nMODEL_DIR = os.path.join(BUCKET, MODEL)\n\n\nos.environ[\"PROJECT\"] = PROJECT\nos.environ[\"BUCKET\"] = BUCKET\nos.environ[\"MODEL\"] = MODEL\nos.environ[\"VERSION\"] = VERSION\nos.environ[\"MODEL_DIR\"] = MODEL_DIR", "Set up the notebook environment\nFirst you must perform a few environment and project configuration steps. \nThese steps may take 8 to 10 minutes, please wait until you see the following response before proceeding:\n\"Creating version (this might take a few minutes)......done.\"", "%%bash\n\ngcloud config set project $PROJECT\n\ngsutil mb $BUCKET\ngsutil cp gs://cloud-training-demos/mlfairness/model.bst $MODEL_DIR/model.bst\n\ngcloud ai-platform models list | grep $MODEL || gcloud ai-platform models create $MODEL --region=global\n\ngcloud ai-platform versions list --model $MODEL | grep $VERSION ||\ngcloud ai-platform versions create $VERSION \\\n --model=$MODEL \\\n --framework='XGBOOST' \\\n --runtime-version=1.14 \\\n --origin=$MODEL_DIR \\\n --python-version=3.5 \\\n --project=$PROJECT \\\n --region=global", "Finally, download the data and arrays needed to use the What-if Tool.", "%%bash\n\ngsutil cp gs://cloud-training-demos/mlfairness/income.pkl .\ngsutil cp gs://cloud-training-demos/mlfairness/x_test.npy .\ngsutil cp gs://cloud-training-demos/mlfairness/y_test.npy . \n\nfeatures = pd.read_pickle(\"income.pkl\")\nx_test = np.load(\"x_test.npy\")\ny_test = np.load(\"y_test.npy\")", "Now take a quick look at the data. The ML model type used for this analysis is XGBoost. XGBoost is a machine learning framework that uses decision trees and gradient boosting to build predictive models. It works by ensembling multiple decision trees together based on the score associated with different leaf nodes in a tree. \nXGBoost requires all values to be numeric so the orginial dataset was slightly modified. The biggest change made was to assign a numeric value to Sex. The originial dataset only had the values \"Female\" and \"Male\" for Sex. The decision was made to assign the value \"1\" to Female and \"2\" to Male. As part of the data prepartion effort the Pandas function \"get_dummies\" was used to convert the remaining domain values into numerical equivalent. For instance the \"Education\" column was turned into several sub-columns named after the value in the column. For instance the \"Education_HS-grad\" has a value of \"1\" for when that was the orginial categorical value and a value of \"0\" for other cateogries.", "features.head()", "To connect the What-if Tool to an AI Platform model, you need to pass it a subset of your test examples. The command below will create a Numpy array of 2000 from our test examples.", "# Combine the features and labels into one array for the What-if Tool\n\nnum_wit_examples = 2000\n\ntest_examples = np.hstack(\n (x_test[:num_wit_examples], y_test[:num_wit_examples].reshape(-1, 1))\n)", "Instantiating the What-if Tool is as simple as creating a WitConfigBuilder object and passing it the AI Platform model desired to be analyzed.\nThe optional \"adjust_prediction\" parameter is used because the What-if Tool expects a list of scores for each class in our model (in this case 2). Since the model only returns a single value from 0 to 1, it must be transformed to the correct format in this function. Lastly, the name 'income_prediction' is used as the ground truth label.\nIt may take 1 to 2 minutes for the What-if Tool to load and render the visualization palette, please be patient.", "# TODO 1\nFEATURE_NAMES = features.columns.tolist() + [\"income_prediction\"]\n\n\ndef adjust(pred):\n return [1 - pred, pred]\n\n\nconfig_builder = (\n WitConfigBuilder(test_examples.tolist(), FEATURE_NAMES)\n .set_ai_platform_model(\n PROJECT, MODEL, VERSION, service_name=\"ml\", adjust_prediction=adjust\n )\n .set_target_feature(\"income_prediction\")\n .set_label_vocab([\"low\", \"high\"])\n)\n\nWitWidget(config_builder, height=800)", "In the following steps we will use the What-if Tool to examine our model\nSince the What-If Tool is embedded in the notebook you must use care when scrolling. The What-if Tool has its own internal scrolling windows so you may need to reposition the frame window to reach the desired location. To do this you must ensure you are at the far edges of the cell to scroll up and down as noted by the red oblong markers in the image below.\nAlso, it might be helpful to widen the display frame in the notebook. You can do this by dragging the vertical grey bar to the left (the place to click and hold is noted by the red arrows).\n\nThe scenario for consideration is that this model, which is used to predict income levels, will be used in a loan approval process. Your task is to determine its fitness for such a use case from a fairness perspective.\nTODO 2: Your first action will be to examine data and its disribution along dimensions that are relevant to loan scoring. The intial presentation in the tool shows all datapoints. Blue dots are those individuals predicted as having incomes above 50k. Red dots are those predicted as having incomes below 50k.\nOn the \"Datapoint Editor\" tab, under \"Binning | X-Axis\" select \"Education_Masters\":\n\nThe results show that a majority of Masters degree holders, domain value \"1\" (in red above the visualization), have incomes above 50k.\n\nReturn to the \"Binning | X-Axis\" selector and choose \"None\" to reset the visualization.\nTODO 2: Next navigate to the Features tab, here you can see the exact distribution of values for every feature in the dataset. If you type \"sex\" into the filter box, you will see that of the 2,000 test datapoints, 670 from Women and 1,330 are from Men (as mentioned earlier the value \"1\" was assigned to Females and \"2\" was assigned to Males). The dataset reflects an imbalance between Females and Males with nearly double the number of cases that are Male. Women seem under-represented in this dataset.\n\nTODO 3: On the \"Performance + Fairness\" tab, you can set an input feature (or set of features) by which to slice the data. This will allow you to evaluate the fairness of specific groups. Income Prediction (corresponding to over or under 50k) has already been selected as the \"Ground Truth Feature\". On the \"Slice by\" selector, scroll to find and choose \"Sex\".\n\nThis selection allows you to see the breakdown of model performance on female datapoints versus male datapoints. Even before you drill into the details you can see that the model has a lower F1 score for females than males. Drilling down on each value (by clicking the arrow beside the domain value) you see that the model predicts high income for females much less than it does for males: 3.4% of the time for females vs 18.9% of the time for males.\n\n\nIn the use-case scenario, the plan is to use this simple income classifier to approve or reject loan applications (not a realistic example but it illustrates the effect of bias in ML usage). In this case, 18.9% of men from the test dataset have their loans approved but only 3.4% of women have their loans approved. If you wanted to ensure than men and women get their loans approved the same percentage of the time, that is a fairness concept called \"demographic parity\". An XGBoost model intially defaults to a 0.50 threshold, which is what appears upon initial examination. One way to achieve demographic parity would be to have different classification thresholds for females and males in our model. You'll notice there is a button on the tool labeled \"demographic parity\". When you press this button, the tool will take the cost ratio into account, and come up with ideal separate thresholds for men and women that will achieve demographic parity over the test dataset.\nTODO 4: On the \"Performance + Fairness\" tab, select \"Demographic Parity\" to see the results.\n\nBy drilling down on each domain value you can see the automatic adjustments. In this case, demographic parity can be found with both groups getting loans approved/predicting a high income ~17.7% of the time. This occurs when the female threshold is set to 0.19 and the male threshold is set to 0.54. Because of the vast difference in the properties of the female and male training data in this 1994 census dataset, you need quite different thresholds to achieve demographic parity. With the high male threshold you may notice there are many more false negatives than before, and with the low female threshold there are many more false positives than before. To reset the Peformance and Fairness Tab simply choose another domain value in the \"Slice by\" selector.\n\n\nThe use of these features can help shed light on subsets of your data on which your classifier is performing very differently. Understanding biases in your datasets and data slices on which your model has disparate performance are very important parts of analyzing a model for fairness. There are many approaches to improving fairness, including augmenting training data, building fairness-related loss functions into your model training procedure, and post-training inference adjustments like those seen in WIT. The WIT provides a great interface for furthering ML fairness learning, but of course there is no silver bullet to improving ML fairness.\nFeel free to explore the What-if Tool and find additional insights.\n<br>\n<br>\n<br>\n<br>\nCopyright 2018 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
joostgp/kaggle_bosch
pre_path_per_sample.ipynb
apache-2.0
[ "import os\nimport re\nimport pickle\nimport time\nimport datetime\n\nimport numpy as np\nimport pandas as pd\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom scipy.sparse import csr_matrix, vstack\n\n%matplotlib inline\n\n# Custom modules\nimport const\nimport func", "Load lookup table & data", "const.TRAIN_FILES\n\nconst.TEST_FILES", "Load data", "num_data = func.load_data_file(const.TRAIN_FILES[0], ftype='bin')\ncat_data = func.load_data_file(const.TRAIN_FILES[1], ftype='bin')\nnum_data_te = func.load_data_file(const.TEST_FILES[0], ftype='bin')\ncat_data_te = func.load_data_file(const.TEST_FILES[1], ftype='bin')\n\ny = num_data['data']['y']\nids = np.concatenate([num_data['data']['ids'].Id.values, num_data_te['data']['ids'].Id.values])\n\nnum_f_n = num_data['data']['feature_names'][1:]\ncat_f_n = cat_data['data']['feature_names'][1:]\n\nnum_data = vstack([num_data['data']['features'], num_data_te['data']['features']], format='csr')\ncat_data = vstack([cat_data['data']['features'], cat_data_te['data']['features']], format='csr')\n\nnum_data.shape\n\ndel num_data_te, cat_data_te", "Load and adjust lookup table", "lut = pd.read_csv(os.path.join(const.DATA_PATH, 'date_feat_lut_V2.csv'))\nlut.head()\n\ndef insert_col_num(x):\n ''' Adds columns number to lookup table'''\n try:\n num_col_n = num_f_n.index(x['name_num'])\n x['col_num'] = num_col_n\n \n except:\n x['col_num'] = np.nan\n \n try:\n cat_col_n = cat_f_n.index(x['name_cat'])\n x['col_cat'] = cat_col_n\n \n except:\n x['col_cat'] = np.nan\n \n return x\n\nlut = lut.apply(lambda x: insert_col_num(x), axis=1)\n\n# Create lookup table for the numeric matrix so we can easily go from feature nr to column no\nlut_num_indices = lut.groupby(['line','station_V2']).col_num.agg(['min','max'])\nlut_num_indices.head()\n\n# Create lookup table for the numeric matrix so we can easily go from feature nr to column no\n\nlut_cat_indices = lut.groupby(['line','station_V2']).col_cat.agg(['min','max'])\nlut_cat_indices.head()\n\nprint lut_num_indices.shape\nprint lut_cat_indices.shape\n\nn_stations = lut.station_V2.nunique()\nn_features = lut.feature_nr.nunique()\nn_samples = num_data.shape[0]\nprint('Number of stations: {}'.format(n_stations))\nprint('Number of features: {}'.format(n_features))\nprint('Number of samples: {}'.format(n_samples))", "Create paths per station\nWe assume that when a sample has a measurement value for one of the features of the station, it has passed this station. We also assume that samples always pass the stations in order.\nTo calculate this matrix we need to sum over all the features per station. Most efficient way to do this is by matrix multiplication:\nA B C\n[0 1 1] [1 0] = [1 1] -> '>0' -> [1 1]\n[0 0 1] x [1 0] [0 1] [0 1]\n[1 1 0] [0 1] [2 1] [1 1]\nWe have to do this for the numeric and categorical features and concate them later.", "# Create matrix B for numeric features\nstation_filter_num = np.zeros((lut_num_indices.shape[0], num_data.shape[1]))\nfor i in range(lut_num_indices.shape[0]):\n if lut_num_indices.iloc[i]['min']>=0:\n i_s = int(lut_num_indices.iloc[i]['min'])\n i_e = int(lut_num_indices.iloc[i]['max']+1)\n #print i_s, i_e\n station_filter_num[i, i_s:i_e] = 1\nstation_filter_num = csr_matrix(station_filter_num)\n\n# Create matrix C for numeric features\nnum_per_station = (num_data * station_filter_num.T)>0\n\n# Create matrix B for categorical features\n\nstation_filter_cat = np.zeros((lut_cat_indices.shape[0], cat_data.shape[1]))\nfor i in range(lut_cat_indices.shape[0]):\n if lut_cat_indices.iloc[i]['min']>=0:\n i_s = int(lut_cat_indices.iloc[i]['min'])\n i_e = int(lut_cat_indices.iloc[i]['max']+1)\n #print i_s, i_e\n station_filter_cat[i, i_s:i_e] = 1\nstation_filter_cat = csr_matrix(station_filter_cat)\n\n# Create matrix C for categorical features\ncat_per_station = (cat_data * station_filter_cat.T)>0\n\n# Double check dimensions\nprint num_per_station.shape\nprint cat_per_station.shape\n\n# Now get a array of station nr visited for each\na=time.time()\nstations_passed = []\nfor i in range(num_data.shape[0]):\n if not i % 100000:\n print('Calculated stations for {} of {}'.format(i+1, num_data.shape[0]))\n \n stations_passed.append(np.unique(np.concatenate([num_per_station[i,:].nonzero()[1], cat_per_station[i,:].nonzero()[1]], axis=0)))\n \n # Below is ~10% slower\n #stations_passed.append(np.asarray(set(num_data[i,:].nonzero()[1]) & set(cat_data[i,:].nonzero()[1])))\nprint time.time()-a\n\n# Method used to convert list of stations visited to either a string '01111000' or array [0,1,0,1,0,0] or both\ndef to_path_info_per_item(items_visited, n_items, o_type='string'):\n tmp = np.zeros((n_items)).astype(int)\n \n for n in items_visited: tmp[n]=1\n \n if o_type=='string':\n return ''.join(map(str,tmp))\n elif o_type=='array':\n return tmp\n elif o_type=='both':\n return ''.join(map(str,tmp)), tmp\n\n# Convert list of stations to binary vectors\nps_strings = []\nps_arr = []\nfor i in range(n_samples):\n if not i % 100000:\n print('Converted {} of {}'.format(i+1, n_samples))\n s_s, s_arr = to_path_info_per_item(stations_passed[i], n_stations, o_type='both')\n ps_strings.append(s_s)\n ps_arr.append(s_arr)\n\n# Now finally get the unique values based on the strings\nu_str, u_ix, i_ix = np.unique(ps_strings, return_index=True, return_inverse=True)\nu_arr = np.array([ps_arr[n] for n in u_ix])\n\nprint('Number of unique paths: {}'.format(u_arr.shape[0]))\n\n# Store the sample_id with unique path id\npd.DataFrame({'id': ids, 'u_arr_ix': i_ix}).to_csv(os.path.join(const.DATA_PATH, 'eda_product_flow_sample_paths_station.csv'), \n index=False)\n# Store the unique strings with id\npd.DataFrame({'id': range(u_arr.shape[0]), 'u_str': u_str}).to_csv(os.path.join(const.DATA_PATH, 'eda_product_flow_unique_paths_station.csv'), \n index=False)\n\ndef distance_matrix(bin_arr_list, verbose=False):\n\n tmp = np.empty((bin_arr_list.shape[0], bin_arr_list.shape[0]))\n tmp[:] = np.nan\n \n for i in range(bin_arr_list.shape[0]):\n if (not i % 1000) & verbose:\n print('{}/{}'.format(i+1,bin_arr_list.shape[0]))\n \n for j in range(bin_arr_list.shape[0]):\n #if j>i:\n ##a = np.array([int(n) for n in list(unique_string[i])])\n #b = np.array([int(n) for n in list(unique_string[j])])\n tmp[i,j] = np.count_nonzero( bin_arr_list[i]!=bin_arr_list[j] )\n return tmp\n\ntmp = distance_matrix(u_arr, True)\n\nfrom sklearn.cluster import KMeans\n\nn_cluster=7\nkm = KMeans(n_clusters=n_cluster)\ntmp\n\n%time km.fit(u_arr)\n\nclusters = km.labels_.tolist()\n\nlen(clusters)\n\nfrom sklearn import decomposition\n\nns=7600\nne=ns+20\nprint clusters[ns:ne]\n[np.count_nonzero( u_arr[i]!=u_arr[i+1]) for i in range(ns, ne)]\n\nu_arr\n\nu_arr[1]\n\nfor n_clus in range(n_cluster):\n u_clus = np.array([u_arr[i] for i,n in enumerate(clusters) if n==n_clus])\n tmp2 = distance_matrix(u_clus)\n print('Mean of matrix: {}'.format(np.nanmean(tmp2)))\n print('Max of matrix: {}'.format(np.nanmax(tmp2)))\n\nn_clus=3\n\nnn_clus = np.array([n for i,n in enumerate(clusters) if n==n_clus])\n\ntitles = [str(i) for i in range(tmp.shape[0])]\n\n#set up colors per clusters using a dict\ncluster_colors = {0: '#1b9e77', 1: '#d95f02', 2: '#7570b3', 3: '#e7298a',4: '#8d03d1', 5:'#2b09db', 6:'#466eb8'}\n\n#set up cluster names using a dict\ncluster_names = {0: '1', \n 1: '2', \n 2: '3', \n 3: '4', \n 4: '5', \n 5: '6', \n 6: '7'}\n\ndf = pd.DataFrame(dict(x=xs, y=ys, label=clusters, title=titles)) \n\n#group by cluster\ngroups = df.groupby('label')\n\n\n# set up plot\nfig, ax = plt.subplots(figsize=(17, 9)) # set size\nax.margins(0.05) # Optional, just adds 5% padding to the autoscaling\n\n#iterate through groups to layer the plot\n#note that I use the cluster_name and cluster_color dicts with the 'name' lookup to return the appropriate color/label\nfor name, group in groups:\n ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, \n label=cluster_names[name], color=cluster_colors[name], \n mec='none')\n ax.set_aspect('auto')\n ax.tick_params(\\\n axis= 'x', # changes apply to the x-axis\n which='both', # both major and minor ticks are affected\n bottom='off', # ticks along the bottom edge are off\n top='off', # ticks along the top edge are off\n labelbottom='off')\n ax.tick_params(\\\n axis= 'y', # changes apply to the y-axis\n which='both', # both major and minor ticks are affected\n left='off', # ticks along the bottom edge are off\n top='off', # ticks along the top edge are off\n labelleft='off')\n \nax.legend(numpoints=1) #show legend with only 1 point\n\n#add label in x,y position with the label as the film title\nfor i in range(len(df)):\n ax.text(df.ix[i]['x'], df.ix[i]['y'], df.ix[i]['title'], size=8) \n\n \n \nplt.show() #show the plot\n\n\npd.DataFrame({'string':station_strings}).to_csv(os.path.join(const.DATA_PATH,'path_string_per_station.csv'), index_label='Id')\n\nstations = []\nfor i in range(num_per_station.shape[0]):\n if not i % 100000:\n print('Hashed {} of {}'.format(i+1, num_per_station.shape[0]))\n stations.append((np.unique(np.concatenate([num_per_station[i,:].nonzero()[1], cat_per_station[i,:].nonzero()[1]], axis=0))))\n\npd.DataFrame({'string':ustring}).to_csv(os.path.join(const.DATA_PATH,'path_unique_string_per_station.csv'), index_label='Id')\n\nhashes = []\nfor i in range(num_per_station.shape[0]):\n if not i % 10000:\n print('Hashed {} of {}'.format(i+1, num_per_station.shape[0]))\n hashes.append(hash(str(np.concatenate([num_per_station[i,:].nonzero()[1], cat_per_station[i,:].nonzero()[1]], axis=0))))\n\nlut.feature_nr.max()\n\npd.Series(hashes).nunique()\n\npd.Series(hashes).value_counts().head()\n\nhash_vals = pd.Series(hashes).value_counts()\n\nhash_vals.hist(range=[0,100])\n\n(hash_vals<10).sum()", "Create hashes based on non-zero values of num and cat data per station\nCreate hashes based on non-zero values of num and cat data per feature\nThis results in 24775 different hashes. Most common hashes are:\n\n-7807953387334174150: 8602\n4448795901197187659: 8570\n-4556810841609180581: 8374\n6868875294474782730: 8272\n4906655664106956524: 6679\n\nof those, 12157 have a single sample\nof those, 20205 have less than 10 samples", "def to_path_info_per_feature(features_visited, n_features, o_type='string'):\n tmp = np.zeros((n_features)).astype(int)\n \n for n in features_visited: tmp[n]=1\n \n if o_type=='string':\n return ''.join(map(str,tmp))\n elif o_type=='array':\n return tmp\n elif o_type=='both':\n return ''.join(map(str,tmp)), tmp\n\n# Generate a list of all the features products have values for\nfeatures_visited = []\nfor i in range(n_samples):\n if not i % 100000:\n print('Calculated {} of {}'.format(i+1, n_samples))\n #stations_visited.append(hash(str(np.concatenate([num_data[i,:].nonzero()[1], cat_data[i,:].nonzero()[1]], axis=0).data)))\n features_visited.append(np.unique(np.concatenate([num_data[i,:].nonzero()[1], cat_data[i,:].nonzero()[1]], axis=0)))\n\n# Covert to list of stations to binary vectors\nstation_strings = []\nstation_arr = []\nfor i in range(n_samples):\n if not i % 100000:\n print('Hashed {} of {}'.format(i+1, n_samples))\n s_s, s_arr = to_path_info_per_feature(features_visited[i], n_features, o_type='both')\n station_strings.append(s_s)\n station_arr.append(s_arr)\n\n# Now finally get the unique values based on the strings\nu_str, u_ix, i_ix = np.unique(station_strings, return_index=True, return_inverse=True)\nu_arr = np.array([station_arr[n] for n in u_ix])\n\nprint('Number of unique paths: {}'.format(u_arr.shape[0]))\n\n# Store the sample_id with unique path id\npd.DataFrame({'id': ids, 'u_arr_ix': i_ix}).to_csv(os.path.join(const.DATA_PATH, 'eda_product_flow_sample_paths_per_feature.csv'), \n index=False)\n# Store the unique strings with id\npd.DataFrame({'id': range(u_arr.shape[0]), 'u_str': u_str}).to_csv(os.path.join(const.DATA_PATH, 'eda_product_flow_unique_paths_per_feature.csv'), \n index=False)" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
marburg-open-courseware/gmoc
docs/mpg-if_error_continue/examples/e-03-1_quicksort.ipynb
mit
[ "Sorting\n<hr>\n\nThe following examples show two implementations of a quicksort algorithm, one using the Lomot, one using the Horade partitioning approach, and one example for merge sort.", "n = 5\ne = 1\nfor i in range(1, n+1):\n e = e * i\n#e\n\ndef fac(n):\n if n <= 1:\n return n\n return(n * fac(n-1))\n \nd = fac(5)\nprint(d)", "Quicksort with partition algorithm of Lomoto\nExample following pseudocode taken from Wikipedia", "def partitionLomoto(my_list, low, high):\n pivot = my_list[high]\n print(\"Actual pivot\", pivot)\n print(\"Actual list before partitioning\", my_list[low:high+1])\n i = low\n for j in range(low, high):\n if my_list[j] <= pivot:\n my_list[i], my_list[j] = my_list[j], my_list[i]\n i = i+1\n my_list[i], my_list[high] = my_list[high], my_list[i]\n pivot = i\n print(\"Actual list after partitioning\", my_list[low:high+1])\n print(\"New pivot position: \", pivot)\n print(\"------------------\")\n return pivot\n\ndef quickSortLomoto(my_list, low, high):\n if low < high:\n pivot = partitionLomoto(my_list, low, high)\n quickSortLomoto(my_list, low, pivot-1)\n quickSortLomoto(my_list, pivot+1, high)\n return my_list\n\nmy_unsorted_list = [21,11,31,9,8,19,1]\nmy_list = my_unsorted_list\nquickSortLomoto(my_unsorted_list, 0, len(my_unsorted_list)-1)", "Quicksort with partition algorithm of Hoare\nExample following pseudocode taken from Wikipedia", "def partitionHoare(my_list, low, high):\n pivot = my_list[low]\n print(\"Actual pivot\", pivot)\n print(\"Actual list before partitioning\", my_list[low:high])\n i = low\n j = high\n \n while True:\n while my_list[i] < pivot:\n i = i + 1\n print(i)\n while my_list[j] > pivot:\n j = j - 1\n print(j)\n if i >= j:\n print(\"Actual list after partitioning\", my_list[low:high])\n print(\"New pivot position: \", pivot)\n print(\"------------------\")\n return j\n else:\n my_list[i], my_list[j] = my_list[j], my_list[i]\n return pivot\n\ndef quickSortHoare(my_list, low, high):\n if low < high:\n pivot = partitionHoare(my_list, low, high)\n quickSortHoare(my_list, low, pivot)\n quickSortHoare(my_list, pivot+1, high)\n return my_list\n\nmy_unsorted_list = [21,11,31,9, 25, 8,19,1]\nmy_list = my_unsorted_list\nquickSortHoare(my_unsorted_list, 0, len(my_unsorted_list)-1)", "Merge sort\nExample following pseudocode taken from Wikipedia", "def mergeSort(my_list):\n if len(my_list) <= 1:\n return my_list\n\n half = len(my_list)//2\n left_list = my_list[:half]\n right_list = my_list[half:]\n print(\"Left list :\", left_list, \"Right list :\", right_list)\n\n left_list = mergeSort(left_list)\n right_list = mergeSort(right_list)\n \n return merge(left_list, right_list)\n\ndef merge(left_list, right_list):\n print(\"Merging...\")\n result = []\n while len(left_list) > 0 and len(right_list) > 0:\n if left_list[0] < right_list[0]:\n print(\"Left :\", left_list[0], \"Right :\", right_list[0])\n result.append(left_list.pop(0))\n print(\"Result :\", result)\n else:\n print(\"Left :\", left_list[0], \"Right :\", right_list[0])\n result.append(right_list.pop(0))\n print(\"Result :\", result)\n while len(left_list) > 0:\n print(\"Left :\", left_list[0])\n result.append(left_list.pop(0))\n print(\"Result :\", result)\n while len(right_list) > 0:\n print(\"Right :\", right_list[0])\n result.append(right_list.pop(0))\n print(\"Result :\", result)\n print(\"------------------\")\n return result\n\nalist = [54,26,93,17,77,31,44,55,20]\nsort = mergeSort(alist)\nprint(sort)\n" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
ddandur/Twords
jupyter_example_notebooks/Trump Tweets Example.ipynb
mit
[ "Collect all tweets from @realDonaldTrump", "import sys\nsys.path.append('..')\n\nfrom twords.twords import Twords \nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport pandas as pd\n# this pandas line makes the dataframe display all text in a line; useful for seeing entire tweets\npd.set_option('display.max_colwidth', -1)\n\ntwit = Twords()\n# set path to folder that contains jar files for twitter search\ntwit.jar_folder_path = \"../jar_files_and_background/\"\n\ntwit.get_all_user_tweets(\"realdonaldtrump\", tweets_per_run=500)\n\ntwit.data_path = \"realdonaldtrump\"\ntwit.get_java_tweets_from_csv_list()\ntwit.convert_tweet_dates_to_standard()", "To sort tweets by favorites or retweets, need to convert unicode to integers:", "twit.tweets_df[\"retweets\"] = twit.tweets_df[\"retweets\"].map(int)\ntwit.tweets_df[\"favorites\"] = twit.tweets_df[\"favorites\"].map(int)\n\ntwit.tweets_df.sort_values(\"favorites\", ascending=False)[:5]\n\ntwit.tweets_df.sort_values(\"retweets\", ascending=False)[:5]", "For some reason the search did not include Trump's username - random errors like this sometimes happen when querying the twitter website.\nLook at word frequencies", "twit.background_path = '../jar_files_and_background/freq_table_72319443_total_words_twitter_corpus.csv'\ntwit.create_Background_dict()\ntwit.create_Stop_words()\n\ntwit.keep_column_of_original_tweets()\ntwit.lower_tweets()\ntwit.keep_only_unicode_tweet_text()\ntwit.remove_urls_from_tweets()\ntwit.remove_punctuation_from_tweets()\ntwit.drop_non_ascii_characters_from_tweets()\ntwit.drop_duplicate_tweets()\ntwit.convert_tweet_dates_to_standard()\ntwit.sort_tweets_by_date()", "Make word frequency dataframe:", "twit.create_word_bag()\ntwit.make_nltk_object_from_word_bag()\ntwit.create_word_freq_df(10000)\n\ntwit.word_freq_df.sort_values(\"log relative frequency\", ascending = False, inplace = True)\ntwit.word_freq_df.head(20)", "Look at most and least Trump-like tweets at varying levels of background requirement\nAt least 100 background occurrences:", "num_words_to_plot = 32\nbackground_cutoff = 100\ntwit.word_freq_df[twit.word_freq_df['background occurrences']>background_cutoff].sort_values(\"log relative frequency\", ascending=True).set_index(\"word\")[\"log relative frequency\"][-num_words_to_plot:].plot.barh(figsize=(20,\n num_words_to_plot/2.), fontsize=30, color=\"c\"); \nplt.title(\"log relative frequency\", fontsize=30); \nax = plt.axes(); \nax.xaxis.grid(linewidth=4);", "At least 1000 background occurrences:", "num_words_to_plot = 32\nbackground_cutoff = 1000\ntwit.word_freq_df[twit.word_freq_df['background occurrences']>background_cutoff].sort_values(\"log relative frequency\", ascending=True).set_index(\"word\")[\"log relative frequency\"][-num_words_to_plot:].plot.barh(figsize=(20,\n num_words_to_plot/2.), fontsize=30, color=\"c\"); \nplt.title(\"log relative frequency\", fontsize=30); \nax = plt.axes(); \nax.xaxis.grid(linewidth=4);", "At least 10,000 background occurrences:", "num_words_to_plot = 32\nbackground_cutoff = 10000\ntwit.word_freq_df[twit.word_freq_df['background occurrences']>background_cutoff].sort_values(\"log relative frequency\", ascending=True).set_index(\"word\")[\"log relative frequency\"][-num_words_to_plot:].plot.barh(figsize=(20,\n num_words_to_plot/2.), fontsize=30, color=\"c\"); \nplt.title(\"log relative frequency\", fontsize=30); \nax = plt.axes(); \nax.xaxis.grid(linewidth=4);", "And now look at least Trump-like relative to Twitter background:", "num_words_to_plot = 32\nbackground_cutoff = 10000\ntwit.word_freq_df[twit.word_freq_df['background occurrences']>background_cutoff].sort_values(\"log relative frequency\", ascending=False).set_index(\"word\")[\"log relative frequency\"][-num_words_to_plot:].plot.barh(figsize=(20,\n num_words_to_plot/2.), fontsize=30, color=\"c\"); \nplt.title(\"log relative frequency\", fontsize=30); \nax = plt.axes(); \nax.xaxis.grid(linewidth=4);", "Trump does not post about things happening automatically.", "twit.tweets_containing(\"fuck\")" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
nvenayak/impact
docs/source/features_0.ipynb
gpl-3.0
[ "Analyzing Features\nRates", "import impact as impt\nimport cobra\nimport cobra.test\nimport cobra.io\nimport numpy as np\n\n# import matplotlib.pyplot as plt\n% matplotlib inline\n\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nfrom plotly.graph_objs import Bar, Layout, Figure, Scatter\ninit_notebook_mode()\n\n# We include this to ensure the js is loaded when viewed online\n# from IPython.display import HTML\n# HTML('<script src=\"https://cdn.plot.ly/plotly-latest.min.js\"></script>')\n\nimport impact.plotting as implot\n\n# Let's grab the iJO1366 E. coli model, cobra's test module has a copy\nmodel = cobra.test.create_test_model(\"ecoli\")\n\n# Simulate anaerobic conditions by prevent oxygen uptake\nmodel.reactions.get_by_id('EX_o2_e').knock_out() \n\n# Optimize the model\nsol = model.optimize()\nmodel.summary()\n\n# Let's consider one substrate and five products\nbiomass_keys = ['Ec_biomass_iJO1366_core_53p95M']\nsubstrate_keys = ['EX_glc_e']\nproduct_keys = ['EX_for_e','EX_ac_e','EX_etoh_e','EX_succ_e']\nanalyte_keys = biomass_keys+substrate_keys+product_keys\n\n# The initial conditions (mM) [biomass, substrate, \n# product1, product2, ..., product_n]\ny0 = [0.05, 100, 0, 0, 0, 0]\nt = np.linspace(0,16,8)\n\n# Returns a dictionary of the profiles\nfrom impact.helpers.synthetic_data import generate_data\ndFBA_profiles = generate_data(y0, t, model, \n biomass_keys, substrate_keys, \n product_keys, plot = False)\n\nimplot.plot([implot.go.Scatter(x=t,y=dFBA_profiles[exchange],name=exchange) for exchange in dFBA_profiles])", "Now that we have a simulated 'two-stage' fermentation data, let's try to analyze it. First let's try to curve fit and pull parameters from the overall data", "# These time courses together form a single trial\nsingle_trial = impt.SingleTrial()\nfor analyte in analyte_keys:\n # Instantiate the timecourse\n timecourse = impt.TimeCourse()\n \n # Define the trial identifier for the experiment\n ti = impt.ReplicateTrialIdentifier()\n ti.strain.nickname = 'my_strain'\n ti.analyte_name = analyte\n timecourse.trial_identifier = ti\n \n if analyte in biomass_keys:\n timecourse.trial_identifier.analyte_type = 'biomass'\n elif analyte in substrate_keys:\n timecourse.trial_identifier.analyte_type = 'substrate'\n elif analyte in product_keys:\n timecourse.trial_identifier.analyte_type = 'product'\n else:\n raise Exception('unid analyte')\n \n timecourse.time_vector = t\n timecourse.data_vector = dFBA_profiles[analyte]\n single_trial.add_analyte_data(timecourse)\nsingle_trial.calculate()\n# # Add this to a replicate trial (even though there's one replicate)\n# replicate_trial = impact.ReplicateTrial()\n# replicate_trial.add_replicate(single_trial)\n\n# # Add this to the experiment\n# experiment = impact.Experiment(info = {'experiment_title' : 'test experiment'})\n# experiment.add_replicate_trial(replicate_trial)\n\n# import plotly.offline\n# plotly.offline.init_notebook_mode()\n# fileName = impact.printGenericTimeCourse_plotly(replicateTrialList=[replicate_trial], \n# titersToPlot=biomass_keys,` output_type='image',)\n\n# from IPython.display import Image\n# Image(fileName)\n\n# We can query the rates instead.\nfor keys in [biomass_keys,substrate_keys,product_keys]:\n# plt.figure()\n data = []\n for analyte in keys:\n trace = Scatter(x=t,\n y=single_trial.analyte_dict[analyte].gradient,\n name = analyte)\n data.append(trace)\n fig = Figure(data=data,\n layout=Layout(title=\"Calculated rates\", \n yaxis = {'title':'Production rate [mmol / h]'})\n )\n iplot(fig)\n# plt.plot(t,single_trial.analyte_dict[analyte].gradient)\n# plt.legend(keys)", "Specific Productivity\nThe specific productivity is the rate, normalized to biomass concentration. This is the value used by dFBA to calculate the initial growth curves.\n$$ \\frac{dX}{dt} = \\mu X $$\n$$ \\frac{dP}{dt} = \\dot{P} X $$\nHere we find the median specific productivity and compare it to the FBA solutions", "exchange_keys = biomass_keys + substrate_keys + product_keys\n\nmedian_specific_productivity = {}\nmodel_specific_productivity = {}\nfor analyte in exchange_keys:\n model_specific_productivity[analyte] = model.solution.x_dict[analyte]\n median_specific_productivity[analyte] = np.median(single_trial.analyte_dict[analyte].specific_productivity.data)\n\ntrace = Bar(x=[analyte for analyte in median_specific_productivity],\n y=[median_specific_productivity[analyte] for analyte in median_specific_productivity],\n name = 'Calculated')\ntrace2 = Bar(x=[analyte for analyte in model_specific_productivity],\n y=[model_specific_productivity[analyte] for analyte in model_specific_productivity],\n name = 'Model')\ndata = [trace, trace2]\nfig = Figure(data=data,\n layout=Layout(title=\"Calculated vs Model Specific Productivity\", \n yaxis = {'title':'Specific Productivity [mmol / (gdw h)]'})\n )\niplot(fig)", "Here we can see that the specific productivities match those calculated in the COBRA model (which is expected since that's where the generated data came from). For cells in steady-state, this should be a constant.\nMetabolic Model Integration\nWith specific productivities, metabolic model integration becomes straightforward. We can constrain the export fluxes based on the data, and solve the missing fluxes. Since this is model-generated data, this will close the mass balance entirely.\nFor experimental data, this offers a prediction to help close the balance.", "# Let's take the model and add bounds for the known reactions\nfor analyte in analyte_keys:\n with_noise = np.median(single_trial.analyte_dict[analyte].specific_productivity.data)\n print(analyte,' ',with_noise)\n model.reactions.get_by_id(analyte).lower_bound = with_noise\n model.reactions.get_by_id(analyte).upper_bound = with_noise\nprint('\\n\\n\\n')\nsolution = model.optimize()\nmodel.summary()", "dFBA Batch Integration\nWe can integrate the experimental data across the course of the batch, and solve an FBA for each point to account for any misisng metabolites and get a dynamic flux map for the batch.", "# dFBA based batch simulation\n# import copy\n# model2 = copy.deepcopy(model)\n# impact.helpers.synthetic_data.dynamic_model_integration(t, y0, model2, single_trial, biomass_keys, substrate_keys, product_keys, extra_points_multiplier = 5)", "Carbon Balance\nFrom here, the carbon balance is straight forward. The export fluxes match experimental data, the remaining fluxes are estimated, and we can complete the carbon balance. Units are import here, and should all be converted a standard mass unit (g/L) to complete the balance.", "# Convert mmol/gdw - hr to g / gdw - hr\n\n# Create a dictionary for the mapping of flux reactions to metabolite names to get the molar mass\nmetabolite_export_reaction_dict = {\n 'EX_for_e':'for_e',\n 'EX_ac_e':'ac_e',\n 'EX_etoh_e':'etoh_e',\n 'EX_glc_e':'glc__D_e',\n 'EX_succ_e':'succ_e'\n}\n\nmass_flux = {}\nfor analyte in product_keys+substrate_keys:\n mass_flux[analyte] = model.solution.x_dict[analyte] \\\n * model.metabolites.get_by_id(metabolite_export_reaction_dict[analyte]).formula_weight\nmass_flux[biomass_keys[0]] = model.solution.x_dict[biomass_keys[0]]*1000\nprint(mass_flux)\n\n# The balance is the sum of all metabolites, the uptake is already negative.\nbalance = sum(mass_flux[metabolite] for metabolite in mass_flux)\nprint(balance)\n# The closure is the total substrate accounted for\npercent_closure = balance/mass_flux['EX_glc_e']\n\nprint('\\nThe mass balance is %f%% closed' % ((1-percent_closure)*100))\nprint(mass_flux)\n\n# Two situations\n# 1: balance is > 100% (must be some unaccounted substrate)\nlabels = [analyte.split('_')[1] for analyte in mass_flux]\nprint(percent_closure)\nif percent_closure < 0:\n fig = {\n 'data': [{'labels': labels + ['Unaccounted substrate'],\n 'values': [mass_flux[metabolite] for metabolite in mass_flux]+[balance],\n 'type': 'pie'}],\n 'layout': {'title': 'Mass balance'}\n }\n# 2: balance is < 100% (must be some unaccounted product)\nelse:\n fig = {\n 'data': [{'labels': labels + ['Missing product'],\n 'values': [mass_flux[metabolite] for metabolite in mass_flux]+[abs(balance)],\n 'type': 'pie'}],\n 'layout': {'title': 'Mass balance'}\n }\niplot(fig)\n\nanalyte_keys = substrate_keys + biomass_keys + product_keys\n\n# Calculate the waterfall for the products and biomass\nsubstrate_consuming_keys = biomass_keys+product_keys\nrunning_total = balance\nbase = []\nfor i, key in enumerate(analyte_keys):\n if i == 0:\n running_total += -mass_flux[key]\n base.append(0)\n else:\n base.append(running_total)\n running_total += -mass_flux[key]\n \n\nbase_trace = Bar(x=analyte_keys,\n y=base,\n marker=dict(color='rgba(1,1,1, 0.0)',))\n\nsubstrate_trace = Bar(x=[substrate_keys[0]],\n y=[-mass_flux[substrate_keys[0]]],\n marker=dict(color='rgba(55, 128, 191, 0.7)',\n line=dict(color='rgba(55, 128, 191, 1.0)',\n width=2,)))\n\n\nbiomass_trace = Bar(x=[biomass_keys[0]],\n y=[-mass_flux[biomass_keys[0]]],\n marker=dict(color='rgba(50, 171, 96, 0.7)',\n line=dict(color='rgba(50, 171, 96, 1.0)',\n width=2,)))\n\nproducts_trace = Bar(x=product_keys,\n y=[-mass_flux[metabolite] for metabolite in product_keys],\n marker=dict(color='rgba(219, 64, 82, 0.7)',\n line=dict(color='rgba(219, 64, 82, 1.0)',\n width=2,)),\n )\n\nbalance_base_trace = Bar(x=['Balance'],\n y=[base[1]-balance],\n marker=dict(color='rgba(1,1,1, 0.0)',))\n\nbalance_trace = Bar(x=['Balance'],\n y=[balance],\n marker=dict(color='rgba(0, 0, 0, 0.7)',\n line=dict(color='rgba(0, 0, 0, 1.0)',\n width=2,)),\n )\n\ndata = [substrate_trace, balance_base_trace, base_trace, balance_trace, biomass_trace,products_trace]\nlayout = Layout(barmode='stack',\n# paper_bgcolor='rgba(245, 246, 249, 1)',\n# plot_bgcolor='rgba(245, 246, 249, 1)',\n yaxis={'title': 'Exchange rate (mmol/(gdw h))'},\n showlegend=False\n )\nfig = Figure(data=data,layout=layout)\niplot(fig)", "Flux mapping with escher\nMore detail is provided in the escher documentation: http://nbviewer.jupyter.org/github/zakandrewking/escher/blob/master/docs/notebooks/COBRApy%20and%20Escher.ipynb", "import escher\nimport json\nfrom IPython.display import HTML\n\nb = escher.Builder(map_name='iJO1366.Central metabolism',\n reaction_data=solution.x_dict,\n # color and size according to the absolute value\n reaction_styles=['color', 'size', 'abs', 'text'],\n # change the default colors\n reaction_scale=[{'type': 'min', 'color': '#cccccc', 'size': 4},\n {'type': 'mean', 'color': '#0000dd', 'size': 20},\n {'type': 'max', 'color': '#ff0000', 'size': 40}],\n # only show the primary metabolites\n hide_secondary_metabolites=True)\nb.display_in_notebook()" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
diegocavalca/Studies
deep-learnining-specialization/1. neural nets and deep learning/resources/Building your Deep Neural Network - Step by Step v3.ipynb
cc0-1.0
[ "Building your Deep Neural Network: Step by Step\nWelcome to your week 4 assignment (part 1 of 2)! You have previously trained a 2-layer Neural Network (with a single hidden layer). This week, you will build a deep neural network, with as many layers as you want!\n\nIn this notebook, you will implement all the functions required to build a deep neural network.\nIn the next assignment, you will use these functions to build a deep neural network for image classification.\n\nAfter this assignment you will be able to:\n- Use non-linear units like ReLU to improve your model\n- Build a deeper neural network (with more than 1 hidden layer)\n- Implement an easy-to-use neural network class\nNotation:\n- Superscript $[l]$ denotes a quantity associated with the $l^{th}$ layer. \n - Example: $a^{[L]}$ is the $L^{th}$ layer activation. $W^{[L]}$ and $b^{[L]}$ are the $L^{th}$ layer parameters.\n- Superscript $(i)$ denotes a quantity associated with the $i^{th}$ example. \n - Example: $x^{(i)}$ is the $i^{th}$ training example.\n- Lowerscript $i$ denotes the $i^{th}$ entry of a vector.\n - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the $l^{th}$ layer's activations).\nLet's get started!\n1 - Packages\nLet's first import all the packages that you will need during this assignment. \n- numpy is the main package for scientific computing with Python.\n- matplotlib is a library to plot graphs in Python.\n- dnn_utils provides some necessary functions for this notebook.\n- testCases provides some test cases to assess the correctness of your functions\n- np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work. Please don't change the seed.", "import numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nfrom testCases_v2 import *\nfrom dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n%load_ext autoreload\n%autoreload 2\n\nnp.random.seed(1)", "2 - Outline of the Assignment\nTo build your neural network, you will be implementing several \"helper functions\". These helper functions will be used in the next assignment to build a two-layer neural network and an L-layer neural network. Each small helper function you will implement will have detailed instructions that will walk you through the necessary steps. Here is an outline of this assignment, you will:\n\nInitialize the parameters for a two-layer network and for an $L$-layer neural network.\nImplement the forward propagation module (shown in purple in the figure below).\nComplete the LINEAR part of a layer's forward propagation step (resulting in $Z^{[l]}$).\nWe give you the ACTIVATION function (relu/sigmoid).\nCombine the previous two steps into a new [LINEAR->ACTIVATION] forward function.\nStack the [LINEAR->RELU] forward function L-1 time (for layers 1 through L-1) and add a [LINEAR->SIGMOID] at the end (for the final layer $L$). This gives you a new L_model_forward function.\n\n\nCompute the loss.\nImplement the backward propagation module (denoted in red in the figure below).\nComplete the LINEAR part of a layer's backward propagation step.\nWe give you the gradient of the ACTIVATE function (relu_backward/sigmoid_backward) \nCombine the previous two steps into a new [LINEAR->ACTIVATION] backward function.\nStack [LINEAR->RELU] backward L-1 times and add [LINEAR->SIGMOID] backward in a new L_model_backward function\n\n\nFinally update the parameters.\n\n<img src=\"images/final outline.png\" style=\"width:800px;height:500px;\">\n<caption><center> Figure 1</center></caption><br>\nNote that for every forward function, there is a corresponding backward function. That is why at every step of your forward module you will be storing some values in a cache. The cached values are useful for computing gradients. In the backpropagation module you will then use the cache to calculate the gradients. This assignment will show you exactly how to carry out each of these steps. \n3 - Initialization\nYou will write two helper functions that will initialize the parameters for your model. The first function will be used to initialize parameters for a two layer model. The second one will generalize this initialization process to $L$ layers.\n3.1 - 2-layer Neural Network\nExercise: Create and initialize the parameters of the 2-layer neural network.\nInstructions:\n- The model's structure is: LINEAR -> RELU -> LINEAR -> SIGMOID. \n- Use random initialization for the weight matrices. Use np.random.randn(shape)*0.01 with the correct shape.\n- Use zero initialization for the biases. Use np.zeros(shape).", "# GRADED FUNCTION: initialize_parameters\n\ndef initialize_parameters(n_x, n_h, n_y):\n \"\"\"\n Argument:\n n_x -- size of the input layer\n n_h -- size of the hidden layer\n n_y -- size of the output layer\n \n Returns:\n parameters -- python dictionary containing your parameters:\n W1 -- weight matrix of shape (n_h, n_x)\n b1 -- bias vector of shape (n_h, 1)\n W2 -- weight matrix of shape (n_y, n_h)\n b2 -- bias vector of shape (n_y, 1)\n \"\"\"\n \n np.random.seed(1)\n \n ### START CODE HERE ### (≈ 4 lines of code)\n W1 = np.random.randn(n_h, n_x)*0.01\n b1 = np.zeros((n_h, 1))\n W2 = np.random.randn(n_y, n_h)*0.01\n b2 = np.zeros((n_y, 1))\n ### END CODE HERE ###\n \n assert(W1.shape == (n_h, n_x))\n assert(b1.shape == (n_h, 1))\n assert(W2.shape == (n_y, n_h))\n assert(b2.shape == (n_y, 1))\n \n parameters = {\"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2}\n \n return parameters \n\nparameters = initialize_parameters(2,2,1)\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))", "Expected output:\n<table style=\"width:80%\">\n <tr>\n <td> **W1** </td>\n <td> [[ 0.01624345 -0.00611756]\n [-0.00528172 -0.01072969]] </td> \n </tr>\n\n <tr>\n <td> **b1**</td>\n <td>[[ 0.]\n [ 0.]]</td> \n </tr>\n\n <tr>\n <td>**W2**</td>\n <td> [[ 0.00865408 -0.02301539]]</td>\n </tr>\n\n <tr>\n <td> **b2** </td>\n <td> [[ 0.]] </td> \n </tr>\n\n</table>\n\n3.2 - L-layer Neural Network\nThe initialization for a deeper L-layer neural network is more complicated because there are many more weight matrices and bias vectors. When completing the initialize_parameters_deep, you should make sure that your dimensions match between each layer. Recall that $n^{[l]}$ is the number of units in layer $l$. Thus for example if the size of our input $X$ is $(12288, 209)$ (with $m=209$ examples) then:\n<table style=\"width:100%\">\n\n\n <tr>\n <td> </td> \n <td> **Shape of W** </td> \n <td> **Shape of b** </td> \n <td> **Activation** </td>\n <td> **Shape of Activation** </td> \n <tr>\n\n <tr>\n <td> **Layer 1** </td> \n <td> $(n^{[1]},12288)$ </td> \n <td> $(n^{[1]},1)$ </td> \n <td> $Z^{[1]} = W^{[1]} X + b^{[1]} $ </td> \n\n <td> $(n^{[1]},209)$ </td> \n <tr>\n\n <tr>\n <td> **Layer 2** </td> \n <td> $(n^{[2]}, n^{[1]})$ </td> \n <td> $(n^{[2]},1)$ </td> \n <td>$Z^{[2]} = W^{[2]} A^{[1]} + b^{[2]}$ </td> \n <td> $(n^{[2]}, 209)$ </td> \n <tr>\n\n <tr>\n <td> $\\vdots$ </td> \n <td> $\\vdots$ </td> \n <td> $\\vdots$ </td> \n <td> $\\vdots$</td> \n <td> $\\vdots$ </td> \n <tr>\n\n <tr>\n <td> **Layer L-1** </td> \n <td> $(n^{[L-1]}, n^{[L-2]})$ </td> \n <td> $(n^{[L-1]}, 1)$ </td> \n <td>$Z^{[L-1]} = W^{[L-1]} A^{[L-2]} + b^{[L-1]}$ </td> \n <td> $(n^{[L-1]}, 209)$ </td> \n <tr>\n\n\n <tr>\n <td> **Layer L** </td> \n <td> $(n^{[L]}, n^{[L-1]})$ </td> \n <td> $(n^{[L]}, 1)$ </td>\n <td> $Z^{[L]} = W^{[L]} A^{[L-1]} + b^{[L]}$</td>\n <td> $(n^{[L]}, 209)$ </td> \n <tr>\n\n</table>\n\nRemember that when we compute $W X + b$ in python, it carries out broadcasting. For example, if: \n$$ W = \\begin{bmatrix}\n j & k & l\\\n m & n & o \\\n p & q & r \n\\end{bmatrix}\\;\\;\\; X = \\begin{bmatrix}\n a & b & c\\\n d & e & f \\\n g & h & i \n\\end{bmatrix} \\;\\;\\; b =\\begin{bmatrix}\n s \\\n t \\\n u\n\\end{bmatrix}\\tag{2}$$\nThen $WX + b$ will be:\n$$ WX + b = \\begin{bmatrix}\n (ja + kd + lg) + s & (jb + ke + lh) + s & (jc + kf + li)+ s\\\n (ma + nd + og) + t & (mb + ne + oh) + t & (mc + nf + oi) + t\\\n (pa + qd + rg) + u & (pb + qe + rh) + u & (pc + qf + ri)+ u\n\\end{bmatrix}\\tag{3} $$\nExercise: Implement initialization for an L-layer Neural Network. \nInstructions:\n- The model's structure is [LINEAR -> RELU] $ \\times$ (L-1) -> LINEAR -> SIGMOID. I.e., it has $L-1$ layers using a ReLU activation function followed by an output layer with a sigmoid activation function.\n- Use random initialization for the weight matrices. Use np.random.rand(shape) * 0.01.\n- Use zeros initialization for the biases. Use np.zeros(shape).\n- We will store $n^{[l]}$, the number of units in different layers, in a variable layer_dims. For example, the layer_dims for the \"Planar Data classification model\" from last week would have been [2,4,1]: There were two inputs, one hidden layer with 4 hidden units, and an output layer with 1 output unit. Thus means W1's shape was (4,2), b1 was (4,1), W2 was (1,4) and b2 was (1,1). Now you will generalize this to $L$ layers! \n- Here is the implementation for $L=1$ (one layer neural network). It should inspire you to implement the general case (L-layer neural network).\npython\n if L == 1:\n parameters[\"W\" + str(L)] = np.random.randn(layer_dims[1], layer_dims[0]) * 0.01\n parameters[\"b\" + str(L)] = np.zeros((layer_dims[1], 1))", "# GRADED FUNCTION: initialize_parameters_deep\n\ndef initialize_parameters_deep(layer_dims):\n \"\"\"\n Arguments:\n layer_dims -- python array (list) containing the dimensions of each layer in our network\n \n Returns:\n parameters -- python dictionary containing your parameters \"W1\", \"b1\", ..., \"WL\", \"bL\":\n Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1])\n bl -- bias vector of shape (layer_dims[l], 1)\n \"\"\"\n \n np.random.seed(3)\n parameters = {}\n L = len(layer_dims) # number of layers in the network\n\n for l in range(1, L):\n ### START CODE HERE ### (≈ 2 lines of code)\n parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) * 0.01\n parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))\n ### END CODE HERE ###\n \n assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1]))\n assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))\n\n \n return parameters\n\nparameters = initialize_parameters_deep([5,4,3])\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))", "Expected output:\n<table style=\"width:80%\">\n <tr>\n <td> **W1** </td>\n <td>[[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388]\n [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218]\n [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034]\n [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]]</td> \n </tr>\n\n <tr>\n <td>**b1** </td>\n <td>[[ 0.]\n [ 0.]\n [ 0.]\n [ 0.]]</td> \n </tr>\n\n <tr>\n <td>**W2** </td>\n <td>[[-0.01185047 -0.0020565 0.01486148 0.00236716]\n [-0.01023785 -0.00712993 0.00625245 -0.00160513]\n [-0.00768836 -0.00230031 0.00745056 0.01976111]]</td> \n </tr>\n\n <tr>\n <td>**b2** </td>\n <td>[[ 0.]\n [ 0.]\n [ 0.]]</td> \n </tr>\n\n</table>\n\n4 - Forward propagation module\n4.1 - Linear Forward\nNow that you have initialized your parameters, you will do the forward propagation module. You will start by implementing some basic functions that you will use later when implementing the model. You will complete three functions in this order:\n\nLINEAR\nLINEAR -> ACTIVATION where ACTIVATION will be either ReLU or Sigmoid. \n[LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID (whole model)\n\nThe linear forward module (vectorized over all the examples) computes the following equations:\n$$Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}\\tag{4}$$\nwhere $A^{[0]} = X$. \nExercise: Build the linear part of forward propagation.\nReminder:\nThe mathematical representation of this unit is $Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}$. You may also find np.dot() useful. If your dimensions don't match, printing W.shape may help.", "# GRADED FUNCTION: linear_forward\n\ndef linear_forward(A, W, b):\n \"\"\"\n Implement the linear part of a layer's forward propagation.\n\n Arguments:\n A -- activations from previous layer (or input data): (size of previous layer, number of examples)\n W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)\n b -- bias vector, numpy array of shape (size of the current layer, 1)\n\n Returns:\n Z -- the input of the activation function, also called pre-activation parameter \n cache -- a python dictionary containing \"A\", \"W\" and \"b\" ; stored for computing the backward pass efficiently\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n Z = np.dot(W, A) + b\n ### END CODE HERE ###\n \n assert(Z.shape == (W.shape[0], A.shape[1]))\n cache = (A, W, b)\n \n return Z, cache\n\nA, W, b = linear_forward_test_case()\n\nZ, linear_cache = linear_forward(A, W, b)\nprint(\"Z = \" + str(Z))", "Expected output:\n<table style=\"width:35%\">\n\n <tr>\n <td> **Z** </td>\n <td> [[ 3.26295337 -1.23429987]] </td> \n </tr>\n\n</table>\n\n4.2 - Linear-Activation Forward\nIn this notebook, you will use two activation functions:\n\n\nSigmoid: $\\sigma(Z) = \\sigma(W A + b) = \\frac{1}{ 1 + e^{-(W A + b)}}$. We have provided you with the sigmoid function. This function returns two items: the activation value \"a\" and a \"cache\" that contains \"Z\" (it's what we will feed in to the corresponding backward function). To use it you could just call: \npython\nA, activation_cache = sigmoid(Z)\n\n\nReLU: The mathematical formula for ReLu is $A = RELU(Z) = max(0, Z)$. We have provided you with the relu function. This function returns two items: the activation value \"A\" and a \"cache\" that contains \"Z\" (it's what we will feed in to the corresponding backward function). To use it you could just call:\npython\nA, activation_cache = relu(Z)\n\n\nFor more convenience, you are going to group two functions (Linear and Activation) into one function (LINEAR->ACTIVATION). Hence, you will implement a function that does the LINEAR forward step followed by an ACTIVATION forward step.\nExercise: Implement the forward propagation of the LINEAR->ACTIVATION layer. Mathematical relation is: $A^{[l]} = g(Z^{[l]}) = g(W^{[l]}A^{[l-1]} +b^{[l]})$ where the activation \"g\" can be sigmoid() or relu(). Use linear_forward() and the correct activation function.", "# GRADED FUNCTION: linear_activation_forward\n\ndef linear_activation_forward(A_prev, W, b, activation):\n \"\"\"\n Implement the forward propagation for the LINEAR->ACTIVATION layer\n\n Arguments:\n A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)\n W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)\n b -- bias vector, numpy array of shape (size of the current layer, 1)\n activation -- the activation to be used in this layer, stored as a text string: \"sigmoid\" or \"relu\"\n\n Returns:\n A -- the output of the activation function, also called the post-activation value \n cache -- a python dictionary containing \"linear_cache\" and \"activation_cache\";\n stored for computing the backward pass efficiently\n \"\"\"\n \n if activation == \"sigmoid\":\n # Inputs: \"A_prev, W, b\". Outputs: \"A, activation_cache\".\n ### START CODE HERE ### (≈ 2 lines of code)\n Z, linear_cache = linear_forward(A_prev, W, b)\n A, activation_cache = sigmoid(Z)\n ### END CODE HERE ###\n \n elif activation == \"relu\":\n # Inputs: \"A_prev, W, b\". Outputs: \"A, activation_cache\".\n ### START CODE HERE ### (≈ 2 lines of code)\n Z, linear_cache = linear_forward(A_prev, W, b)\n A, activation_cache = relu(Z)\n ### END CODE HERE ###\n \n assert (A.shape == (W.shape[0], A_prev.shape[1]))\n cache = (linear_cache, activation_cache)\n\n return A, cache\n\nA_prev, W, b = linear_activation_forward_test_case()\n\nA, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = \"sigmoid\")\nprint(\"With sigmoid: A = \" + str(A))\n\nA, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = \"relu\")\nprint(\"With ReLU: A = \" + str(A))", "Expected output:\n<table style=\"width:35%\">\n <tr>\n <td> **With sigmoid: A ** </td>\n <td > [[ 0.96890023 0.11013289]]</td> \n </tr>\n <tr>\n <td> **With ReLU: A ** </td>\n <td > [[ 3.43896131 0. ]]</td> \n </tr>\n</table>\n\nNote: In deep learning, the \"[LINEAR->ACTIVATION]\" computation is counted as a single layer in the neural network, not two layers. \nd) L-Layer Model\nFor even more convenience when implementing the $L$-layer Neural Net, you will need a function that replicates the previous one (linear_activation_forward with RELU) $L-1$ times, then follows that with one linear_activation_forward with SIGMOID.\n<img src=\"images/model_architecture_kiank.png\" style=\"width:600px;height:300px;\">\n<caption><center> Figure 2 : [LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID model</center></caption><br>\nExercise: Implement the forward propagation of the above model.\nInstruction: In the code below, the variable AL will denote $A^{[L]} = \\sigma(Z^{[L]}) = \\sigma(W^{[L]} A^{[L-1]} + b^{[L]})$. (This is sometimes also called Yhat, i.e., this is $\\hat{Y}$.) \nTips:\n- Use the functions you had previously written \n- Use a for loop to replicate [LINEAR->RELU] (L-1) times\n- Don't forget to keep track of the caches in the \"caches\" list. To add a new value c to a list, you can use list.append(c).", "# GRADED FUNCTION: L_model_forward\n\ndef L_model_forward(X, parameters):\n \"\"\"\n Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation\n \n Arguments:\n X -- data, numpy array of shape (input size, number of examples)\n parameters -- output of initialize_parameters_deep()\n \n Returns:\n AL -- last post-activation value\n caches -- list of caches containing:\n every cache of linear_relu_forward() (there are L-1 of them, indexed from 0 to L-2)\n the cache of linear_sigmoid_forward() (there is one, indexed L-1)\n \"\"\"\n\n caches = []\n A = X\n L = len(parameters) // 2 # number of layers in the neural network\n \n # Implement [LINEAR -> RELU]*(L-1). Add \"cache\" to the \"caches\" list.\n for l in range(1, L):\n A_prev = A \n ### START CODE HERE ### (≈ 2 lines of code)\n A, cache = linear_activation_forward(A_prev, parameters['W'+str(l)], parameters['b'+str(l)], activation = \"relu\")\n caches.append(cache)\n ### END CODE HERE ###\n \n # Implement LINEAR -> SIGMOID. Add \"cache\" to the \"caches\" list.\n ### START CODE HERE ### (≈ 2 lines of code)\n AL, cache = linear_activation_forward(A, parameters['W'+str(L)], parameters['b'+str(L)], activation = \"sigmoid\")\n caches.append(cache)\n ### END CODE HERE ###\n \n assert(AL.shape == (1,X.shape[1]))\n \n return AL, caches\n\nX, parameters = L_model_forward_test_case()\nAL, caches = L_model_forward(X, parameters)\nprint(\"AL = \" + str(AL))\nprint(\"Length of caches list = \" + str(len(caches)))", "<table style=\"width:40%\">\n <tr>\n <td> **AL** </td>\n <td > [[ 0.17007265 0.2524272 ]]</td> \n </tr>\n <tr>\n <td> **Length of caches list ** </td>\n <td > 2</td> \n </tr>\n</table>\n\nGreat! Now you have a full forward propagation that takes the input X and outputs a row vector $A^{[L]}$ containing your predictions. It also records all intermediate values in \"caches\". Using $A^{[L]}$, you can compute the cost of your predictions.\n5 - Cost function\nNow you will implement forward and backward propagation. You need to compute the cost, because you want to check if your model is actually learning.\nExercise: Compute the cross-entropy cost $J$, using the following formula: $$-\\frac{1}{m} \\sum\\limits_{i = 1}^{m} (y^{(i)}\\log\\left(a^{[L] (i)}\\right) + (1-y^{(i)})\\log\\left(1- a^{L}\\right)) \\tag{7}$$", "# GRADED FUNCTION: compute_cost\n\ndef compute_cost(AL, Y):\n \"\"\"\n Implement the cost function defined by equation (7).\n\n Arguments:\n AL -- probability vector corresponding to your label predictions, shape (1, number of examples)\n Y -- true \"label\" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)\n\n Returns:\n cost -- cross-entropy cost\n \"\"\"\n \n m = Y.shape[1]\n\n # Compute loss from aL and y.\n ### START CODE HERE ### (≈ 1 lines of code)\n cost = -1./m * np.sum(Y*np.log(AL) + (1-Y)*np.log(1-AL))\n ### END CODE HERE ###\n \n cost = np.squeeze(cost) # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).\n assert(cost.shape == ())\n \n return cost\n\nY, AL = compute_cost_test_case()\n\nprint(\"cost = \" + str(compute_cost(AL, Y)))", "Expected Output:\n<table>\n\n <tr>\n <td>**cost** </td>\n <td> 0.41493159961539694</td> \n </tr>\n</table>\n\n6 - Backward propagation module\nJust like with forward propagation, you will implement helper functions for backpropagation. Remember that back propagation is used to calculate the gradient of the loss function with respect to the parameters. \nReminder: \n<img src=\"images/backprop_kiank.png\" style=\"width:650px;height:250px;\">\n<caption><center> Figure 3 : Forward and Backward propagation for LINEAR->RELU->LINEAR->SIGMOID <br> The purple blocks represent the forward propagation, and the red blocks represent the backward propagation. </center></caption>\n<!-- \nFor those of you who are expert in calculus (you don't need to be to do this assignment), the chain rule of calculus can be used to derive the derivative of the loss $\\mathcal{L}$ with respect to $z^{[1]}$ in a 2-layer network as follows:\n\n$$\\frac{d \\mathcal{L}(a^{[2]},y)}{{dz^{[1]}}} = \\frac{d\\mathcal{L}(a^{[2]},y)}{{da^{[2]}}}\\frac{{da^{[2]}}}{{dz^{[2]}}}\\frac{{dz^{[2]}}}{{da^{[1]}}}\\frac{{da^{[1]}}}{{dz^{[1]}}} \\tag{8} $$\n\nIn order to calculate the gradient $dW^{[1]} = \\frac{\\partial L}{\\partial W^{[1]}}$, you use the previous chain rule and you do $dW^{[1]} = dz^{[1]} \\times \\frac{\\partial z^{[1]} }{\\partial W^{[1]}}$. During the backpropagation, at each step you multiply your current gradient by the gradient corresponding to the specific layer to get the gradient you wanted.\n\nEquivalently, in order to calculate the gradient $db^{[1]} = \\frac{\\partial L}{\\partial b^{[1]}}$, you use the previous chain rule and you do $db^{[1]} = dz^{[1]} \\times \\frac{\\partial z^{[1]} }{\\partial b^{[1]}}$.\n\nThis is why we talk about **backpropagation**.\n!-->\n\nNow, similar to forward propagation, you are going to build the backward propagation in three steps:\n- LINEAR backward\n- LINEAR -> ACTIVATION backward where ACTIVATION computes the derivative of either the ReLU or sigmoid activation\n- [LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID backward (whole model)\n6.1 - Linear backward\nFor layer $l$, the linear part is: $Z^{[l]} = W^{[l]} A^{[l-1]} + b^{[l]}$ (followed by an activation).\nSuppose you have already calculated the derivative $dZ^{[l]} = \\frac{\\partial \\mathcal{L} }{\\partial Z^{[l]}}$. You want to get $(dW^{[l]}, db^{[l]} dA^{[l-1]})$.\n<img src=\"images/linearback_kiank.png\" style=\"width:250px;height:300px;\">\n<caption><center> Figure 4 </center></caption>\nThe three outputs $(dW^{[l]}, db^{[l]}, dA^{[l]})$ are computed using the input $dZ^{[l]}$.Here are the formulas you need:\n$$ dW^{[l]} = \\frac{\\partial \\mathcal{L} }{\\partial W^{[l]}} = \\frac{1}{m} dZ^{[l]} A^{[l-1] T} \\tag{8}$$\n$$ db^{[l]} = \\frac{\\partial \\mathcal{L} }{\\partial b^{[l]}} = \\frac{1}{m} \\sum_{i = 1}^{m} dZ^{l}\\tag{9}$$\n$$ dA^{[l-1]} = \\frac{\\partial \\mathcal{L} }{\\partial A^{[l-1]}} = W^{[l] T} dZ^{[l]} \\tag{10}$$\nExercise: Use the 3 formulas above to implement linear_backward().", "# GRADED FUNCTION: linear_backward\n\ndef linear_backward(dZ, cache):\n \"\"\"\n Implement the linear portion of backward propagation for a single layer (layer l)\n\n Arguments:\n dZ -- Gradient of the cost with respect to the linear output (of current layer l)\n cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer\n\n Returns:\n dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n dW -- Gradient of the cost with respect to W (current layer l), same shape as W\n db -- Gradient of the cost with respect to b (current layer l), same shape as b\n \"\"\"\n A_prev, W, b = cache\n m = A_prev.shape[1]\n\n ### START CODE HERE ### (≈ 3 lines of code)\n dW = 1./m * np.dot(dZ, A_prev.T)\n db = 1./m * np.sum(dZ, axis=1, keepdims=True)\n dA_prev = np.dot(W.T, dZ)\n ### END CODE HERE ###\n \n assert (dA_prev.shape == A_prev.shape)\n assert (dW.shape == W.shape)\n assert (db.shape == b.shape)\n \n return dA_prev, dW, db\n\n# Set up some test inputs\ndZ, linear_cache = linear_backward_test_case()\n\ndA_prev, dW, db = linear_backward(dZ, linear_cache)\nprint (\"dA_prev = \"+ str(dA_prev))\nprint (\"dW = \" + str(dW))\nprint (\"db = \" + str(db))", "Expected Output: \n<table style=\"width:90%\">\n <tr>\n <td> **dA_prev** </td>\n <td > [[ 0.51822968 -0.19517421]\n [-0.40506361 0.15255393]\n [ 2.37496825 -0.89445391]] </td> \n </tr> \n\n <tr>\n <td> **dW** </td>\n <td > [[-0.10076895 1.40685096 1.64992505]] </td> \n </tr> \n\n <tr>\n <td> **db** </td>\n <td> [[ 0.50629448]] </td> \n </tr> \n\n</table>\n\n6.2 - Linear-Activation backward\nNext, you will create a function that merges the two helper functions: linear_backward and the backward step for the activation linear_activation_backward. \nTo help you implement linear_activation_backward, we provided two backward functions:\n- sigmoid_backward: Implements the backward propagation for SIGMOID unit. You can call it as follows:\npython\ndZ = sigmoid_backward(dA, activation_cache)\n\nrelu_backward: Implements the backward propagation for RELU unit. You can call it as follows:\n\npython\ndZ = relu_backward(dA, activation_cache)\nIf $g(.)$ is the activation function, \nsigmoid_backward and relu_backward compute $$dZ^{[l]} = dA^{[l]} * g'(Z^{[l]}) \\tag{11}$$. \nExercise: Implement the backpropagation for the LINEAR->ACTIVATION layer.", "# GRADED FUNCTION: linear_activation_backward\n\ndef linear_activation_backward(dA, cache, activation):\n \"\"\"\n Implement the backward propagation for the LINEAR->ACTIVATION layer.\n \n Arguments:\n dA -- post-activation gradient for current layer l \n cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently\n activation -- the activation to be used in this layer, stored as a text string: \"sigmoid\" or \"relu\"\n \n Returns:\n dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n dW -- Gradient of the cost with respect to W (current layer l), same shape as W\n db -- Gradient of the cost with respect to b (current layer l), same shape as b\n \"\"\"\n linear_cache, activation_cache = cache\n \n if activation == \"relu\":\n ### START CODE HERE ### (≈ 2 lines of code)\n dZ = relu_backward(dA, activation_cache)\n dA_prev, dW, db = linear_backward(dZ, linear_cache)\n ### END CODE HERE ###\n \n elif activation == \"sigmoid\":\n ### START CODE HERE ### (≈ 2 lines of code)\n dZ = sigmoid_backward(dA, activation_cache)\n dA_prev, dW, db = linear_backward(dZ, linear_cache)\n ### END CODE HERE ###\n \n return dA_prev, dW, db\n\nAL, linear_activation_cache = linear_activation_backward_test_case()\n\ndA_prev, dW, db = linear_activation_backward(AL, linear_activation_cache, activation = \"sigmoid\")\nprint (\"sigmoid:\")\nprint (\"dA_prev = \"+ str(dA_prev))\nprint (\"dW = \" + str(dW))\nprint (\"db = \" + str(db) + \"\\n\")\n\ndA_prev, dW, db = linear_activation_backward(AL, linear_activation_cache, activation = \"relu\")\nprint (\"relu:\")\nprint (\"dA_prev = \"+ str(dA_prev))\nprint (\"dW = \" + str(dW))\nprint (\"db = \" + str(db))", "Expected output with sigmoid:\n<table style=\"width:100%\">\n <tr>\n <td > dA_prev </td> \n <td >[[ 0.11017994 0.01105339]\n [ 0.09466817 0.00949723]\n [-0.05743092 -0.00576154]] </td> \n\n </tr> \n\n <tr>\n <td > dW </td> \n <td > [[ 0.10266786 0.09778551 -0.01968084]] </td> \n </tr> \n\n <tr>\n <td > db </td> \n <td > [[-0.05729622]] </td> \n </tr> \n</table>\n\nExpected output with relu\n<table style=\"width:100%\">\n <tr>\n <td > dA_prev </td> \n <td > [[ 0.44090989 0. ]\n [ 0.37883606 0. ]\n [-0.2298228 0. ]] </td> \n\n </tr> \n\n <tr>\n <td > dW </td> \n <td > [[ 0.44513824 0.37371418 -0.10478989]] </td> \n </tr> \n\n <tr>\n <td > db </td> \n <td > [[-0.20837892]] </td> \n </tr> \n</table>\n\n6.3 - L-Model Backward\nNow you will implement the backward function for the whole network. Recall that when you implemented the L_model_forward function, at each iteration, you stored a cache which contains (X,W,b, and z). In the back propagation module, you will use those variables to compute the gradients. Therefore, in the L_model_backward function, you will iterate through all the hidden layers backward, starting from layer $L$. On each step, you will use the cached values for layer $l$ to backpropagate through layer $l$. Figure 5 below shows the backward pass. \n<img src=\"images/mn_backward.png\" style=\"width:450px;height:300px;\">\n<caption><center> Figure 5 : Backward pass </center></caption>\n Initializing backpropagation:\nTo backpropagate through this network, we know that the output is, \n$A^{[L]} = \\sigma(Z^{[L]})$. Your code thus needs to compute dAL $= \\frac{\\partial \\mathcal{L}}{\\partial A^{[L]}}$.\nTo do so, use this formula (derived using calculus which you don't need in-depth knowledge of):\npython\ndAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) # derivative of cost with respect to AL\nYou can then use this post-activation gradient dAL to keep going backward. As seen in Figure 5, you can now feed in dAL into the LINEAR->SIGMOID backward function you implemented (which will use the cached values stored by the L_model_forward function). After that, you will have to use a for loop to iterate through all the other layers using the LINEAR->RELU backward function. You should store each dA, dW, and db in the grads dictionary. To do so, use this formula : \n$$grads[\"dW\" + str(l)] = dW^{[l]}\\tag{15} $$\nFor example, for $l=3$ this would store $dW^{[l]}$ in grads[\"dW3\"].\nExercise: Implement backpropagation for the [LINEAR->RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID model.", "# GRADED FUNCTION: L_model_backward\n\ndef L_model_backward(AL, Y, caches):\n \"\"\"\n Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group\n \n Arguments:\n AL -- probability vector, output of the forward propagation (L_model_forward())\n Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat)\n caches -- list of caches containing:\n every cache of linear_activation_forward() with \"relu\" (it's caches[l], for l in range(L-1) i.e l = 0...L-2)\n the cache of linear_activation_forward() with \"sigmoid\" (it's caches[L-1])\n \n Returns:\n grads -- A dictionary with the gradients\n grads[\"dA\" + str(l)] = ... \n grads[\"dW\" + str(l)] = ...\n grads[\"db\" + str(l)] = ... \n \"\"\"\n grads = {}\n L = len(caches) # the number of layers\n m = AL.shape[1]\n Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL\n \n # Initializing the backpropagation\n ### START CODE HERE ### (1 line of code)\n dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))\n ### END CODE HERE ###\n \n # Lth layer (SIGMOID -> LINEAR) gradients. Inputs: \"AL, Y, caches\". Outputs: \"grads[\"dAL\"], grads[\"dWL\"], grads[\"dbL\"]\n ### START CODE HERE ### (approx. 2 lines)\n current_cache = caches[L-1]\n grads[\"dA\" + str(L)], grads[\"dW\" + str(L)], grads[\"db\" + str(L)] = linear_activation_backward(dAL, current_cache, activation = \"sigmoid\")\n ### END CODE HERE ###\n\n for l in reversed(range(L-1)):\n # lth layer: (RELU -> LINEAR) gradients.\n # Inputs: \"grads[\"dA\" + str(l + 2)], caches\". Outputs: \"grads[\"dA\" + str(l + 1)] , grads[\"dW\" + str(l + 1)] , grads[\"db\" + str(l + 1)] \n ### START CODE HERE ### (approx. 5 lines)\n current_cache = caches[l]\n dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads['dA' + str(l + 2)], current_cache, activation = \"relu\")\n grads[\"dA\" + str(l + 1)] = dA_prev_temp\n grads[\"dW\" + str(l + 1)] = dW_temp\n grads[\"db\" + str(l + 1)] = db_temp\n ### END CODE HERE ###\n\n return grads\n\nAL, Y_assess, caches = L_model_backward_test_case()\ngrads = L_model_backward(AL, Y_assess, caches)\nprint (\"dW1 = \"+ str(grads[\"dW1\"]))\nprint (\"db1 = \"+ str(grads[\"db1\"]))\nprint (\"dA1 = \"+ str(grads[\"dA1\"]))", "Expected Output\n<table style=\"width:60%\">\n\n <tr>\n <td > dW1 </td> \n <td > [[ 0.41010002 0.07807203 0.13798444 0.10502167]\n [ 0. 0. 0. 0. ]\n [ 0.05283652 0.01005865 0.01777766 0.0135308 ]] </td> \n </tr> \n\n <tr>\n <td > db1 </td> \n <td > [[-0.22007063]\n [ 0. ]\n [-0.02835349]] </td> \n </tr> \n\n <tr>\n <td > dA1 </td> \n <td > [[ 0. 0.52257901]\n [ 0. -0.3269206 ]\n [ 0. -0.32070404]\n [ 0. -0.74079187]] </td> \n\n </tr> \n</table>\n\n6.4 - Update Parameters\nIn this section you will update the parameters of the model, using gradient descent: \n$$ W^{[l]} = W^{[l]} - \\alpha \\text{ } dW^{[l]} \\tag{16}$$\n$$ b^{[l]} = b^{[l]} - \\alpha \\text{ } db^{[l]} \\tag{17}$$\nwhere $\\alpha$ is the learning rate. After computing the updated parameters, store them in the parameters dictionary. \nExercise: Implement update_parameters() to update your parameters using gradient descent.\nInstructions:\nUpdate parameters using gradient descent on every $W^{[l]}$ and $b^{[l]}$ for $l = 1, 2, ..., L$.", "# GRADED FUNCTION: update_parameters\n\ndef update_parameters(parameters, grads, learning_rate):\n \"\"\"\n Update parameters using gradient descent\n \n Arguments:\n parameters -- python dictionary containing your parameters \n grads -- python dictionary containing your gradients, output of L_model_backward\n \n Returns:\n parameters -- python dictionary containing your updated parameters \n parameters[\"W\" + str(l)] = ... \n parameters[\"b\" + str(l)] = ...\n \"\"\"\n \n L = len(parameters) // 2 # number of layers in the neural network\n\n # Update rule for each parameter. Use a for loop.\n ### START CODE HERE ### (≈ 3 lines of code)\n for l in range(L):\n parameters[\"W\" + str(l+1)] = parameters[\"W\" + str(l+1)] - learning_rate*grads[\"dW\" + str(l+1)]\n parameters[\"b\" + str(l+1)] = parameters[\"b\" + str(l+1)] - learning_rate*grads[\"db\" + str(l+1)]\n ### END CODE HERE ###\n \n return parameters\n\nparameters, grads = update_parameters_test_case()\nparameters = update_parameters(parameters, grads, 0.1)\n\nprint (\"W1 = \"+ str(parameters[\"W1\"]))\nprint (\"b1 = \"+ str(parameters[\"b1\"]))\nprint (\"W2 = \"+ str(parameters[\"W2\"]))\nprint (\"b2 = \"+ str(parameters[\"b2\"]))", "Expected Output:\n<table style=\"width:100%\"> \n <tr>\n <td > W1 </td> \n <td > [[-0.59562069 -0.09991781 -2.14584584 1.82662008]\n [-1.76569676 -0.80627147 0.51115557 -1.18258802]\n [-1.0535704 -0.86128581 0.68284052 2.20374577]] </td> \n </tr> \n\n <tr>\n <td > b1 </td> \n <td > [[-0.04659241]\n [-1.28888275]\n [ 0.53405496]] </td> \n </tr> \n <tr>\n <td > W2 </td> \n <td > [[-0.55569196 0.0354055 1.32964895]]</td> \n </tr> \n\n <tr>\n <td > b2 </td> \n <td > [[-0.84610769]] </td> \n </tr> \n</table>\n\n7 - Conclusion\nCongrats on implementing all the functions required for building a deep neural network! \nWe know it was a long assignment but going forward it will only get better. The next part of the assignment is easier. \nIn the next assignment you will put all these together to build two models:\n- A two-layer neural network\n- An L-layer neural network\nYou will in fact use these models to classify cat vs non-cat images!" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
atulsingh0/MachineLearning
python_DC/LP_Read_Write_Data_#5.ipynb
gpl-3.0
[ "# import\nimport pandas as pd\nimport numpy as np", "Parsing functions in pandas\nread_csv Load delimited data from a file, URL, or file-like object. Use comma as default delimiter\nread_table Load delimited data from a file, URL, or file-like object. Use tab ('\\t') as default delimiter\nread_fwf Read data in fixed-width column format (that is, no delimiters)\nread_clipboard Version of read_table that reads data from the clipboard. Useful for converting tables from web pages", "# reading csv file, first check the content of it\n!more \"dataset/Employees2Head.csv\"\n\n# this file is having header and delimiter is comma (,), we can read this with read_csv method\nfh = pd.read_csv(\"dataset/Employees2Head.csv\")\nlen(fh) # of lines in file excluding header\n\nprint(fh)\n\n# we can read the same file with read_table method with passing an option sep=\nfh = pd.read_table(\"dataset/Employees2Head.csv\", sep=\",\")\nlen(fh)\n\n# let's check how to read a file without header\n!more \"dataset/Employees2.csv\"\n\nfh = pd.read_csv(\"dataset/Employees2.csv\", header=None)\nlen(fh)\n\nprint(fh) # check the column names, it've been assigned by pandas itself\n\n# we can assign file dataframe the column names\nfh.columns\n\nfh.columns = ['LNAME','FNAME','JOB TITLE','DEPARTMENT','EMPLOYEE ANNUAL SALARY','ESTIMATED ANNUAL SALARY MINUS FURLOUGHS'\n]\nprint(fh)\n\n# or we can assign the names while reading the files\nfh = pd.read_table(\"dataset/Employees2.csv\", header=None, sep=',', \n names=['LNAME','FNAME','JOB TITLE','DEPARTMENT','EMPLOYEE ANNUAL SALARY',\n 'ESTIMATED ANNUAL SALARY MINUS FURLOUGHS'])\nlen(fh)\n\nprint(fh)\n\n# In some cases, a table might not have a fixed delimiter, using whitespace or some other\n# pattern to separate fields. In these cases, you can pass a regular expression as a delimiter\n# for read_table.\n# pd.read_table('ch06/ex3.txt', sep='\\s+')\n\n# Skip the rows to read\nfh = pd.read_table(\"dataset/Employees2Head.csv\", sep=\",\", skiprows=[0,1,2])\nlen(fh) # total was 12 rows but skipped 3 rows", "Handling missing data while reading files", "!more \"dataset/Emp2HeadMiss.csv\"\n\n# reading the file\nfh = pd.read_csv(\"dataset/Emp2HeadMiss.csv\")\nprint(fh)\n\npd.isnull(fh) # TRUE denotes the NULL value\n\n# The na_values option can take either a list or set of strings to consider missing values\nfh = pd.read_csv(\"dataset/Emp2HeadMiss.csv\", na_values=['NULL'])\n\n# we can define NA values for each columns as well\nnaValues = {'LNAME':['NA', 'NaN', 'NULL', '|'], 'FNAME':['NULL']}\nfh = pd.read_csv(\"dataset/Emp2HeadMiss.csv\", na_values=naValues)\nprint(fh)", "read_csv /read_table function arguments\npath String indicating filesystem location, URL, or file-like object\nsep or delimiter Character sequence or regular expression to use to split fields in each row\nheader Row number to use as column names. Defaults to 0 (first row), but should be None if there is no header row\nindex_col Column numbers or names to use as the row index in the result. Can be a single name/number or a list of them for a hierarchical index\nnames List of column names for result, combine with header=None\nskiprows Number of rows at beginning of file to ignore or list of row numbers (starting from 0) to skip\nna_values Sequence of values to replace with NA\ncomment Character or characters to split comments off the end of lines\nparse_dates Attempt to parse data to datetime; False by default. If True, will attempt to parse all columns. Otherwise can specify a list of column numbers or name to parse. If element of list is tuple or list, will combine multiple columns together and parse to date (for example if date/time split across two columns)\nkeep_date_col If joining columns to parse date, drop the joined columns. Default True\nconverters Dict containing column number of name mapping to functions. For example {'foo': f} would apply the function f to all values in the 'foo' column\ndayfirst When parsing potentially ambiguous dates, treat as international format (e.g. 7/6/2012 -&gt; June 7, 2012). Default False\ndate_parser Function to use to parse dates\nnrows Number of rows to read from beginning of file\niterator Return a TextParser object for reading file piecemeal\nchunksize For iteration, size of file chunks\nskip_footer Number of lines to ignore at end of file\nverbose Print various parser output information, like the number of missing values placed in non-numeric columns\nencoding Text encoding for unicode. For example 'utf-8' for UTF-8 encoded text\nsqueeze If the parsed data only contains one column return a Series\nthousands Separator for thousands, e.g. ',' or '.'\nReading Text Files in Pieces", "fh = pd.read_csv(\"dataset/Employees.csv\")\nlen(fh)\n\nfh.info()\n\nfh.describe()\n\n# if want to read few lines from file\nfh = pd.read_csv(\"dataset/Employees.csv\", nrows=5)\nprint(fh)\n\n# To read out a file in pieces, specify a chunksize as a number of rows\nchunker = pd.read_csv(\"dataset/Employees.csv\", chunksize=1000)\nchunker\n\nline = 0\nfor data in chunker:\n line = line + 1\nprint(line)", "Writing Data Out to Text Format", "fh = pd.read_csv(\"dataset/Employees.csv\")\nlen(fh)\n\n# save the fh as csv\nfh.to_csv(\"dataset/Emp.csv\")\n\n# save the fh as excel\nfh.to_excel(\"dataset/Emp.xls\")\n\n# Other delimiters can be used\n# fh.to_csv(\"dataset/Emp.csv\", sep=\"|\")\n\n# Missing values appear as empty strings in the output. You might want to denote them\n# by some other sentinel value:\n# sentinel = ['NULL']\n# data.to_csv(sys.stdout, na_rep=sentinel)\n\n# With no other options specified, both the row and column labels are written. Both of\n# these can be disabled:\nfh.to_csv(\"dataset/Emp.csv\", header = False, index = False)\n\n# can write column subset as well\ncols = ['LNAME', 'FNAME']\nfh.to_csv(\"dataset/Emp.csv\", index = False, columns=cols)", "Save Series", "dates = pd.date_range('1/1/2000', periods=7)\nts = pd.Series(np.arange(7), index=dates)\nts.to_csv(\"dataset/times.psv\", sep=\"|\")\n\n!more \"dataset/times.psv\"\n\n# With a bit of wrangling (no header, first column as index), you can read a CSV version\n# of a Series with read_csv, but there is also a from_csv convenience method that makes\n# it a bit simpler:\npd.Series.from_csv('dataset/times.psv', parse_dates=True, sep=\"|\")", "Manually Working with Delimited Formats", "# import csv\nimport csv\nfh = open(\"dataset/Emp.csv\")\nreader = csv.reader(fh)\n\ncount=0\nfor line in reader:\n count = count+1\nprint(count)\n\nlines = list(csv.reader(open(\"dataset/Emp.csv\")))\nheader, values = lines[0], lines[1:]\nheader\n\ndata_dict = {h: v for h, v in zip(header, zip(*values))}\ndata_dict.keys()\n\n# Defining a new format with a different delimiter, string quoting convention, \n# or line terminator is done by defining a simple subclass of csv.Dialect\nf = open(\"dataset/times.psv\")\n\nclass my_dialect(csv.Dialect):\n lineterminator = '\\n'\n delimiter = '|'\n quoting = csv.QUOTE_NONE\n \nreader = csv.reader(f, dialect=my_dialect)\nprint(reader)\n\n# or we can define as\nreader = csv.reader(open(\"dataset/times.psv\"), delimiter = '|')\nfor line in reader:\n print(line)", "CSV dialect options\ndelimiter One-character string to separate fields. Defaults to ','.\nlineterminator Line terminator for writing, defaults to '\\r\\n'. Reader ignores this and recognizes cross-platform line terminators.\nquotechar Quote character for fields with special characters (like a delimiter). Default is '\"'.\nquoting Quoting convention. Options include csv.QUOTE_ALL (quote all fields),\n csv.QUOTE_MINIMAL (only fields with special characters like the delimiter),\n csv.QUOTE_NONNUMERIC, and csv.QUOTE_NON (no quoting). See Python’s documentation for full details. Defaults to QUOTE_MINIMAL.\nskipinitialspace Ignore whitespace after each delimiter. Default False.\ndoublequote How to handle quoting character inside a field. If True, it is doubled. \nescapechar String to escape the delimiter if quoting is set to csv.QUOTE_NONE. Disabled by default", "# To write delimited files manually, use csv.writer.\nwith open('dataset/mydata.csv', 'w') as f:\n writer = csv.writer(f, dialect=my_dialect)\n writer.writerow(('one', 'two', 'three'))\n writer.writerow(('1', '2', '3'))\n writer.writerow(('4', '5', '6'))\n writer.writerow(('7', '8', '9'))", "JSON Data", "obj = \"\"\"\n{\"name\": \"Wes\",\n \"places_lived\": [\"United States\", \"Spain\", \"Germany\"],\n \"pet\": null,\n \"siblings\": [{\"name\": \"Scott\", \"age\": 25, \"pet\": \"Zuko\"},\n {\"name\": \"Katie\", \"age\": 33, \"pet\": \"Cisco\"}]\n}\n\"\"\"\nobj\n\nimport json\ndata = json.loads(obj)\ndata\n\nasjson = json.dumps(data)\nasjson\n\nsiblings = pd.DataFrame(data['siblings'], columns=['name', 'age'])\nsiblings", "XML and HTML: Web Scraping", "# lxml pkg\nfrom lxml.html import parse\n# from urllib2 import urlopen # for python 2\nfrom urllib.request import urlopen\n\n# this will download some data from net\n#parsed = parse(urlopen('http://finance.yahoo.com/q/op?s=AAPL+Options'))\nparsed = parse(urlopen('http://finance.yahoo.com'))\n#parsed = parse(urlopen('http://www.omdbapi.com/'))\ndoc = parsed.getroot()\n\nprint(doc)\n\n# to fetch all hyperlinks <a\nlinks = doc.findall('.//a')\nlen(links)\n\nlnk = links[18]\nlnk.get('href')\n\nlnk.text_content()\n\n# to get all the urls in one liner\nurls = [lnk.get('href') for lnk in doc.findall('.//a')]\nprint(urls[:10])\n\n## Finding the tables in html \ntables = doc.findall('.//table')\nprint(len(tables))\n\ntable = tables[0]\nprint(table)\n\n# table will have only 1 table\n# get td tag\nrows = table.findall('.//tr')\nprint(rows)\n\n# For the header as well as the data rows, we want to extract the text from each cell; in\n# the case of the header these are th cells and td cells for the data:\ndef _unpack(row, kind='td'):\n elts = row.findall('.//%s' % kind)\n return [val.text_content() for val in elts]\n\n# printing table header th tag\n_unpack(rows[0], kind='th')\n\n# printing table data td tag\n_unpack(rows[0], kind='td')\n\n# combining all the code into one func\nfrom pandas.io.parsers import TextParser\ndef parse_options_data(table):\n rows = table.findall('.//tr')\n header = _unpack(rows[0], kind='th')\n data = [_unpack(r) for r in rows[1:]]\n return TextParser(data, names=header).get_chunk()\n\ndata = parse_options_data(table)\nprint(data)", "Parsing XML with lxml.objectify", "from lxml import objectify\nparsed = objectify.parse(open(\"dataset/Performance_MNR.xml\"))\nroot = parsed.getroot()\n\nprint(root)\n\ndata = []\nskip_fields = ['PARENT_SEQ', 'INDICATOR_SEQ',\n 'DESIRED_CHANGE', 'DECIMAL_PLACES']\nfor elt in root.INDICATOR:\n el_data = {}\n for child in elt.getchildren():\n if child.tag in skip_fields:\n continue\n el_data[child.tag] = child.pyval\n data.append(el_data)\n\nperf = pd.DataFrame(data)\n\nperf.head()" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
ES-DOC/esdoc-jupyterhub
notebooks/miroc/cmip6/models/miroc6/ocean.ipynb
gpl-3.0
[ "ES-DOC CMIP6 Model Properties - Ocean\nMIP Era: CMIP6\nInstitute: MIROC\nSource ID: MIROC6\nTopic: Ocean\nSub-Topics: Timestepping Framework, Advection, Lateral Physics, Vertical Physics, Uplow Boundaries, Boundary Forcing. \nProperties: 133 (101 required)\nModel descriptions: Model description details\nInitialized From: CMIP5:MIROC5 \nNotebook Help: Goto notebook help page\nNotebook Initialised: 2018-02-20 15:02:40\nDocument Setup\nIMPORTANT: to be executed each time you run the notebook", "# DO NOT EDIT ! \nfrom pyesdoc.ipython.model_topic import NotebookOutput \n\n# DO NOT EDIT ! \nDOC = NotebookOutput('cmip6', 'miroc', 'miroc6', 'ocean')", "Document Authors\nSet document authors", "# Set as follows: DOC.set_author(\"name\", \"email\") \n# TODO - please enter value(s)", "Document Contributors\nSpecify document contributors", "# Set as follows: DOC.set_contributor(\"name\", \"email\") \n# TODO - please enter value(s)", "Document Publication\nSpecify document publication status", "# Set publication status: \n# 0=do not publish, 1=publish. \nDOC.set_publication_status(0)", "Document Table of Contents\n1. Key Properties\n2. Key Properties --&gt; Seawater Properties\n3. Key Properties --&gt; Bathymetry\n4. Key Properties --&gt; Nonoceanic Waters\n5. Key Properties --&gt; Software Properties\n6. Key Properties --&gt; Resolution\n7. Key Properties --&gt; Tuning Applied\n8. Key Properties --&gt; Conservation\n9. Grid\n10. Grid --&gt; Discretisation --&gt; Vertical\n11. Grid --&gt; Discretisation --&gt; Horizontal\n12. Timestepping Framework\n13. Timestepping Framework --&gt; Tracers\n14. Timestepping Framework --&gt; Baroclinic Dynamics\n15. Timestepping Framework --&gt; Barotropic\n16. Timestepping Framework --&gt; Vertical Physics\n17. Advection\n18. Advection --&gt; Momentum\n19. Advection --&gt; Lateral Tracers\n20. Advection --&gt; Vertical Tracers\n21. Lateral Physics\n22. Lateral Physics --&gt; Momentum --&gt; Operator\n23. Lateral Physics --&gt; Momentum --&gt; Eddy Viscosity Coeff\n24. Lateral Physics --&gt; Tracers\n25. Lateral Physics --&gt; Tracers --&gt; Operator\n26. Lateral Physics --&gt; Tracers --&gt; Eddy Diffusity Coeff\n27. Lateral Physics --&gt; Tracers --&gt; Eddy Induced Velocity\n28. Vertical Physics\n29. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Details\n30. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Tracers\n31. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Momentum\n32. Vertical Physics --&gt; Interior Mixing --&gt; Details\n33. Vertical Physics --&gt; Interior Mixing --&gt; Tracers\n34. Vertical Physics --&gt; Interior Mixing --&gt; Momentum\n35. Uplow Boundaries --&gt; Free Surface\n36. Uplow Boundaries --&gt; Bottom Boundary Layer\n37. Boundary Forcing\n38. Boundary Forcing --&gt; Momentum --&gt; Bottom Friction\n39. Boundary Forcing --&gt; Momentum --&gt; Lateral Friction\n40. Boundary Forcing --&gt; Tracers --&gt; Sunlight Penetration\n41. Boundary Forcing --&gt; Tracers --&gt; Fresh Water Forcing \n1. Key Properties\nOcean key properties\n1.1. Model Overview\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOverview of ocean model.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.model_overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "1.2. Model Name\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nName of ocean model code (NEMO 3.6, MOM 5.0,...)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.model_name') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "1.3. Model Family\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of ocean model.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.model_family') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"OGCM\" \n# \"slab ocean\" \n# \"mixed layer ocean\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"OGCM\") \n", "1.4. Basic Approximations\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N\nBasic approximations made in the ocean.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.basic_approximations') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Primitive equations\" \n# \"Non-hydrostatic\" \n# \"Boussinesq\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Boussinesq\") \nDOC.set_value(\"Primitive equations\") \n", "1.5. Prognostic Variables\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N\nList of prognostic variables in the ocean component.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.prognostic_variables') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Potential temperature\" \n# \"Conservative temperature\" \n# \"Salinity\" \n# \"U-velocity\" \n# \"V-velocity\" \n# \"W-velocity\" \n# \"SSH\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Potential temperature\") \nDOC.set_value(\"SSH\") \nDOC.set_value(\"Salinity\") \nDOC.set_value(\"U-velocity\") \nDOC.set_value(\"V-velocity\") \n", "2. Key Properties --&gt; Seawater Properties\nPhysical properties of seawater in ocean\n2.1. Eos Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of EOS for sea water", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.seawater_properties.eos_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Linear\" \n# \"Wright, 1997\" \n# \"Mc Dougall et al.\" \n# \"Jackett et al. 2006\" \n# \"TEOS 2010\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Other: mcdougall et al.\") \n", "2.2. Eos Functional Temp\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nTemperature used in EOS for sea water", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.seawater_properties.eos_functional_temp') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Potential temperature\" \n# \"Conservative temperature\" \n# TODO - please enter value(s)\n", "2.3. Eos Functional Salt\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nSalinity used in EOS for sea water", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.seawater_properties.eos_functional_salt') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Practical salinity Sp\" \n# \"Absolute salinity Sa\" \n# TODO - please enter value(s)\n", "2.4. Eos Functional Depth\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDepth or pressure used in EOS for sea water ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.seawater_properties.eos_functional_depth') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Pressure (dbars)\" \n# \"Depth (meters)\" \n# TODO - please enter value(s)\n", "2.5. Ocean Freezing Point\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nEquation used to compute the freezing point (in deg C) of seawater, as a function of salinity and pressure", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.seawater_properties.ocean_freezing_point') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"TEOS 2010\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Other: varying\") \n", "2.6. Ocean Specific Heat\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nSpecific heat in ocean (cpocean) in J/(kg K)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.seawater_properties.ocean_specific_heat') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "2.7. Ocean Reference Density\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nBoussinesq reference density (rhozero) in kg / m3", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.seawater_properties.ocean_reference_density') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "3. Key Properties --&gt; Bathymetry\nProperties of bathymetry in ocean\n3.1. Reference Dates\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nReference date of bathymetry", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.bathymetry.reference_dates') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Present day\" \n# \"21000 years BP\" \n# \"6000 years BP\" \n# \"LGM\" \n# \"Pliocene\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Present day\") \n", "3.2. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs the bathymetry fixed in time in the ocean ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.bathymetry.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \nDOC.set_value(True) \n", "3.3. Ocean Smoothing\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe any smoothing or hand editing of bathymetry in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.bathymetry.ocean_smoothing') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "3.4. Source\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe source of bathymetry in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.bathymetry.source') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "4. Key Properties --&gt; Nonoceanic Waters\nNon oceanic waters treatement in ocean\n4.1. Isolated Seas\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nDescribe if/how isolated seas is performed", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.nonoceanic_waters.isolated_seas') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"Yes\") \n", "4.2. River Mouth\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nDescribe if/how river mouth mixing or estuaries specific treatment is performed", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.nonoceanic_waters.river_mouth') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"N/A\") \n", "5. Key Properties --&gt; Software Properties\nSoftware properties of ocean code\n5.1. Repository\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nLocation of code for this component.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.software_properties.repository') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "5.2. Code Version\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nCode version identifier.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.software_properties.code_version') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "5.3. Code Languages\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N\nCode language(s).", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.software_properties.code_languages') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "6. Key Properties --&gt; Resolution\nResolution in the ocean grid\n6.1. Name\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nThis is a string usually used by the modelling group to describe the resolution of this grid, e.g. ORCA025, N512L180, T512L70 etc.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.resolution.name') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "6.2. Canonical Horizontal Resolution\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nExpression quoted for gross comparisons of resolution, eg. 50km or 0.1 degrees etc.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.resolution.canonical_horizontal_resolution') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "6.3. Range Horizontal Resolution\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nRange of horizontal resolution with spatial details, eg. 50(Equator)-100km or 0.1-0.5 degrees etc.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.resolution.range_horizontal_resolution') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "6.4. Number Of Horizontal Gridpoints\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nTotal number of horizontal (XY) points (or degrees of freedom) on computational grid.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.resolution.number_of_horizontal_gridpoints') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "6.5. Number Of Vertical Levels\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nNumber of vertical levels resolved on computational grid.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.resolution.number_of_vertical_levels') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "6.6. Is Adaptive Grid\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDefault is False. Set true if grid resolution changes during execution.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.resolution.is_adaptive_grid') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "6.7. Thickness Level 1\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nThickness of first surface ocean level (in meters)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.resolution.thickness_level_1') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "7. Key Properties --&gt; Tuning Applied\nTuning methodology for ocean component\n7.1. Description\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nGeneral overview description of tuning: explain and motivate the main targets and metrics retained. &amp;Document the relative weight given to climate performance metrics versus process oriented metrics, &amp;and on the possible conflicts with parameterization level tuning. In particular describe any struggle &amp;with a parameter value that required pushing it to its limits to solve a particular model deficiency.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.tuning_applied.description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "7.2. Global Mean Metrics Used\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N\nList set of metrics of the global mean state used in tuning model/component", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.tuning_applied.global_mean_metrics_used') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "7.3. Regional Metrics Used\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N\nList of regional metrics of mean state (e.g THC, AABW, regional means etc) used in tuning model/component", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.tuning_applied.regional_metrics_used') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "7.4. Trend Metrics Used\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N\nList observed trend metrics used in tuning model/component", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.tuning_applied.trend_metrics_used') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "8. Key Properties --&gt; Conservation\nConservation in the ocean component\n8.1. Description\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nBrief description of conservation methodology", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.conservation.description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "8.2. Scheme\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N\nProperties conserved in the ocean by the numerical schemes", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.conservation.scheme') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Energy\" \n# \"Enstrophy\" \n# \"Salt\" \n# \"Volume of ocean\" \n# \"Momentum\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "8.3. Consistency Properties\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nAny additional consistency properties (energy conversion, pressure gradient discretisation, ...)?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.conservation.consistency_properties') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "8.4. Corrected Conserved Prognostic Variables\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nSet of variables which are conserved by more than the numerical scheme alone.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.conservation.corrected_conserved_prognostic_variables') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "8.5. Was Flux Correction Used\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nDoes conservation involve flux correction ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.key_properties.conservation.was_flux_correction_used') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "9. Grid\nOcean grid\n9.1. Overview\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOverview of grid in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.grid.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "10. Grid --&gt; Discretisation --&gt; Vertical\nProperties of vertical discretisation in ocean\n10.1. Coordinates\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of vertical coordinates in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.grid.discretisation.vertical.coordinates') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Z-coordinate\" \n# \"Z*-coordinate\" \n# \"S-coordinate\" \n# \"Isopycnic - sigma 0\" \n# \"Isopycnic - sigma 2\" \n# \"Isopycnic - sigma 4\" \n# \"Isopycnic - other\" \n# \"Hybrid / Z+S\" \n# \"Hybrid / Z+isopycnic\" \n# \"Hybrid / other\" \n# \"Pressure referenced (P)\" \n# \"P*\" \n# \"Z**\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "10.2. Partial Steps\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nUsing partial steps with Z or Z vertical coordinate in ocean ?*", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.grid.discretisation.vertical.partial_steps') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "11. Grid --&gt; Discretisation --&gt; Horizontal\nType of horizontal discretisation scheme in ocean\n11.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nHorizontal grid type", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.grid.discretisation.horizontal.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Lat-lon\" \n# \"Rotated north pole\" \n# \"Two north poles (ORCA-style)\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "11.2. Staggering\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nHorizontal grid staggering type", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.grid.discretisation.horizontal.staggering') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Arakawa B-grid\" \n# \"Arakawa C-grid\" \n# \"Arakawa E-grid\" \n# \"N/a\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "11.3. Scheme\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nHorizontal discretisation scheme in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.grid.discretisation.horizontal.scheme') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Finite difference\" \n# \"Finite volumes\" \n# \"Finite elements\" \n# \"Unstructured grid\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Other: finite differences\") \n", "12. Timestepping Framework\nOcean Timestepping Framework\n12.1. Overview\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOverview of time stepping in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.timestepping_framework.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "12.2. Diurnal Cycle\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDiurnal cycle type", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.timestepping_framework.diurnal_cycle') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"None\" \n# \"Via coupling\" \n# \"Specific treatment\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "13. Timestepping Framework --&gt; Tracers\nProperties of tracers time stepping in ocean\n13.1. Scheme\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nTracers time stepping scheme", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.timestepping_framework.tracers.scheme') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Leap-frog + Asselin filter\" \n# \"Leap-frog + Periodic Euler\" \n# \"Predictor-corrector\" \n# \"Runge-Kutta 2\" \n# \"AM3-LF\" \n# \"Forward-backward\" \n# \"Forward operator\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Forward-backward\") \n", "13.2. Time Step\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nTracers time step (in seconds)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.timestepping_framework.tracers.time_step') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "14. Timestepping Framework --&gt; Baroclinic Dynamics\nBaroclinic dynamics in ocean\n14.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nBaroclinic dynamics type", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.timestepping_framework.baroclinic_dynamics.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Preconditioned conjugate gradient\" \n# \"Sub cyling\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "14.2. Scheme\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nBaroclinic dynamics scheme", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.timestepping_framework.baroclinic_dynamics.scheme') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Leap-frog + Asselin filter\" \n# \"Leap-frog + Periodic Euler\" \n# \"Predictor-corrector\" \n# \"Runge-Kutta 2\" \n# \"AM3-LF\" \n# \"Forward-backward\" \n# \"Forward operator\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "14.3. Time Step\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nBaroclinic time step (in seconds)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.timestepping_framework.baroclinic_dynamics.time_step') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "15. Timestepping Framework --&gt; Barotropic\nBarotropic time stepping in ocean\n15.1. Splitting\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nTime splitting method", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.timestepping_framework.barotropic.splitting') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"None\" \n# \"split explicit\" \n# \"implicit\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "15.2. Time Step\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nBarotropic time step (in seconds)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.timestepping_framework.barotropic.time_step') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "16. Timestepping Framework --&gt; Vertical Physics\nVertical physics time stepping in ocean\n16.1. Method\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDetails of vertical time stepping in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.timestepping_framework.vertical_physics.method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "17. Advection\nOcean advection\n17.1. Overview\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOverview of advection in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.advection.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "18. Advection --&gt; Momentum\nProperties of lateral momemtum advection scheme in ocean\n18.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of lateral momemtum advection scheme in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.advection.momentum.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Flux form\" \n# \"Vector form\" \nDOC.set_value(\"Vector form\") \n", "18.2. Scheme Name\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nName of ocean momemtum advection scheme", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.advection.momentum.scheme_name') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"Second-order, energy-preserving\") \n", "18.3. ALE\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nUsing ALE for vertical advection ? (if vertical coordinates are sigma)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.advection.momentum.ALE') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "19. Advection --&gt; Lateral Tracers\nProperties of lateral tracer advection scheme in ocean\n19.1. Order\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOrder of lateral tracer advection scheme in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.advection.lateral_tracers.order') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "19.2. Flux Limiter\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nMonotonic flux limiter for lateral tracer advection scheme in ocean ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.advection.lateral_tracers.flux_limiter') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \nDOC.set_value(True) \n", "19.3. Effective Order\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nEffective order of limited lateral tracer advection scheme in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.advection.lateral_tracers.effective_order') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "19.4. Name\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescriptive text for lateral tracer advection scheme in ocean (e.g. MUSCL, PPM-H5, PRATHER,...)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.advection.lateral_tracers.name') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"Prather 2nd moment (PSOM)\") \n", "19.5. Passive Tracers\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N\nPassive tracers advected", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.advection.lateral_tracers.passive_tracers') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Ideal age\" \n# \"CFC 11\" \n# \"CFC 12\" \n# \"SF6\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "19.6. Passive Tracers Advection\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIs advection of passive tracers different than active ? if so, describe.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.advection.lateral_tracers.passive_tracers_advection') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "20. Advection --&gt; Vertical Tracers\nProperties of vertical tracer advection scheme in ocean\n20.1. Name\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescriptive text for vertical tracer advection scheme in ocean (e.g. MUSCL, PPM-H5, PRATHER,...)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.advection.vertical_tracers.name') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"Prather 2nd moment (PSOM)\") \n", "20.2. Flux Limiter\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nMonotonic flux limiter for vertical tracer advection scheme in ocean ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.advection.vertical_tracers.flux_limiter') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \nDOC.set_value(True) \n", "21. Lateral Physics\nOcean lateral physics\n21.1. Overview\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOverview of lateral physics in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "21.2. Scheme\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of transient eddy representation in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.scheme') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"None\" \n# \"Eddy active\" \n# \"Eddy admitting\" \n# TODO - please enter value(s)\n", "22. Lateral Physics --&gt; Momentum --&gt; Operator\nProperties of lateral physics operator for momentum in ocean\n22.1. Direction\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDirection of lateral physics momemtum scheme in the ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.momentum.operator.direction') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Horizontal\" \n# \"Isopycnal\" \n# \"Isoneutral\" \n# \"Geopotential\" \n# \"Iso-level\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Horizontal\") \n", "22.2. Order\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOrder of lateral physics momemtum scheme in the ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.momentum.operator.order') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Harmonic\" \n# \"Bi-harmonic\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Harmonic\") \n", "22.3. Discretisation\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDiscretisation of lateral physics momemtum scheme in the ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.momentum.operator.discretisation') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Second order\" \n# \"Higher order\" \n# \"Flux limiter\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Second order\") \n", "23. Lateral Physics --&gt; Momentum --&gt; Eddy Viscosity Coeff\nProperties of eddy viscosity coeff in lateral physics momemtum scheme in the ocean\n23.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nLateral physics momemtum eddy viscosity coeff type in the ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Constant\" \n# \"Space varying\" \n# \"Time + space varying (Smagorinsky)\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Space varying\") \n", "23.2. Constant Coefficient\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf constant, value of eddy viscosity coeff in lateral physics momemtum scheme (in m2/s)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.constant_coefficient') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "23.3. Variable Coefficient\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf space-varying, describe variations of eddy viscosity coeff in lateral physics momemtum scheme", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.variable_coefficient') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"Latitude\") \n", "23.4. Coeff Background\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe background eddy viscosity coeff in lateral physics momemtum scheme (give values in m2/s)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.coeff_background') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"N/A\") \n", "23.5. Coeff Backscatter\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs there backscatter in eddy viscosity coeff in lateral physics momemtum scheme ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.coeff_backscatter') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "24. Lateral Physics --&gt; Tracers\nProperties of lateral physics for tracers in ocean\n24.1. Mesoscale Closure\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs there a mesoscale closure in the lateral physics tracers scheme ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.mesoscale_closure') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \nDOC.set_value(True) \n", "24.2. Submesoscale Mixing\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs there a submesoscale mixing parameterisation (i.e Fox-Kemper) in the lateral physics tracers scheme ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.submesoscale_mixing') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "25. Lateral Physics --&gt; Tracers --&gt; Operator\nProperties of lateral physics operator for tracers in ocean\n25.1. Direction\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDirection of lateral physics tracers scheme in the ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.operator.direction') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Horizontal\" \n# \"Isopycnal\" \n# \"Isoneutral\" \n# \"Geopotential\" \n# \"Iso-level\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Isopycnal\") \n", "25.2. Order\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOrder of lateral physics tracers scheme in the ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.operator.order') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Harmonic\" \n# \"Bi-harmonic\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Harmonic\") \n", "25.3. Discretisation\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDiscretisation of lateral physics tracers scheme in the ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.operator.discretisation') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Second order\" \n# \"Higher order\" \n# \"Flux limiter\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Other: flux limited\") \n", "26. Lateral Physics --&gt; Tracers --&gt; Eddy Diffusity Coeff\nProperties of eddy diffusity coeff in lateral physics tracers scheme in the ocean\n26.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nLateral physics tracers eddy diffusity coeff type in the ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Constant\" \n# \"Space varying\" \n# \"Time + space varying (Smagorinsky)\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Space varying\") \n", "26.2. Constant Coefficient\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf constant, value of eddy diffusity coeff in lateral physics tracers scheme (in m2/s)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.constant_coefficient') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "26.3. Variable Coefficient\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf space-varying, describe variations of eddy diffusity coeff in lateral physics tracers scheme", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.variable_coefficient') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"Latitude\") \n", "26.4. Coeff Background\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe background eddy diffusity coeff in lateral physics tracers scheme (give values in m2/s)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.coeff_background') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \nDOC.set_value(1000) \n", "26.5. Coeff Backscatter\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs there backscatter in eddy diffusity coeff in lateral physics tracers scheme ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.coeff_backscatter') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "27. Lateral Physics --&gt; Tracers --&gt; Eddy Induced Velocity\nProperties of eddy induced velocity (EIV) in lateral physics tracers scheme in the ocean\n27.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of EIV in lateral physics tracers in the ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_induced_velocity.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"GM\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"GM\") \n", "27.2. Constant Val\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf EIV scheme for tracers is constant, specify coefficient value (M2/s)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_induced_velocity.constant_val') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \nDOC.set_value(300) \n", "27.3. Flux Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of EIV flux (advective or skew)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_induced_velocity.flux_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"Skew flux\") \n", "27.4. Added Diffusivity\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of EIV added diffusivity (constant, flow dependent or none)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_induced_velocity.added_diffusivity') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "28. Vertical Physics\nOcean Vertical Physics\n28.1. Overview\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOverview of vertical physics in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "29. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Details\nProperties of vertical physics in ocean\n29.1. Langmuir Cells Mixing\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs there Langmuir cells mixing in upper ocean ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.details.langmuir_cells_mixing') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "30. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Tracers\n*Properties of boundary layer (BL) mixing on tracers in the ocean *\n30.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of boundary layer mixing for tracers in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.tracers.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Constant value\" \n# \"Turbulent closure - TKE\" \n# \"Turbulent closure - KPP\" \n# \"Turbulent closure - Mellor-Yamada\" \n# \"Turbulent closure - Bulk Mixed Layer\" \n# \"Richardson number dependent - PP\" \n# \"Richardson number dependent - KT\" \n# \"Imbeded as isopycnic vertical coordinate\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Turbulent closure - TKE\") \n", "30.2. Closure Order\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf turbulent BL mixing of tracers, specific order of closure (0, 1, 2.5, 3)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.tracers.closure_order') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "30.3. Constant\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf constant BL mixing of tracers, specific coefficient (m2/s)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.tracers.constant') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "30.4. Background\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nBackground BL mixing of tracers coefficient, (schema and value in m2/s - may by none)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.tracers.background') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"Tsujino type\") \n", "31. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Momentum\n*Properties of boundary layer (BL) mixing on momentum in the ocean *\n31.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of boundary layer mixing for momentum in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.momentum.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Constant value\" \n# \"Turbulent closure - TKE\" \n# \"Turbulent closure - KPP\" \n# \"Turbulent closure - Mellor-Yamada\" \n# \"Turbulent closure - Bulk Mixed Layer\" \n# \"Richardson number dependent - PP\" \n# \"Richardson number dependent - KT\" \n# \"Imbeded as isopycnic vertical coordinate\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Turbulent closure - TKE\") \n", "31.2. Closure Order\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf turbulent BL mixing of momentum, specific order of closure (0, 1, 2.5, 3)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.momentum.closure_order') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "31.3. Constant\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf constant BL mixing of momentum, specific coefficient (m2/s)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.momentum.constant') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "31.4. Background\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nBackground BL mixing of momentum coefficient, (schema and value in m2/s - may by none)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.momentum.background') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"1e-4 [m^2/s]\") \n", "32. Vertical Physics --&gt; Interior Mixing --&gt; Details\n*Properties of interior mixing in the ocean *\n32.1. Convection Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of vertical convection in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.details.convection_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Non-penetrative convective adjustment\" \n# \"Enhanced vertical diffusion\" \n# \"Included in turbulence closure\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Non-penetrative convective adjustment\") \n", "32.2. Tide Induced Mixing\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe how tide induced mixing is modelled (barotropic, baroclinic, none)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.details.tide_induced_mixing') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "32.3. Double Diffusion\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs there double diffusion", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.details.double_diffusion') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "32.4. Shear Mixing\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs there interior shear mixing", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.details.shear_mixing') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "33. Vertical Physics --&gt; Interior Mixing --&gt; Tracers\n*Properties of interior mixing on tracers in the ocean *\n33.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of interior mixing for tracers in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.tracers.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Constant value\" \n# \"Turbulent closure / TKE\" \n# \"Turbulent closure - Mellor-Yamada\" \n# \"Richardson number dependent - PP\" \n# \"Richardson number dependent - KT\" \n# \"Imbeded as isopycnic vertical coordinate\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Other: constant values\") \n", "33.2. Constant\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf constant interior mixing of tracers, specific coefficient (m2/s)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.tracers.constant') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "33.3. Profile\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs the background interior mixing using a vertical profile for tracers (i.e is NOT constant) ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.tracers.profile') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "33.4. Background\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nBackground interior mixing of tracers coefficient, (schema and value in m2/s - may by none)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.tracers.background') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "34. Vertical Physics --&gt; Interior Mixing --&gt; Momentum\n*Properties of interior mixing on momentum in the ocean *\n34.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of interior mixing for momentum in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.momentum.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Constant value\" \n# \"Turbulent closure / TKE\" \n# \"Turbulent closure - Mellor-Yamada\" \n# \"Richardson number dependent - PP\" \n# \"Richardson number dependent - KT\" \n# \"Imbeded as isopycnic vertical coordinate\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Other: constant values\") \n", "34.2. Constant\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf constant interior mixing of momentum, specific coefficient (m2/s)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.momentum.constant') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "34.3. Profile\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs the background interior mixing using a vertical profile for momentum (i.e is NOT constant) ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.momentum.profile') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "34.4. Background\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nBackground interior mixing of momentum coefficient, (schema and value in m2/s - may by none)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.momentum.background') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"1e-4 [m^2/s]\") \n", "35. Uplow Boundaries --&gt; Free Surface\nProperties of free surface in ocean\n35.1. Overview\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOverview of free surface in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.uplow_boundaries.free_surface.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "35.2. Scheme\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nFree surface scheme in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.uplow_boundaries.free_surface.scheme') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Linear implicit\" \n# \"Linear filtered\" \n# \"Linear semi-explicit\" \n# \"Non-linear implicit\" \n# \"Non-linear filtered\" \n# \"Non-linear semi-explicit\" \n# \"Fully explicit\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Other: linear split-explicit\") \n", "35.3. Embeded Seaice\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs the sea-ice embeded in the ocean model (instead of levitating) ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.uplow_boundaries.free_surface.embeded_seaice') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n", "36. Uplow Boundaries --&gt; Bottom Boundary Layer\nProperties of bottom boundary layer in ocean\n36.1. Overview\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOverview of bottom boundary layer in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.uplow_boundaries.bottom_boundary_layer.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "36.2. Type Of Bbl\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of bottom boundary layer in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.uplow_boundaries.bottom_boundary_layer.type_of_bbl') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Diffusive\" \n# \"Acvective\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Other: advective\") \n", "36.3. Lateral Mixing Coef\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nIf bottom BL is diffusive, specify value of lateral mixing coefficient (in m2/s)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.uplow_boundaries.bottom_boundary_layer.lateral_mixing_coef') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n", "36.4. Sill Overflow\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe any specific treatment of sill overflows", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.uplow_boundaries.bottom_boundary_layer.sill_overflow') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"No specific treatment\") \n", "37. Boundary Forcing\nOcean boundary forcing\n37.1. Overview\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nOverview of boundary forcing in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "37.2. Surface Pressure\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe how surface pressure is transmitted to ocean (via sea-ice, nothing specific,...)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.surface_pressure') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "37.3. Momentum Flux Correction\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nDescribe any type of ocean surface momentum flux correction and, if applicable, how it is applied and where.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.momentum_flux_correction') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \nDOC.set_value(\"No\") \n", "37.4. Tracers Flux Correction\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nDescribe any type of ocean surface tracers flux correction and, if applicable, how it is applied and where.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.tracers_flux_correction') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "37.5. Wave Effects\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe if/how wave effects are modelled at ocean surface.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.wave_effects') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "37.6. River Runoff Budget\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe how river runoff from land surface is routed to ocean and any global adjustment done.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.river_runoff_budget') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "37.7. Geothermal Heating\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nDescribe if/how geothermal heating is present at ocean bottom.", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.geothermal_heating') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "38. Boundary Forcing --&gt; Momentum --&gt; Bottom Friction\nProperties of momentum bottom friction in ocean\n38.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of momentum bottom friction in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.momentum.bottom_friction.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Linear\" \n# \"Non-linear\" \n# \"Non-linear (drag function of speed of tides)\" \n# \"Constant drag coefficient\" \n# \"None\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"Constant drag coefficient\") \n", "39. Boundary Forcing --&gt; Momentum --&gt; Lateral Friction\nProperties of momentum lateral friction in ocean\n39.1. Type\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of momentum lateral friction in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.momentum.lateral_friction.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"None\" \n# \"Free-slip\" \n# \"No-slip\" \n# \"Other: [Please specify]\" \nDOC.set_value(\"No-slip\") \n", "40. Boundary Forcing --&gt; Tracers --&gt; Sunlight Penetration\nProperties of sunlight penetration scheme in ocean\n40.1. Scheme\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of sunlight penetration scheme in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.tracers.sunlight_penetration.scheme') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"1 extinction depth\" \n# \"2 extinction depth\" \n# \"3 extinction depth\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "40.2. Ocean Colour\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nIs the ocean sunlight penetration scheme ocean colour dependent ?", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.tracers.sunlight_penetration.ocean_colour') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \nDOC.set_value(True) \n", "40.3. Extinction Depth\nIs Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1\nDescribe and list extinctions depths for sunlight penetration scheme (if applicable).", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.tracers.sunlight_penetration.extinction_depth') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "41. Boundary Forcing --&gt; Tracers --&gt; Fresh Water Forcing\nProperties of surface fresh water forcing in ocean\n41.1. From Atmopshere\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of surface fresh water forcing from atmos in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.tracers.fresh_water_forcing.from_atmopshere') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Freshwater flux\" \n# \"Virtual salt flux\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "41.2. From Sea Ice\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of surface fresh water forcing from sea-ice in ocean", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.tracers.fresh_water_forcing.from_sea_ice') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Freshwater flux\" \n# \"Virtual salt flux\" \n# \"Real salt flux\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n", "41.3. Forced Mode Restoring\nIs Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1\nType of surface salinity restoring in forced mode (OMIP)", "# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.ocean.boundary_forcing.tracers.fresh_water_forcing.forced_mode_restoring') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n", "©2017 ES-DOC" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
shumway/srt_bootcamp
SymPyExample.ipynb
mit
[ "SymPy\nThe SymPy package is useful for symbolic algebra, much like the commercial software Mathematica.\nWe won't make much use of SymPy during the boot camp, but it is definitely useful to know about\nfor mathematics courses.", "import sympy as sp\nsp.init_printing()", "Symbols and Expressions\nWe'll define x and y to be sympy symbols, then do some symbolic algebra.", "x, y = sp.symbols(\"x y\")\n\nexpression = (x+y)**4\n\nexpression\n\nsp.expand(expression)\n\nexpression = 8*x**2 + 26*x*y + 15*y**2\n\nexpression\n\nsp.factor(expression)\n\nexpression - 20 *x*y - 14*y**2\n\nsp.factor(expression - 20*x*y - 14*y**2)", "Lambdify: Making python functions from sympy expressions", "expression\n\nf = sp.lambdify((x,y), expression, 'numpy')\n\nf(3,4)\n\n8 * 3**2 + 26 * 3 * 4 + 15 * 4**2", "Calculus\nYou can use sympy to perform symbolic integration or differentiation.", "expression = 5*x**2 * sp.sin(3*x**3)\n\nexpression\n\nexpression.diff(x)\n\nexpression = sp.cos(x)\n\nexpression.integrate(x)\n\nexpression.integrate((x, 0, sp.pi / 2))", "You can also create unevalated integrals or derivatives. These can later be evaluated with their doit methods.", "deriv = sp.Derivative(expression)\n\nderiv\n\nderiv.doit()\n\ninte = sp.Integral(expression, (x, 0, sp.pi / 2))\n\ninte\n\ninte.doit()" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
evanmiltenburg/python-for-text-analysis
Chapters-colab/Chapter_12_Importing_external_modules.ipynb
apache-2.0
[ "<a href=\"https://colab.research.google.com/github/cltl/python-for-text-analysis/blob/colab/Chapters-colab/Chapter_12_Importing_external_modules.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "%%capture\n!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Data.zip\n!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/images.zip\n!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Extra_Material.zip\n\n!unzip Data.zip -d ../\n!unzip images.zip -d ./\n!unzip Extra_Material.zip -d ../\n\n!rm Data.zip\n!rm Extra_Material.zip\n!rm images.zip", "Chapter 12: Importing external modules\nWe use some materials from this other Python course.\nMost of the functionality we have used thus far is built into the Python language itself. Now we have also learned how to write our own functions. Often, however, you need to use external modules in your code. A lot of external modules are already available in the Python Standard Library, for a wide variety of tasks. There are also countless third-party providers of Python modules.\nAt the end of this chapter, you will be able to:\n\nimport an entire module\nimport a specific function from a module\nuse dir and help to get information about a module or function\nimport a few commonly used modules: random, datetime, and requests\n\nIf you want to learn more about these topics, you might find the following links useful:\n* Tutorial: The import statement\n* Video: OS Module - Use Underlying Operating System Functionality\nIf you have questions about this chapter, please contact us (cltl.python.course@gmail.com).\n1. Importing a module or a function\nPython modules\nA Python module is a Python file (i.e., a file ending in .py) which contains function definitions and statements. You can already write one yourself! (More about this in the next chapter.)\nSome modules are part of the Python standard library and contain useful functions. You can import these modules and use the functions as explained below.\nMore on modules can be found here: https://docs.python.org/3/tutorial/modules.html\nTo use an external module in your code, you need to import it explicitely. Consider, for example, the module random from the standard library, which contains functions for generating random numbers:", "import random\nprint(random.randint(0, 100))", "Note the syntax used: using the dot, we indicate that our machine should look for the randint() method inside the random module we just imported. You can import an entire module or import only a specific function in the module. We could also have imported the (single) method we needed as follows:", "from random import randint\nprint(randint(0, 100))", "In this case we wouldn't have to specify where our machine should find the randint() function: note that we don't need to use the module random in the function call in this case.\n2. Getting help\nWe might not understand how an external method works, or what input it needs, or what are the output values it returns. In that case, we can use help() (just as we did with functions and methods):", "help(randint)", "If we like the randint() method, we might also be interested which other methods are offered in the random package. We can use dir() for this:", "dir(random)", "You can also (temporarily) change the names of the functions you import:", "from random import randint as random_number\nprint(random_number(0, 100))", "If you want to import the entire module, it works the same way (using the syntax we have already seen above). Changing the name can be useful if we want to shorten it (as shown below).", "import random as rn\nprint(rn.randint(0,4))", "3. Other useful modules\nThere are plenty of very useful modules out there, so it is a good practice to check if someone has already created a module for a task that you are facing. Here, we'll show\n\ndatetime (module to manipulate dates)\nrequests (module to download the content of a webpage)\n\n3.1 Datetime", "import datetime\n\nprint(datetime.datetime.now())", "We can decipher the output ourselves: the first value is the current year, the second the current month, then day, hour, minute, etc. We can also see what Python tells us about this result:", "help(datetime.datetime.now)", "3.2 Requests", "import requests\na=requests.get(\"https://tae898.github.io\")\nprint(a.content)", "Don't worry too much about the response: it is a format called HTML (which is basically behind all web pages) and one would need to write some more code to extract the useful information from it. But: it is really impressive that we can retrieve any webpage from the web with just three lines of code! If you want to have a quick look at how to extract content, feel free to check out the beautifulsoup module. \nSo, how does one find a useful module for a specific task? Answer: Google it ;-)\nExercises\nExercise 1: \nCheck which arguments should be supplied to the random.sample() method and what is their intention. Then call this function with different arguments.", "# your code here", "Exercise 2\nFigure out what the os module does and think about tasks it could be used for.", "# play around here" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
ceos-seo/data_cube_notebooks
notebooks/Data_Challenge/Weather.ipynb
apache-2.0
[ "2022 EY Challenge - Weather Data\nThis notebook is used to create a weather dataset from <b>\"TerraClimate\"</b>. These data parameters, or their variability, can be used as \"predictor variables\" to relate to species samples. TerraClimate is a dataset of monthly climate and climatic water balance for global terrestrial surfaces from 1958-2019. These data provide important inputs for ecological and hydrological studies at global scales that require high spatial resolution and time-varying data. All data have monthly temporal resolution and a 4-km (0.036 degree) spatial resolution. The data can be found in the MS Planetary Computer catalog: https://planetarycomputer.microsoft.com/dataset/terraclimate", "# Supress Warnings \nimport warnings\nwarnings.filterwarnings('ignore')\n\n# Import common GIS tools\nimport numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport rasterio.features\nimport folium\nimport math\n\n# Import Planetary Computer tools\nimport pystac_client\nimport planetary_computer", "Define the analysis region and view on a map\nFirst, we define our area of interest using latitude and longitude coordinates. Our test region is near Richmond, NSW, Australia. The first line defines the lower-left corner of the bounding box and the second line defines the upper-right corner of the bounding box. GeoJSON format uses a specific order: (longitude, latitude), so be careful when entering the coordinates.", "# Define the bounding box using corners\nmin_lon, min_lat = (150.62, -33.69) # Lower-left corner (longitude, latitude)\nmax_lon, max_lat = (150.83, -33.48) # Upper-right corner (longitude, latitude)\n\nbbox = (min_lon, min_lat, max_lon, max_lat)\nlatitude = (min_lat, max_lat)\nlongitude = (min_lon, max_lon)\n\ndef _degree_to_zoom_level(l1, l2, margin = 0.0):\n \n degree = abs(l1 - l2) * (1 + margin)\n zoom_level_int = 0\n if degree != 0:\n zoom_level_float = math.log(360/degree)/math.log(2)\n zoom_level_int = int(zoom_level_float)\n else:\n zoom_level_int = 18\n return zoom_level_int\n\ndef display_map(latitude = None, longitude = None):\n\n margin = -0.5\n zoom_bias = 0\n lat_zoom_level = _degree_to_zoom_level(margin = margin, *latitude ) + zoom_bias\n lon_zoom_level = _degree_to_zoom_level(margin = margin, *longitude) + zoom_bias\n zoom_level = min(lat_zoom_level, lon_zoom_level) \n center = [np.mean(latitude), np.mean(longitude)]\n \n map_hybrid = folium.Map(location=center,zoom_start=zoom_level, \n tiles=\" http://mt1.google.com/vt/lyrs=y&z={z}&x={x}&y={y}\",attr=\"Google\")\n \n line_segments = [(latitude[0],longitude[0]),(latitude[0],longitude[1]),\n (latitude[1],longitude[1]),(latitude[1],longitude[0]),\n (latitude[0],longitude[0])]\n \n map_hybrid.add_child(folium.features.PolyLine(locations=line_segments,color='red',opacity=0.8))\n map_hybrid.add_child(folium.features.LatLngPopup()) \n\n return map_hybrid\n\n# Plot bounding box on a map\nf = folium.Figure(width=600, height=600)\nm = display_map(latitude,longitude)\nf.add_child(m)", "Discover and load the data for analysis\nUsing <b>pystac</b>, we will load the collection with links to all of the metadata about this dataset. The collection contains assets, which are links to the root of a Zarr store, which can be opened with xarray. Once loaded and opened, we can select the parameters we desire for further analyses. Overall, there are 18 variables for consideration. You can click the \"Data Variables\" output \"arrow\" for a list of those parameters.", "import pystac\ncollection = pystac.read_file(\"https://planetarycomputer.microsoft.com/api/stac/v1/collections/terraclimate\")\nasset = collection.assets[\"zarr-https\"]\n\nimport fsspec\nimport xarray as xr\n\nstore = fsspec.get_mapper(asset.href)\ndata = xr.open_zarr(store, **asset.extra_fields[\"xarray:open_kwargs\"])\n\n# View the dimensions, coordinates and variables of the dataset\n# Click on the \"data variables\" arrow to expand the output and see all of the possible variables\ndata", "Parsing the dataset\nAssuming we do not need all 18 variables and global coverage, we will \"clip\" the data to our region and select a time window that is representative of weather over this area (e.g. 5 years). Finally, we will select the variables we think are most likely to be \"predictor variables\" for frog species habitats. These are:<br> \n<br>maximum air temperature (tmax) - 2 meters above surface\n<br>minimum air temperature (tmin) - 2 meters above surface\n<br>accumulated precipitation (ppt) - accumulated monthly in millimeters\n<br>soil moisture (soil) - soil moisture in millimeters at end of month", "clipped_data = data.sel(lon=slice(min_lon,max_lon),lat=slice(max_lat,min_lat),time=slice('2015-01-01','2019-12-31'))\n\nparsed_data = clipped_data[['tmax', 'tmin', 'ppt', 'soil']]\n\n# View the dimensions: time is in months, lat/lon is in pixels\n# View the coordinates: lat, lon and time\n# View the data variables we have parsed from the overall dataset\nparsed_data", "Data Analysis\nNow we will look closer at some of this data using plotting and statistics.", "fig = plt.figure(figsize=(12, 6))\nparsed_data[\"tmax\"].mean(dim=[\"lat\",\"lon\"]).plot(marker='o',markersize=4,linewidth=1)\nparsed_data[\"tmin\"].mean(dim=[\"lat\",\"lon\"]).plot(marker='o',markersize=4,linewidth=1)\nplt.title(\"Mean Monthly Maximum and Minimum Air Temperature\")\nplt.show()\n\n# Precipitation\nprecip = (parsed_data[\"ppt\"]).mean(dim=[\"lat\",\"lon\"])\nprecip.plot(figsize=(12, 6),marker='o',markersize=4,linewidth=1)\nplt.title(\"Mean Accumulated Precipitation (mm)\")\nplt.show()\n\n# Soil Moisture\nmoisture = (parsed_data[\"soil\"]).mean(dim=[\"lat\",\"lon\"])\nmoisture.plot(figsize=(12, 6),marker='o',markersize=4,linewidth=1)\nplt.title(\"Mean Soil Moisture (mm)\")\nplt.show()", "How will the participants use this data?\nThe GeoTIFF file will contain the Lat-Lon coordinates of each pixel and will also contain the selected parameters for each pixel as separate data layers. Since the FrogID data is also Lat-Lon position, it is possible to find the closest pixel using code similar to what is demonstrated below. Once this pixel is found, then the corresponding parameter data values can be used for modeling species distribution. One example is to use the long-term mean values of a given parameter for a particular location and use that value for species modeling. Below are some sample results for a random Lat-Lon location.", "val_maxtemp = parsed_data.tmax.mean(dim=[\"time\"]).sel(lon=150.71, lat=-33.51, method=\"nearest\").values \nprint(\"This is the mean maximum air temperature for the closest pixel: \", np.round(val_maxtemp,1))\nval_allmaxtemp = parsed_data.tmax.max(dim=[\"time\"]).sel(lon=150.71, lat=-33.51, method=\"nearest\").values \nprint(\"This is the overall maximum air temperature for the closest pixel: \", np.round(val_allmaxtemp,1))\nval_mintemp = parsed_data.tmin.mean(dim=[\"time\"]).sel(lon=150.71, lat=-33.51, method=\"nearest\").values \nprint(\"This is the mean minimum air temperature for the closest pixel: \", np.round(val_mintemp,1))\nval_allmintemp = parsed_data.tmin.min(dim=[\"time\"]).sel(lon=150.71, lat=-33.51, method=\"nearest\").values \nprint(\"This is the overall minimum air temperature for the closest pixel: \", np.round(val_allmintemp,1))\nval_precip = parsed_data.ppt.mean(dim=[\"time\"]).sel(lon=150.71, lat=-33.51, method=\"nearest\").values \nprint(\"This is the mean accumulated precipitation for the closest pixel: \", np.round(val_precip,1))\nval_soil = parsed_data.soil.mean(dim=[\"time\"]).sel(lon=150.71, lat=-33.51, method=\"nearest\").values \nprint(\"This is the mean soil moisture for the closest pixel: \", np.round(val_soil,1))", "Saving the time series data in CSV format\nNow, what if you want to save the time series data for a particular parameter and Lat-Lon location? We can use the example above to specify a Lat-Lon position and then save the time series soil moisture data for that location. Below is the code that will create this CSV file. The file will contain columns for time (month), latitude and longitude (for the nearest pixel) and soil moisture.", "filename = \"Soil_Moisture_sample.csv\"\nparsed_data[\"soil\"].sel(lon=150.71, lat=-33.51, method=\"nearest\").to_dataframe().to_csv(filename)\n\n# Show the location and size of the new output file\n!ls *.csv -lah" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
yingchi/fastai-notes
deeplearning1/nbs/lesson3_fintuning_yc.ipynb
apache-2.0
[ "Modify the Model\nRetrain last layer's linear model\nThe original VGG16 network's last layer is Dense (a linear model), so it is a little odd and wasterful that we are adding an additional linear model on top of it in lesson 2. \nAlso, you may notice that the last layer had a softmax activation, which is an odd choice for an intermediate layer after we add another linear layer to a model.\nSo, we start by removing the last layer, and telling Keras to fix the weights in all the other layers.", "%matplotlib inline\nfrom importlib import reload\nimport utils; reload(utils)\nfrom utils import *\nimport keras\nfrom keras import backend as K\nfrom keras.utils.data_utils import get_file\nfrom keras.models import Sequential\nfrom keras.layers import Input\nfrom keras.layers.core import Flatten, Dense, Dropout, Lambda\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D\nfrom keras.optimizers import SGD, RMSprop\nfrom keras.preprocessing import image\n\nfrom vgg16 import Vgg16\nvgg = Vgg16()\nmodel = vgg.model\n\n# vgg.model.summary()\n\nmodel.pop() # remove the last layer\nfor layer in model.layers:\n layer.trainable = False", "WARNING: Now that we have modified the definition of model, be careful not to rerun any code in the previous sections.", "model.add(Dense(2, activation = 'softmax'))", "Now, compile our updated model, and set up our batches to use the preprocessed images.", "path = \"data/dogscats/\"\n# path = \"data/dogscats/\"\nmodel_path = path + 'models/'\n\ntrn_data = load_array(model_path+'train_data.bc')\nval_data = load_array(model_path+'valid_data.bc')\n\n# Use batch size of 1 since we're just doing preprocessing on the CPU\nval_batches = get_batches(path+'valid', shuffle=False, batch_size=1)\nbatches = get_batches(path+'train', shuffle=False, batch_size=1)\n\nval_classes = val_batches.classes\ntrn_classes = batches.classes\nval_labels = onehot(val_classes)\ntrn_labels = onehot(trn_classes)\n\nbatch_size = 32\ngen = image.ImageDataGenerator()\nbatches = gen.flow(trn_data, trn_labels, batch_size=batch_size, shuffle=True)\nval_batches = gen.flow(val_data, val_labels, batch_size=batch_size, shuffle=False)", "We define a simple function for fitting models, just to save some typing", "def fit_model(model, batches, val_batches, nb_epoch=1):\n model.fit_generator(batches, samples_per_epoch=batches.N, nb_epoch=nb_epoch,\n validation_data=val_batches, nb_val_samples=val_batches.N)", "...and now, we can use it to train the last layer of our model!\nBe warned, it will run quite slowy, because it still has to calculate all the previous layers in order to know what input to pass to the new final layer.\nYou can always precalculate the output of the penultimate layer, like what we did earlier - but since we're only likle to want 1 or 2 iterations, let's just run it.", "opt = RMSprop(lr=0.1)\nmodel.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n\nfit_model(model, batches, val_batches, nb_epoch=2)\n\nmodel.save_weights(model_path+'finetune1.h5')", "How many layers to retrain?\nWell, for dogs vs. cats problems, the classes are similar to the imageNet models output, so no need to retrain more layers. But for state farms, we may consider to retrain more Dense layers. \nHowever, for state farm, there is also no need to retrain the convolution layers, because the spacial relationships in pictures are very likely to be the same. Figuring out whether someone is playing mobile phones is not gonna use different spatial features.", "layers = model.layers\n# Get the index of the first dense layer...\nfirst_dense_idx = [index for index,layer in enumerate(layers) if type(layer) is Dense][0]\n# ...and set this and all subsequent layers to trainable\nfor layer in layers[first_dense_idx:]: layer.trainable=True\n\nK.set_value(opt.lr, 0.01)\nfit_model(model, batches, val_batches, 3)\n\nmodel.save_weights(model_path+'finetune2.h5')\n\nfor layer in layers[12:]: layer.trainable=True\nK.set_value(opt.lr, 0.001)\nfit_model(model, batches, val_batches, 4)\n\nmodel.save_weights(model_path+'finetune3.h5')" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
ueapy/ueapy.github.io
content/notebooks/2017-03-24-climate-model-output.ipynb
mit
[ "name = '2017-03-24-climate-model-output'\ntitle = 'Two ways of preparing climate model output for analysis'\ntags = 'numpy, iris'\nauthor = 'Denis Sergeev'\n\nfrom nb_tools import connect_notebook_to_post\nfrom IPython.core.display import HTML, Image\n\nhtml = connect_notebook_to_post(name, title, tags, author)", "Today one of the group members asked for help with reading climate model output and preparing it for data analysis.\nThis notebook shows a couple of ways of doing that with the help of numpy and iris Python packages.\nLuckily, the model output is quite small and stored in a simple ASCII file. However, it has some properties that can be a hurdle for a programming novice.\nDownload the data from UEA archive\nWe start with downloading data from a given link.", "URL = 'https://raw.githubusercontent.com/ueapy/ueapy.github.io/src/content/data/run1_U_60N_10hPa.dat'", "Instead of copy-pasting the contents manually, we are going to use Python's standard library and download the file, making this part of scientific analysis more reproducible.", "from urllib.request import urlretrieve", "To organise data and code folders, we also import os module.", "import os\n\ndatadir = os.path.join(os.path.pardir, 'data') # directory is one level up\nif not os.path.isdir(datadir):\n # if the directory does not exist, create it\n os.makedirs(datadir)\n\n# File with data\nfname = os.path.join(datadir, 'data.dat')", "Now that we have a directory to store data, we can save the model output there.", "urlretrieve(URL, fname)", "Read the data using numpy\nSince the data are purely numeric, we use numpy module.", "import numpy as np\n\ndata = np.genfromtxt(fname)\n\ndata.shape\n\ndata", "For some reason the data are stored in 6 columns by 1500 rows, which in total is 9000 values.\nWe know a priori that the file contains 75 years of data written every third day, and the climate model's calendar is 360-day calendar. Hence, we have 120 values per year:", "data.shape[0] * data.shape[1] / 75", "Keeping data in $1500\\times6$ array does not seem to be useful, so we make it 1-D:", "data = data.flatten()\ndata.shape", "Wrap it up in a function\nTo make the code above reusable, we create the following function to get data.", "def get_model_data(url=URL, fname='climate_model_data.dat', force_download=False):\n \"\"\"\n Function to download climate model output from UEA server\n \n Parameters\n ---------\n url : string (optional)\n web location of the data\n fname : string (optional)\n full path to save the data\n force_download : bool (optional)\n if True, force redownload of data\n Returns\n -------\n data : numpy.ndarray\n 1-D array of data\n \"\"\"\n if not os.path.exists(fname) or force_download:\n urlretrieve(URL, fname)\n # print('Downloading...')\n data = np.genfromtxt(fname)\n \n return data.flatten()\n\ndata = get_model_data()", "1. Plain NumPy\nReshape the array to YEARS $\\times$ DAYS\nNow we transform the array into a more useful shape.", "NDAYS = 120 # the number of 3-day periods in a 360-day year\nNYEARS = 75 # the total number of years\n\ndata_yd = data.reshape((NYEARS, NDAYS))\nprint(data_yd.shape)", "For example, this is a value of $u$-wind on 30 January of the last year:", "data_yd[-1, 10]", "Select only winter months\nWhat if we want to extract only winter data? We can't use the first winter, because it's incomplete: it only has January and February. So the first winter period will comprise December data from the year 1:", "data_yd[0, -10:]", "plus January and February data from the year 2:", "data_yd[1, :20]", "To join them, we can use numpy.concatentate() function:", "np.concatenate([data_yd[0, -10:], data_yd[1, :20]])", "And of course we can apply the same logic to the whole dataset:", "data_djf = np.concatenate([data_yd[:-1, -10:], data_yd[1:, :20]], axis=1)\nprint(data_djf.shape)", "Selecting years by a certain criterion\n\nHow to find winters when at least 20 days of constant wind direction followed by its change?\n\nHere we are just applying this answer on Stack Overflow to our problem.", "for i, yr in enumerate(data_djf):\n condition = yr > 0\n lens_true = np.diff(np.where(np.concatenate(([condition[0]], condition[:-1] != condition[1:], [True])))[0])[::2]\n if 20 <= lens_true.max() < 30:\n print(i, lens_true.max())", "2. What if you want to use labelled arrays?\nIn the above example numpy's capabilities were probably enough. But when you have more dimensions and data are more complex, it is mostly always better to use labelled arrays and all the great functionality offered by such libraries as xarray or iris.\nWe show how iris library can be used with the same dataset. We chose iris, mostly because it can handle non-standard calendars, like 360-day one.\nTo create an appropriate time coordinate, we will use iris companion package - cf_units.", "import cf_units\nimport iris\n\nDAYS_PER_YEAR = 360\n\nt_unit = cf_units.Unit('days since 0001-01-01 00:00:00',\n calendar='360_day')\n\nt_coord = iris.coords.DimCoord(np.arange(0, DAYS_PER_YEAR * NYEARS, 3),\n units=t_unit,\n standard_name='time')", "Now we can attach the newly created time coordinate to the data themselves by creating an iris cube:", "cube = iris.cube.Cube(data=data,\n units='m/s',\n dim_coords_and_dims=[(t_coord, 0)])\ncube.rename('eastward_wind')\n\nprint(cube)", "Calculate seasonal means\nSource: http://scitools.org.uk/iris/docs/latest/userguide/cube_statistics.html\nSince we now have a labelled aray with appropriate metadata, we can use iris to make statistical analysis easier and make the code more readable.", "import iris.coord_categorisation\n\niris.coord_categorisation.add_season(cube, 'time', name='clim_season')\niris.coord_categorisation.add_season_year(cube, 'time', name='season_year')\n\nprint(cube)\n\ncube.coord('clim_season')\n\nfor season, year in zip(cube.coord('clim_season')[:100:10].points,\n cube.coord('season_year')[:100:10].points):\n print('{} {}'.format(season, year))\n\nannual_seasonal_mean = cube.aggregated_by(['clim_season', 'season_year'],\n iris.analysis.MEAN)\n\nprint(annual_seasonal_mean)\n\nHTML(html)" ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
probml/pyprobml
notebooks/book1/13/bnn_hierarchical_numpyro.ipynb
mit
[ "Hierarchical Bayesian Neural Networks\nIllustration of hierarchial Bayesian neural network classifiers.\nCode and text is based on This blog post by Thomas Wiecki.\nOriginal PyMC3 Notebook. Converted to Numpyro by Aleyna Kara (@karalleyna).\nSetup\nPlease change your colab runtime to CPU.", "# http://num.pyro.ai/en/stable/getting_started.html#installation\n!pip install numpyro[cuda111] -f https://storage.googleapis.com/jax-releases/jax_releases.html\n\nimport argparse\nimport os\nimport time\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom jax import vmap, jit\nimport jax.numpy as jnp\nfrom jax.random import PRNGKey, split, normal\nimport jax.random as random\nimport numpy as np\n\nimport numpyro\nfrom numpyro import handlers\nimport numpyro.distributions as dist\nfrom numpyro.infer import MCMC, NUTS\n\nfrom scipy import stats\nimport seaborn as sns\nfrom warnings import filterwarnings\n\nimport sklearn\nfrom sklearn import datasets\nfrom sklearn.preprocessing import scale\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import make_moons\n\nfrom functools import partial\n\nfilterwarnings(\"ignore\")\nsns.set_style(\"white\")\n\ncmap = sns.diverging_palette(250, 12, s=85, l=25, as_cmap=True)\ncmap_uncertainty = sns.cubehelix_palette(light=1, as_cmap=True)", "Data\nThe data set we are using are our battle tested half-moons as it is simple, non-linear and leads to pretty visualizations. This is what it looks like:", "X, Y = make_moons(noise=0.3, n_samples=1000)\nplt.scatter(X[Y == 0, 0], X[Y == 0, 1], label=\"Class 0\")\nplt.scatter(X[Y == 1, 0], X[Y == 1, 1], color=\"r\", label=\"Class 1\")\nsns.despine()\nplt.legend();", "This is just to illustrate what the data generating distribution looks like, we will use way fewer data points, and create different subsets with different rotations.", "# @title Set the number of groups\n\nn_grps = 18 # @param {type:\"slider\", min:0, max:20, step:1}\n\nn_grps_sq = int(np.sqrt(n_grps))\nn_samples = 100\n\ndef rotate(X, deg):\n theta = np.radians(deg)\n c, s = np.cos(theta), np.sin(theta)\n R = np.matrix([[c, -s], [s, c]])\n\n X = X.dot(R)\n\n return np.asarray(X)\n\nnp.random.seed(31)\n\nXs, Ys = [], []\nfor i in range(n_grps):\n # Generate data with 2 classes that are not linearly separable\n X, Y = make_moons(noise=0.3, n_samples=n_samples)\n X = scale(X)\n\n # Rotate the points randomly for each category\n rotate_by = np.random.randn() * 90.0\n X = rotate(X, rotate_by)\n Xs.append(X)\n Ys.append(Y)\n\nXs = np.stack(Xs)\nYs = np.stack(Ys)\n\nXs_train = Xs[:, : n_samples // 2, :]\nXs_test = Xs[:, n_samples // 2 :, :]\nYs_train = Ys[:, : n_samples // 2]\nYs_test = Ys[:, n_samples // 2 :]\n\nfig, axs = plt.subplots(figsize=(15, 12), nrows=n_grps_sq, ncols=n_grps_sq, sharex=True, sharey=True)\naxs = axs.flatten()\nfor i, (X, Y, ax) in enumerate(zip(Xs_train, Ys_train, axs)):\n ax.scatter(X[Y == 0, 0], X[Y == 0, 1], label=\"Class 0\")\n ax.scatter(X[Y == 1, 0], X[Y == 1, 1], color=\"r\", label=\"Class 1\")\n sns.despine()\n ax.legend()\n ax.set(title=\"Category {}\".format(i + 1), xlabel=\"X1\", ylabel=\"X2\")", "As you can see, we have 4 categories in default that share a higher-order structure (the half-moons). However, in the pure data space, no single classifier will be able to do a good job here. Also, because we only have 50 data points in each class, a NN will likely have a hard time producing robust results. But let's actually test this.\nFit separate MLPs, one per task\nFirst we fit one MLP per task/dataset. For details, see Thomas's blob post \n on Bayesian Deep Learning.", "\"\"\"\nA two-layer bayesian neural network with computational flow\ngiven by D_X => D_H => D_H => D_Y where D_H is the number of\nhidden units.\n\"\"\"\n\n\ndef bnn(X, Y, layer_sizes):\n D_X, D_Y = X.shape[1], 1\n\n z = X\n for i, (D_in, D_out) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):\n w = numpyro.sample(f\"w{i}\", dist.Normal(jnp.zeros((D_in, D_out)), jnp.ones((D_in, D_out)))) # D_X D_H\n z = jnp.tanh(jnp.matmul(z, w)) # N D_H <= first layer of activations\n\n # sample final layer of weights and neural network output\n w_final = numpyro.sample(f\"w_final\", dist.Normal(jnp.zeros((D_out, D_Y)), jnp.ones((D_out, D_Y)))) # D_H D_Y\n z_final = jnp.matmul(z, w_final).squeeze(-1) # N D_Y <= output of the neural network\n\n # Bernoulli likelihood <= Binary classification\n Y = numpyro.sample(\"Y\", dist.Bernoulli(logits=z_final), obs=Y)\n\ndef run_inference(model, rng_key, num_warmup=100, num_samples=100, num_chains=1, **kwargs):\n kernel = NUTS(model)\n mcmc = MCMC(kernel, num_warmup=num_warmup, num_samples=num_samples, num_chains=num_chains, progress_bar=False)\n mcmc.run(rng_key, **kwargs)\n return mcmc\n\ndef get_predictions(\n model, rng_key, samples, X, layer_sizes, num_warmup=100, num_samples=100, num_chains=1, **bnn_kwargs\n):\n # helper function for prediction\n @jit\n def predict(samples, rng_key):\n model_ = handlers.substitute(handlers.seed(model, rng_key), samples)\n # note that Y will be sampled in the model because we pass Y=None here\n model_trace = (\n handlers.trace(model_).get_trace(X=X, Y=None, layer_sizes=layer_sizes, **bnn_kwargs)\n if bnn_kwargs\n else handlers.trace(model_).get_trace(X=X, Y=None, layer_sizes=layer_sizes)\n )\n return model_trace[\"Y\"][\"value\"]\n\n # predict Y at inputs X\n keys = random.split(rng_key, num_samples * num_chains)\n predictions = vmap(predict, in_axes=(0, 0))(samples, keys)\n return predictions\n\ndef get_mean_predictions(predictions, threshold=0.5):\n # compute mean prediction and confidence interval around median\n mean_prediction = jnp.mean(predictions, axis=0)\n return mean_prediction > threshold\n\ndef fit_and_eval(\n model, training_data, test_data, grid, layer_sizes, num_warmup=100, num_samples=100, num_chains=1, **bnn_kwargs\n):\n X_train, Y_train = training_data\n X_test, Y_test = test_data\n\n args = [num_warmup, num_samples, num_chains]\n\n kwargs = {\"X\": X_train, \"Y\": Y_train, \"layer_sizes\": layer_sizes}\n if bnn_kwargs:\n kwargs = {**kwargs, **bnn_kwargs}\n\n # do inference\n rng_key, rng_key_train, rng_key_test, rng_key_grid = random.split(random.PRNGKey(0), 4)\n mcmc = run_inference(model, rng_key, *args, **kwargs)\n samples = mcmc.get_samples()\n\n # predict Y_train and Y_test at inputs X_traind and X_test, respectively\n predictions = get_predictions(model, rng_key_train, samples, X_train, layer_sizes, *args, **bnn_kwargs)\n pred_train = get_mean_predictions(predictions)\n\n predictions = get_predictions(model, rng_key_test, samples, X_test, layer_sizes, *args, **bnn_kwargs)\n pred_test = get_mean_predictions(predictions)\n\n ppc_grid = get_predictions(model, rng_key_grid, samples, grid, layer_sizes, *args, **bnn_kwargs)\n return pred_train, pred_test, ppc_grid, samples\n\nnum_warmup = 1000 # @param {type:\"slider\", min:500, max:2000, step:1}\n\nnum_samples = 500 # @param {type:\"slider\", min:500, max:2000, step:1}\n\nnum_chains = 1\n\ngrid = jnp.mgrid[-3:3:100j, -3:3:100j].reshape((2, -1)).T\n\nhidden_layers = [5, 5]\n\nfit_eval = lambda train, test: fit_and_eval(\n bnn, train, test, grid, (train[0].shape[1], *hidden_layers), num_warmup, num_samples, num_chains\n)\nYs_pred_train, Ys_pred_test, ppc_grid_single, _ = vmap(fit_eval)((Xs_train, Ys_train), (Xs_test, Ys_test))\n\nprint(\"Train accuracy = {:.2f}%\".format(100 * jnp.mean(Ys_pred_train == Ys_train)))\n\nprint(\"Test accuracy = {:.2f}%\".format(100 * jnp.mean(Ys_pred_test == Ys_test)))", "OK, that doesn't seem so bad. Now let's look at the decision surfaces -- i.e. what the classifier thinks about each point in the data space.", "def plot_decision_surfaces_non_hierarchical(nrows=2, ncols=2):\n fig, axes = plt.subplots(figsize=(15, 12), nrows=nrows, ncols=ncols, sharex=True, sharey=True)\n axes = axes.flatten()\n for i, (X, Y_pred, Y_true, ax) in enumerate(zip(Xs_train, Ys_pred_train, Ys_train, axes)):\n contour = ax.contourf(\n grid[:, 0].reshape(100, 100),\n grid[:, 1].reshape(100, 100),\n ppc_grid_single[i, ...].mean(axis=0).reshape(100, 100),\n cmap=cmap,\n )\n ax.scatter(X[Y_true == 0, 0], X[Y_true == 0, 1], label=\"Class 0\")\n ax.scatter(X[Y_true == 1, 0], X[Y_true == 1, 1], color=\"r\", label=\"Class 1\")\n sns.despine()\n ax.legend()\n\nplot_decision_surfaces_non_hierarchical(nrows=n_grps_sq, ncols=n_grps_sq)\n\nplot_decision_surfaces_non_hierarchical()", "That doens't look all that convincing. We know from the data generation process we should get a \"Z\"-shaped decision surface, but we don't have enough data to properly estimate the non-linearity in every category.\nHierarchical Bayesian Neural Network\nIt's actually quite straight-forward to turn this into one big hierarchical model for all categories, rather than many individual ones. Let's call the weight connecting neuron $i$ in layer 1 to neuron $j$ in layer 2 in category $c$ $w_{i, j, c}$ (I just omit the layer index for simplicity in notation). Rather than placing a fixed prior as we did above (i.e. $ w_{i, j, c} \\sim \\mathcal{N}(0, 1^2)$), we will assume that each weight comes from an overarching group distribution:\n$ w_{i, j, c} \\sim \\mathcal{N}(\\mu_{i, j}, \\sigma^2)$. The key is that we will estimate $\\mu_{i, j}$ and $\\sigma$ simultaneously from data. \nWhy not allow for different $\\sigma_{i,j}^2$ per connection you might ask? Mainly just to make our life simpler and because it works well enough.\nNote that we create a very rich model here. Every individual weight has its own hierarchical structure with a single group mean parameter and 16 per-category weights distributed around the group mean. While this creates a big amount of group distributions (as many as the flat NN had weights) there is no problem with this per-se, although it might be a bit unusual. One might argue that this model is quite complex and while that's true, in terms of degrees-of-freedom, this model is simpler than the unpooled one above (more on this below).\nAs for the code, we stack weights along a 3rd dimenson to get separate weights for each group. That way, through the power of broadcasting, the linear algebra works out almost the same as before.", "def hierarchical_bnn(X, Y, layer_sizes):\n D_C, _, D_X = X.shape\n D_Y = 1\n layer_sizes = (D_X, *layer_sizes, D_Y)\n z = X\n\n w_mean, w_std = [], []\n for i, (D_in, D_out) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):\n # Group mean distribution for input to hidden layer\n w_c = numpyro.sample(f\"w{i}_c\", dist.Normal(jnp.zeros((D_in, D_out)), jnp.ones((D_in, D_out))))\n # Group standard-deviation\n w_c_std = numpyro.sample(f\"w{i}_c_std\", dist.HalfNormal(1.0))\n\n w_mean.append(w_c)\n w_std.append(w_c_std)\n\n with numpyro.plate(\"plate_i\", D_C, dim=-3):\n for k, (D_in, D_out, w_c, w_c_std) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:], w_mean, w_std)):\n w_all = numpyro.sample(f\"w{k}_all\", dist.Normal(jnp.zeros((1, D_in, D_out)), jnp.ones((1, D_in, D_out))))\n w = w_all * w_c_std + w_c\n z = (\n jnp.tanh(jnp.matmul(z, w)) if k != len(layer_sizes) - 2 else jnp.matmul(z, w)\n ) # output of the neural network\n\n z = z.squeeze(-1)\n # Bernoulli likelihood <= Binary classification\n Y = numpyro.sample(\"Y\", dist.Bernoulli(logits=z), obs=Y)\n\ngrid_3d = jnp.repeat(grid[None, ...], n_grps, axis=0)\n\nYs_hierarchical_pred_train, Ys_hierarchical_pred_test, ppc_grid, trace_hier = fit_and_eval(\n hierarchical_bnn,\n (Xs_train, Ys_train),\n (Xs_test, Ys_test),\n grid_3d,\n (Xs_train.shape[-1], *hidden_layers),\n num_warmup,\n num_samples,\n num_chains,\n)\n\nprint(\"Train accuracy = {:.2f}%\".format(100 * jnp.mean(Ys_hierarchical_pred_train == Ys_train)))\n\nprint(\"Test accuracy = {:.2f}%\".format(100 * jnp.mean(Ys_hierarchical_pred_test == Ys_test)))", "Great -- we get higher train and test accuracy. Let's look at what the classifier has learned for each category.", "def plot_decision_surfaces_hierarchical(nrows=2, ncols=2):\n fig, axes = plt.subplots(figsize=(15, 12), nrows=nrows, ncols=ncols, sharex=True, sharey=True)\n\n for i, (X, Y_pred, Y_true, ax) in enumerate(zip(Xs_train, Ys_hierarchical_pred_train, Ys_train, axes.flatten())):\n contour = ax.contourf(\n grid[:, 0].reshape((100, 100)),\n grid[:, 1].reshape((100, 100)),\n ppc_grid[:, i, :].mean(axis=0).reshape(100, 100),\n cmap=cmap,\n )\n ax.scatter(X[Y_true == 0, 0], X[Y_true == 0, 1], label=\"Class 0\")\n ax.scatter(X[Y_true == 1, 0], X[Y_true == 1, 1], color=\"r\", label=\"Class 1\")\n sns.despine()\n ax.legend()\n\nplot_decision_surfaces_hierarchical(nrows=n_grps_sq, ncols=n_grps_sq)\n\nplot_decision_surfaces_hierarchical()" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
bhlmn/ds
docs/ml/data/housing.ipynb
mit
[ "The Housing Dataset\nThis dataset contains information about houses in the Boston area collected in 1978. It is small, containing only 506 observations, and contains 14 variables. The dataset can be found here.\nVariables\nDrawing from the University of Toronto's Computer Science department, the 14 variables are:\n\nCRIM - per capita crime rate by town\nZN - proportion of residential land zoned for lots over 25,000 sq.ft.\nINDUS - proportion of non-retail business acres per town.\nCHAS - Charles River dummy variable (1 if tract bounds river; 0 otherwise)\nNOX - nitric oxides concentration (parts per 10 million)\nRM - average number of rooms per dwelling\nAGE - proportion of owner-occupied units built prior to 1940\nDIS - weighted distances to five Boston employment centres\nRAD - index of accessibility to radial highways\nTAX - full-value property-tax rate per 10,000\nPTRATIO - pupil-teacher ratio by town\nB - 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town\nLSTAT - % lower status of the population\nMEDV - Median value of owner-occupied homes in $1000's\n\nThe Toronto CS team notes that \"MEDV seems to be censored at 50.00 (corresponding to a median price of 50,000); Censoring is suggested by the fact that the highest median price of exactly 50,000 is reported in 16 cases, while 15 cases have prices between 40,000 and 50,000, with prices rounded to the nearest hundred. Harrison and Rubinfeld do not mention any censoring.\"\nLoading the Data", "import pandas as pd\ndata_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data'\n# this url has no header info, so column names must be specified\ncolnames = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS',\n 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']\n# load dataset into pandas\ndf = pd.read_csv(data_url, header=None, sep='\\s+', names=colnames)\ndf.head()", "Let's explore some of these variables. It seems like there should definitely be a correlation between several of these variables. For example, I bet as home value increases (MEDV) so will the number of rooms (RM), but the crime rate (CRIM) will decrease. Other relationships might not be so intuitive. \nLet's compare seven of these variables, including the three mentioned, as well as nitric oxide concentration (NOX), the proportion of older (pre-1940s) houses (AGE), accessibility to highways (RAD), and the teacher to student ratio (PTRATIO).", "import matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n# Our seven columns of interest\ncols = ['MEDV', 'RM', 'CRIM', 'NOX', 'AGE', 'RAD', 'PTRATIO']\nsns.set(font_scale=1.5)\nsns.pairplot(df[cols], size = 2.5)", "A lot of information in this plot. However, the trends we supposed earlier appear to be valid. Other interesting trends are that nitric oxide concentration appears to be higher in areas with a larger share of older homes. Looks like all the crime happens where there are older homes and when the teacher/student ration is 1 to 20. Many of these relationships are pretty noisy. Let's check how these variables correlate with a heatmap.", "import numpy as np\ncm = np.corrcoef(df[cols].values.T)\nsns.heatmap(cm, annot=True, square=True, fmt='.2f', annot_kws={'size' : 12}, \n yticklabels=cols, xticklabels=cols)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
phoebe-project/phoebe2-docs
2.3/examples/mesh_wd.ipynb
gpl-3.0
[ "Wilson-Devinney Style Meshing\nNOTE: Wilson-Devinney Style meshing requires developer mode in PHOEBE and is meant to be used for testing, not used for science.\nSetup\nLet's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab).", "#!pip install -I \"phoebe>=2.3,<2.4\"", "As always, let's do imports and initialize a logger and a new bundle.", "import phoebe\nfrom phoebe import u # units\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nphoebe.devel_on() # CURRENTLY REQUIRED FOR WD-STYLE MESHING (WHICH IS EXPERIMENTAL)\n\nlogger = phoebe.logger()\n\nb = phoebe.default_binary()", "Changing Meshing Options\nNext we need to add compute options and change the mesh_style for all stars from 'marching' to 'wd'", "b.set_value_all('mesh_method', 'wd')\nb.set_value_all('eclipse_method', 'graham')", "Adding Datasets\nNext let's add a mesh dataset so that we can plot our Wilson-Devinney style meshes", "b.add_dataset('mesh', compute_times=[0, 0.5], dataset='mesh01', columns=['visibilities'])", "Running Compute", "b.run_compute(irrad_method='none')", "Plotting", "afig, mplfig = b['mesh01@model'].plot(time=0.5, x='us', y='vs',\n show=True)", "Now let's zoom in so we can see the layout of the triangles. Note that Wilson-Devinney uses trapezoids, but since PHOEBE uses triangles, we take each of the trapezoids and split it into two triangles.", "afig, mplfig = b['primary@mesh01@model'].plot(time=0.0, x='us', y='vs',\n ec='blue', fc='gray', \n xlim=(-0.2,0.2), ylim=(-0.2,0.2), \n show=True)", "And now looking down from above. Here you can see the gaps between the surface elements (and you can also see some of the subdivision that's taking place along the limb).", "afig, mplfig = b['primary@mesh01@model'].plot(time=0.0, x='us', y='ws', \n ec='blue', fc='gray', \n xlim=(-0.1,0.1), ylim=(-2.75,-2.55), \n show=True)", "And see which elements are visible at the current time. This defaults to use the 'RdYlGn' colormap which will make visible elements green, partially hidden elements yellow, and hidden elements red. Note that the observer is in the positive w-direction.", "afig, mplfig = b['secondary@mesh01@model'].plot(time=0.0, x='us', y='ws', \n ec='face', fc='visibilities',\n show=True)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
sintefmath/Splipy
doc/Tutorial/Basic manipulation.ipynb
gpl-3.0
[ "Basic Manipulation\nSplipy implements all affine transformations like translate (move), rotate, scale etc. These should be available as operators where this makes sense. To start, we need to import the libraries we are going to use first", "import splipy as sp\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport splipy.curve_factory as curve_factory", "Rotate", "crv = curve_factory.n_gon(6) # create a sample curve\nt0 = crv.start() # parametric starting point \nt1 = crv.end() # parametric end point\nt = np.linspace(t0, t1, 361) # uniform grid of 361 evaluation points on the parametric domain\n\nx = crv(t)\nplt.plot(x[:,0], x[:,1]) # plot curve\n\ncrv.rotate(10.0/360*2*np.pi) # rotate by 10 degrees (input is in radians)\n\nx = crv(t)\nplt.plot(x[:,0], x[:,1], 'r-') # plot curve (in red)\n\nplt.axis('equal')\nplt.show()", "Translate", "crv = curve_factory.n_gon(6) # create a sample curve\nt0 = crv.start() # parametric starting point \nt1 = crv.end() # parametric end point\nt = np.linspace(t0, t1, 361) # uniform grid of 361 evaluation points on the parametric domain\n\nx = crv(t)\nplt.plot(x[:,0], x[:,1]) # plot curve\n\ndx = [0.1, 0.1] # translation amount \ncrv.translate(dx) # move the object by 'dx'\n\nx = crv(t)\nplt.plot(x[:,0], x[:,1], 'r-') # plot curve (in red)\n\nplt.axis('equal')\nplt.show()", "Note that translate can also be applied as an operator", "crv.translate([1, 2]) # moves object 1 in x-direction, 2 in y-direction\ncrv += [1,2] # does the exact same thing\ncrv = crv + [1,2] # same thing\ncrv_2 = crv + [1,2] # creates a new object crv_2 which is the translated version of crv\ncrv += (1,2) # translation vector only needs to be array-like (any indexable input will work)", "Scaling\nNote that scaling is done in relation to the origin. Depending on your use, you might want to center the object around the origin before scaling.", "crv = curve_factory.n_gon(6) # create a sample curve\nt0 = crv.start() # parametric starting point \nt1 = crv.end() # parametric end point\nt = np.linspace(t0, t1, 361) # uniform grid of 361 evaluation points on the parametric domain\n\nx = crv(t)\nplt.plot(x[:,0], x[:,1]) # plot curve\n\ncrv.scale(1.5) # scales the object by a factor of 150%\n\nx = crv(t)\nplt.plot(x[:,0], x[:,1], 'r-') # plot curve (in red)\n\nplt.axis('equal')\nplt.show()", "Scaling is also available as operators", "crv.scale(1.5)\ncrv *= 1.5 # does the exact same thing\ncrv = crv * 1.5 # same thing\ncrv_2 = crv * 1.5 # keeps crv unchanged, returns a new object crv_2 which is the scaled version of crv\ncrv *= (2,1) # doubles the size in x-direction, while leaving the size in y-direction unchanged\n", "Control-point manipulation\nFor special case manipulation, it is possible to manipulate the controlpoints directly", "curve = curve_factory.n_gon(6)\n\n# for a slightly more inefficient translation operations, we may manipulate the controlpoints one-by-one\nfor controlpoint in curve:\n controlpoint += [1,0]\n\n# alternative way of iterating over the controlpoints of a spline object\nfor i in range(len(curve)):\n curve[i] += [1,0]\n\nprint(curve)\n\n\ncurve[0] += [1,0] # this will move the first controlpoint one unit in the x-direction\ncurve[0,0] += 1 # exact same thing (now moved a total of two)\nprint(curve)" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
jve2kor/machine-learning-nanodegree
projects/customer_segments/customer_segments.ipynb
gpl-3.0
[ "Machine Learning Engineer Nanodegree\nUnsupervised Learning\nProject: Creating Customer Segments\nWelcome to the third project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality necessary to successfully complete this project. Sections that begin with 'Implementation' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!\nIn addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide. \n\nNote: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.\n\nGetting Started\nIn this project, you will analyze a dataset containing data on various customers' annual spending amounts (reported in monetary units) of diverse product categories for internal structure. One goal of this project is to best describe the variation in the different types of customers that a wholesale distributor interacts with. Doing so would equip the distributor with insight into how to best structure their delivery service to meet the needs of each customer.\nThe dataset for this project can be found on the UCI Machine Learning Repository. For the purposes of this project, the features 'Channel' and 'Region' will be excluded in the analysis — with focus instead on the six product categories recorded for customers.\nRun the code block below to load the wholesale customers dataset, along with a few of the necessary Python libraries required for this project. You will know the dataset loaded successfully if the size of the dataset is reported.", "# Import libraries necessary for this project\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import display # Allows the use of display() for DataFrames\n\n# Import supplementary visualizations code visuals.py\nimport visuals as vs\n\n# Pretty display for notebooks\n%matplotlib inline\n\n# Load the wholesale customers dataset\ntry:\n data = pd.read_csv(\"customers.csv\")\n data.drop(['Region', 'Channel'], axis = 1, inplace = True)\n print \"Wholesale customers dataset has {} samples with {} features each.\".format(*data.shape)\nexcept:\n print \"Dataset could not be loaded. Is the dataset missing?\"", "Data Exploration\nIn this section, you will begin exploring the data through visualizations and code to understand how each feature is related to the others. You will observe a statistical description of the dataset, consider the relevance of each feature, and select a few sample data points from the dataset which you will track through the course of this project.\nRun the code block below to observe a statistical description of the dataset. Note that the dataset is composed of six important product categories: 'Fresh', 'Milk', 'Grocery', 'Frozen', 'Detergents_Paper', and 'Delicatessen'. Consider what each category represents in terms of products you could purchase.", "# Display a description of the dataset\ndisplay(data.describe())", "Implementation: Selecting Samples\nTo get a better understanding of the customers and how their data will transform through the analysis, it would be best to select a few sample data points and explore them in more detail. In the code block below, add three indices of your choice to the indices list which will represent the customers to track. It is suggested to try different sets of samples until you obtain customers that vary significantly from one another.", "# TODO: Select three indices of your choice you wish to sample from the dataset\nindices = [65, 200, 410]\n\n# Create a DataFrame of the chosen samples\nsamples = pd.DataFrame(data.loc[indices], columns = data.keys()).reset_index(drop = True)\nprint \"Chosen samples of wholesale customers dataset:\"\ndisplay(samples)\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# look at percentile ranks\npcts = 100. * data.rank(axis=0, pct=True).iloc[indices].round(decimals=3)\nprint pcts\n\nsns.heatmap(pcts, annot=True, linewidth=.1, vmax=99, fmt='.1f', cmap='YlOrRd', square=True, cbar=False)\nplt.yticks([2.5,1.5,.5], ['Index '+str(x) for x in indices], rotation='horizontal')\nplt.xticks(rotation=45, ha='center')\nplt.title('Percentile ranks of\\nsamples\\' category spending');", "Question 1\nConsider the total purchase cost of each product category and the statistical description of the dataset above for your sample customers.\nWhat kind of establishment (customer) could each of the three samples you've chosen represent?\nHint: Examples of establishments include places like markets, cafes, and retailers, among many others. Avoid using names for establishments, such as saying \"McDonalds\" when describing a sample customer as a restaurant.\n**Answer:\nSample 0 - As the maximum spending is on the Milk,Grocery,Detergent_paper - this customer represents a coffee and cafe or chain based on the statistics in the dataset.\nSample 1: the amount of diary, grocery and detergents_paper products are above 50% purchased of other customers. In addition, fresh fruits and vegatables are purchased just below 25%, and frozen products are purchased above 75% of all other customes - this customer represents a restaurant\nSample 2 : The third sample above, seems to purchase from every category, but the amount purchased are in the 25%-50% tile range in the distribution with the exception of detergents_paper and delicatessen category.This is a small sandwich shop or even a consumer customer.\nImplementation: Feature Relevance\nOne interesting thought to consider is if one (or more) of the six product categories is actually relevant for understanding customer purchasing. That is to say, is it possible to determine whether customers purchasing some amount of one category of products will necessarily purchase some proportional amount of another category of products? We can make this determination quite easily by training a supervised regression learner on a subset of the data with one feature removed, and then score how well that model can predict the removed feature.\nIn the code block below, you will need to implement the following:\n - Assign new_data a copy of the data by removing a feature of your choice using the DataFrame.drop function.\n - Use sklearn.cross_validation.train_test_split to split the dataset into training and testing sets.\n - Use the removed feature as your target label. Set a test_size of 0.25 and set a random_state.\n - Import a decision tree regressor, set a random_state, and fit the learner to the training data.\n - Report the prediction score of the testing set using the regressor's score function.", "from sklearn.cross_validation import train_test_split\nfrom sklearn.tree import DecisionTreeRegressor\nfor feature in data.keys():\n # TODO: Make a copy of the DataFrame, using the 'drop' function to drop the given feature\n new_data = data.drop([feature], axis = 1)\n\n # TODO: Split the data into training and testing sets using the given feature as the target\n X_train, X_test, y_train, y_test = train_test_split(new_data, data[feature],test_size=0.25, random_state=0)\n\n # TODO: Create a decision tree regressor and fit it to the training set\n regressor = DecisionTreeRegressor(random_state=42)\n regressor.fit(X_train,y_train)\n\n # TODO: Report the score of the prediction using the testing set\n score = regressor.score(X_test,y_test)\n print score,feature", "Question 2\nWhich feature did you attempt to predict? What was the reported prediction score? Is this feature necessary for identifying customers' spending habits?\nHint: The coefficient of determination, R^2, is scored between 0 and 1, with 1 being a perfect fit. A negative R^2 implies the model fails to fit the data.\n**Answer: \nDetergents_Paper seems to be strongly predictable by all of the other categories with a score of 0.66, follow closely by Grocery with a score of 0.60. Since its value can be predicted, their values may not be necessary to identify the customers' spending habits.\nMilk and Frozen have scores of 0.32 and 0.25 respectively. They do not have strong correlations with the other categories, and should be necessary for identifying customers' spending habits.\nVisualize Feature Distributions\nTo get a better understanding of the dataset, we can construct a scatter matrix of each of the six product features present in the data. If you found that the feature you attempted to predict above is relevant for identifying a specific customer, then the scatter matrix below may not show any correlation between that feature and the others. Conversely, if you believe that feature is not relevant for identifying a specific customer, the scatter matrix might show a correlation between that feature and another feature in the data. Run the code block below to produce a scatter matrix.", "# Produce a scatter matrix for each pair of features in the data\npd.plotting.scatter_matrix(data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');", "Question 3\nAre there any pairs of features which exhibit some degree of correlation? Does this confirm or deny your suspicions about the relevance of the feature you attempted to predict? How is the data for those features distributed?\nHint: Is the data normally distributed? Where do most of the data points lie? \n*Answer: yes,(Detergent_Paper,Grocery) and (Detergent_Paper,Milk) they exhibit very high degreee of correlation.\nIt denies my suspicions about the relevance of the feature i used to predict.\nData Distribution:\nAll of the features appears are Skewed right , with the majority data points landing towards the right of the mode , with the exceptions of Detergent_Paper and Grocery category pairs, which has an almost symmetric (normal) distribution across the x and y axis centering on the mode This pair is follow by the Grocery and Milk and Detergent_Paper and Milk category pairs. This confirms our suspicions about the relevence of the Grocery and Detergent_Paper categories being correlated and that Milk and Frozen categories could be used to for identifying customers' spending habits. \nData Preprocessing\nIn this section, you will preprocess the data to create a better representation of customers by performing a scaling on the data and detecting (and optionally removing) outliers. Preprocessing data is often times a critical step in assuring that results you obtain from your analysis are significant and meaningful.\nImplementation: Feature Scaling\nIf data is not normally distributed, especially if the mean and median vary significantly (indicating a large skew), it is most often appropriate to apply a non-linear scaling — particularly for financial data. One way to achieve this scaling is by using a Box-Cox test, which calculates the best power transformation of the data that reduces skewness. A simpler approach which can work in most cases would be applying the natural logarithm.\nIn the code block below, you will need to implement the following:\n - Assign a copy of the data to log_data after applying logarithmic scaling. Use the np.log function for this.\n - Assign a copy of the sample data to log_samples after applying logarithmic scaling. Again, use np.log.", "# TODO: Scale the data using the natural logarithm\nlog_data = data.apply(np.log)\n\n# TODO: Scale the sample data using the natural logarithm\nlog_samples = samples.apply(np.log)\n\n# Produce a scatter matrix for each pair of newly-transformed features\npd.scatter_matrix(log_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');", "Observation\nAfter applying a natural logarithm scaling to the data, the distribution of each feature should appear much more normal. For any pairs of features you may have identified earlier as being correlated, observe here whether that correlation is still present (and whether it is now stronger or weaker than before).\nRun the code below to see how the sample data has changed after having the natural logarithm applied to it.", "# Display the log-transformed sample data\ndisplay(log_samples)", "Implementation: Outlier Detection\nDetecting outliers in the data is extremely important in the data preprocessing step of any analysis. The presence of outliers can often skew results which take into consideration these data points. There are many \"rules of thumb\" for what constitutes an outlier in a dataset. Here, we will use Tukey's Method for identfying outliers: An outlier step is calculated as 1.5 times the interquartile range (IQR). A data point with a feature that is beyond an outlier step outside of the IQR for that feature is considered abnormal.\nIn the code block below, you will need to implement the following:\n - Assign the value of the 25th percentile for the given feature to Q1. Use np.percentile for this.\n - Assign the value of the 75th percentile for the given feature to Q3. Again, use np.percentile.\n - Assign the calculation of an outlier step for the given feature to step.\n - Optionally remove data points from the dataset by adding indices to the outliers list.\nNOTE: If you choose to remove any outliers, ensure that the sample data does not contain any of these points!\nOnce you have performed this implementation, the dataset will be stored in the variable good_data.", "# For each feature find the data points with extreme high or low values\nfeature_outliers = {}\ndef compare_count(index):\n return feature_outliers[index]['count']\nfor feature in log_data.keys():\n \n # TODO: Calculate Q1 (25th percentile of the data) for the given feature\n Q1 = np.percentile(log_data[feature],25)\n \n # TODO: Calculate Q3 (75th percentile of the data) for the given feature\n Q3 = np.percentile(log_data[feature],75)\n \n # TODO: Use the interquartile range to calculate an outlier step (1.5 times the interquartile range)\n step = 1.5 * (Q3 -Q1 )\n \n # Display the outliers\n print \"Data points considered outliers for the feature '{}':\".format(feature)\n display(log_data[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))])\n \n for outlier in log_data[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))].index:\n feature_outlier = feature_outliers.get(str(outlier), {'count':0, 'features':[]});\n feature_outlier['count'] += 1\n feature_outlier['features'].append(feature)\n feature_outliers[str(outlier)] = feature_outlier\n \n# OPTIONAL: Select the indices for data points you wish to remove\n\noutliers = list(feature_outliers.keys())\noutliers.sort(key=compare_count)\nfor outlier in outliers:\n if feature_outliers[str(outlier)]['count'] > 1:\n print \"outlier\", outlier, \"in\", feature_outliers[str(outlier)]['count'], \"features: \", feature_outliers[str(outlier)]['features']\noutliers = np.array(outliers, np.int32)\n\n\n\n# Remove the outliers, if any were specified\ngood_data = log_data.drop(log_data.index[outliers]).reset_index(drop = True)", "Question 4\nAre there any data points considered outliers for more than one feature based on the definition above? Should these data points be removed from the dataset? If any data points were added to the outliers list to be removed, explain why. \nAnswer:\nWith 154 having the most outlying features with Milk, Grocery and Delicatessen. They should be removed from the dataset since they are outside of the expected range and skewing the analysis for our attempt to cluster the data to split the customers into segments. Any data points that are added to the outliers list should be removed from our data points, since we are applying an additional 1.5 basis on the IQR, . Removing the outliers will allow us to more easily cluster the dataset features and hopefully reduce dimensionality using PCA .\nFeature Transformation\nIn this section you will use principal component analysis (PCA) to draw conclusions about the underlying structure of the wholesale customer data. Since using PCA on a dataset calculates the dimensions which best maximize variance, we will find which compound combinations of features best describe customers.\nImplementation: PCA\nNow that the data has been scaled to a more normal distribution and has had any necessary outliers removed, we can now apply PCA to the good_data to discover which dimensions about the data best maximize the variance of features involved. In addition to finding these dimensions, PCA will also report the explained variance ratio of each dimension — how much variance within the data is explained by that dimension alone. Note that a component (dimension) from PCA can be considered a new \"feature\" of the space, however it is a composition of the original features present in the data.\nIn the code block below, you will need to implement the following:\n - Import sklearn.decomposition.PCA and assign the results of fitting PCA in six dimensions with good_data to pca.\n - Apply a PCA transformation of log_samples using pca.transform, and assign the results to pca_samples.", "# TODO: Apply PCA by fitting the good data with the same number of dimensions as features\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=6)\npca.fit(good_data)\n\n# TODO: Transform log_samples using the PCA fit above\npca_samples = pca.transform(log_samples)\n\n# Generate PCA results plot\npca_results = vs.pca_results(good_data, pca)\n\nprint \"The cumulative explained variance is equal to:\"\nprint pca_results['Explained Variance'].cumsum()\nprint \"\"", "Question 5\nHow much variance in the data is explained in total by the first and second principal component? What about the first four principal components? Using the visualization provided above, discuss what the first four dimensions best represent in terms of customer spending.\nHint: A positive increase in a specific dimension corresponds with an increase of the positive-weighted features and a decrease of the negative-weighted features. The rate of increase or decrease is based on the individual feature weights.\nAnswer:\nFirst 2 components1st PC: 49.9% , 2nd PC: 22.6% , Total: 72.5%\nFirst 4 components: 3rd PC: 10.5%,4th PC: 9.8%,Total: 92.8%\nEach component represents different sections of customer spending\nFirst principal component positive weight is placed on Detergents_Paper with meaningful positive weight on Milk and Grocery. This dimension is best categorized by customer spending on retail goods.\nsecond principal component positive weight is placed on fresh with meaningful positive weight on frozen and delicatessen. This dimension is best categorized by customer spending on food.\nThird principal component positive weight is placed on fresh with a significant negative weight on delicatessen. This dimension is best categorized by customer spending on fresh products.\nFourth principal component positive weight is placed on frozen with a significant negative weight on delicatessen. This dimension is best categorized by customer spending on frozen products.\nObservation\nRun the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it in six dimensions. Observe the numerical value for the first four dimensions of the sample points. Consider if this is consistent with your initial interpretation of the sample points.", "# Display sample log-data after having a PCA transformation applied\ndisplay(pd.DataFrame(np.round(pca_samples, 4), columns = pca_results.index.values))", "Implementation: Dimensionality Reduction\nWhen using principal component analysis, one of the main goals is to reduce the dimensionality of the data — in effect, reducing the complexity of the problem. Dimensionality reduction comes at a cost: Fewer dimensions used implies less of the total variance in the data is being explained. Because of this, the cumulative explained variance ratio is extremely important for knowing how many dimensions are necessary for the problem. Additionally, if a signifiant amount of variance is explained by only two or three dimensions, the reduced data can be visualized afterwards.\nIn the code block below, you will need to implement the following:\n - Assign the results of fitting PCA in two dimensions with good_data to pca.\n - Apply a PCA transformation of good_data using pca.transform, and assign the results to reduced_data.\n - Apply a PCA transformation of log_samples using pca.transform, and assign the results to pca_samples.", "# TODO: Apply PCA by fitting the good data with only two dimensions\npca = PCA(n_components=2)\npca.fit(good_data)\n\n# TODO: Transform the good data using the PCA fit above\nreduced_data = pca.transform(good_data)\n\n# TODO: Transform log_samples using the PCA fit above\npca_samples = pca.transform(log_samples)\n\n# Create a DataFrame for the reduced data\nreduced_data = pd.DataFrame(reduced_data, columns = ['Dimension 1', 'Dimension 2'])", "Observation\nRun the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it using only two dimensions. Observe how the values for the first two dimensions remains unchanged when compared to a PCA transformation in six dimensions.", "# Display sample log-data after applying PCA transformation in two dimensions\ndisplay(pd.DataFrame(np.round(pca_samples, 4), columns = ['Dimension 1', 'Dimension 2']))", "Visualizing a Biplot\nA biplot is a scatterplot where each data point is represented by its scores along the principal components. The axes are the principal components (in this case Dimension 1 and Dimension 2). In addition, the biplot shows the projection of the original features along the components. A biplot can help us interpret the reduced dimensions of the data, and discover relationships between the principal components and original features.\nRun the code cell below to produce a biplot of the reduced-dimension data.", "# Create a biplot\nvs.biplot(good_data, reduced_data, pca)", "Observation\nOnce we have the original feature projections (in red), it is easier to interpret the relative position of each data point in the scatterplot. For instance, a point the lower right corner of the figure will likely correspond to a customer that spends a lot on 'Milk', 'Grocery' and 'Detergents_Paper', but not so much on the other product categories. \nFrom the biplot, which of the original features are most strongly correlated with the first component? What about those that are associated with the second component? Do these observations agree with the pca_results plot you obtained earlier?\nClustering\nIn this section, you will choose to use either a K-Means clustering algorithm or a Gaussian Mixture Model clustering algorithm to identify the various customer segments hidden in the data. You will then recover specific data points from the clusters to understand their significance by transforming them back into their original dimension and scale. \nQuestion 6\nWhat are the advantages to using a K-Means clustering algorithm? What are the advantages to using a Gaussian Mixture Model clustering algorithm? Given your observations about the wholesale customer data so far, which of the two algorithms will you use and why?\nAnswer:\n<br>K-Means clustering algorithm Advantages:\n<br>1) Easy, Fast and Robust (Hard Cluster)\n<br>2) Straightforward algorithm for simple data in shape.\n<br>3) Less expensive because doesn't need to calculate \n<br>Gaussian Mixture Model Advantages:\n<br>1) Robust in terms creating distributional assumption -fuzzy / soft clustering \n<br>2) Works good in hyperspace (taken more Bayesian Approach)\n<br>3) Using estimation maximization for fitting the Gaussian distribution within different clusters\n<br>Given the above scatter plot, the data appears to be quite uniform. A lot of data points don't clearly belong to one <br>particular cluster or another, so it seems more logical to adopt a Gaussian Mixture Model in this case.\nImplementation: Creating Clusters\nDepending on the problem, the number of clusters that you expect to be in the data may already be known. When the number of clusters is not known a priori, there is no guarantee that a given number of clusters best segments the data, since it is unclear what structure exists in the data — if any. However, we can quantify the \"goodness\" of a clustering by calculating each data point's silhouette coefficient. The silhouette coefficient for a data point measures how similar it is to its assigned cluster from -1 (dissimilar) to 1 (similar). Calculating the mean silhouette coefficient provides for a simple scoring method of a given clustering.\nIn the code block below, you will need to implement the following:\n - Fit a clustering algorithm to the reduced_data and assign it to clusterer.\n - Predict the cluster for each data point in reduced_data using clusterer.predict and assign them to preds.\n - Find the cluster centers using the algorithm's respective attribute and assign them to centers.\n - Predict the cluster for each sample data point in pca_samples and assign them sample_preds.\n - Import sklearn.metrics.silhouette_score and calculate the silhouette score of reduced_data against preds.\n - Assign the silhouette score to score and print the result.", "from sklearn.mixture import GMM\nfrom sklearn.metrics import silhouette_score\n\ndef produceGMM(k):\n global clusterer, preds, centers, sample_preds\n \n # Apply your clustering algorithm of choice to the reduced data \n clusterer = GMM(n_components=k, random_state=0)\n clusterer.fit(reduced_data)\n\n # Predict the cluster for each data point\n preds = clusterer.predict(reduced_data)\n\n # Find the cluster centers\n centers = clusterer.means_ \n \n # Predict the cluster for each transformed sample data point\n sample_preds = clusterer.predict(pca_samples)\n\n # Calculate the mean silhouette coefficient for the number of clusters chosen\n score = silhouette_score(reduced_data,preds)\n return score\n\nresults = pd.DataFrame(columns=['Silhouette Score'])\nresults.columns.name = 'Number of Clusters' \nfor k in range(2,16):\n score = produceGMM(k) \n results = results.append(pd.DataFrame([score],columns=['Silhouette Score'],index=[k]))\n\ndisplay(results)", "Question 7\nReport the silhouette score for several cluster numbers you tried. Of these, which number of clusters has the best silhouette score? \nAnswer:\n<br>The silhouette scores for several sizes of clusters are displayed above.\n<br>Overall, a Gaussian Mixture Model with 2 clusters has the best silhouette score.\nCluster Visualization\nOnce you've chosen the optimal number of clusters for your clustering algorithm using the scoring metric above, you can now visualize the results by executing the code block below. Note that, for experimentation purposes, you are welcome to adjust the number of clusters for your clustering algorithm to see various visualizations. The final visualization provided should, however, correspond with the optimal number of clusters.", "#using 2 clustures with GMM\nproduceGMM(2)\n# Display the results of the clustering from implementation\n\nvs.cluster_results(reduced_data, preds, centers, pca_samples)", "Implementation: Data Recovery\nEach cluster present in the visualization above has a central point. These centers (or means) are not specifically data points from the data, but rather the averages of all the data points predicted in the respective clusters. For the problem of creating customer segments, a cluster's center point corresponds to the average customer of that segment. Since the data is currently reduced in dimension and scaled by a logarithm, we can recover the representative customer spending from these data points by applying the inverse transformations.\nIn the code block below, you will need to implement the following:\n - Apply the inverse transform to centers using pca.inverse_transform and assign the new centers to log_centers.\n - Apply the inverse function of np.log to log_centers using np.exp and assign the true centers to true_centers.", "# TODO: Inverse transform the centers\nlog_centers = pca.inverse_transform(centers)\n\n# TODO: Exponentiate the centers\ntrue_centers = np.exp(log_centers)\n\n# Display the true centers\nsegments = ['Segment {}'.format(i) for i in range(0,len(centers))]\ntrue_centers = pd.DataFrame(np.round(true_centers), columns = data.keys())\ntrue_centers.index = segments\ndisplay(true_centers)", "Question 8\nConsider the total purchase cost of each product category for the representative data points above, and reference the statistical description of the dataset at the beginning of this project. What set of establishments could each of the customer segments represent?\nHint: A customer who is assigned to 'Cluster X' should best identify with the establishments represented by the feature set of 'Segment X'.", "plt.figure()\nplt.axes().set_title(\"Segment 0\")\nsns.barplot(x=true_centers.columns.values,y=true_centers.iloc[0].values)\n\nplt.figure()\nplt.axes().set_title(\"Segment 1\")\nsns.barplot(x=true_centers.columns.values,y=true_centers.iloc[1].values)", "Answer:\n<br>Segment 0: This most likely represents cafes/restaurants serving fresh food due to the strong weight upon the Fresh category. Whilst the volume falls below the overall population mean, it is consistent with the original prediction for what a Restaurant might look like in the Data Explotation section.\n<br>Segment 1: The quantities of Grocery and Milk are predominant here. The Milk and Grocery values in this cluster exceed the overall means observed in the Data Exploration section, which suggests the are bulk distributors or large resellers such as supermarkets.\nQuestion 9\nFor each sample point, which customer segment from Question 8 best represents it? Are the predictions for each sample point consistent with this?\nRun the code block below to find which cluster each sample point is predicted to be.", "# Display the predictions\nfor i, pred in enumerate(sample_preds):\n print \"Sample point\", i, \"predicted to be in Cluster\", pred", "Answer:\nFor the 3 samples that we picked earlier, sample points 1 , 2 and 3 are placed in customer segment 1, which have high Milk, Grocery and Detergents_Paper feature spending patterns. This is consistant for sample 1 , 2,3 since they also purchase high quantities of Milk, Grocery and Detergents_Paper products .\nConclusion\nIn this final section, you will investigate ways that you can make use of the clustered data. First, you will consider how the different groups of customers, the customer segments, may be affected differently by a specific delivery scheme. Next, you will consider how giving a label to each customer (which segment that customer belongs to) can provide for additional features about the customer data. Finally, you will compare the customer segments to a hidden variable present in the data, to see whether the clustering identified certain relationships.\nQuestion 10\nCompanies will often run A/B tests when making small changes to their products or services to determine whether making that change will affect its customers positively or negatively. The wholesale distributor is considering changing its delivery service from currently 5 days a week to 3 days a week. However, the distributor will only make this change in delivery service for customers that react positively. How can the wholesale distributor use the customer segments to determine which customers, if any, would react positively to the change in delivery service?\nHint: Can we assume the change affects all customers equally? How can we determine which group of customers it affects the most?\nAnswer:\nWe believe running A/B tests are great for testing small changes to see how effective they are before rolling it out of different customer segments because changes like reduced delivery schedule may affect different customer segments differently. In particular, we believe purchasers of perishable goods, such as milk, and grocery products are more likely to require more frequent deliveries, since their storage may only handle a day of food, and since customer segment 0 is the majority purchasers of these products, we would recommend that they be not place on this new delivery schedule. Customer segment 1 purchase these items in less quantity (25-50%), so may have a less sensitive reaction to the new delivery schedule. However, those are just guesses, and an effective A/B testing program will be able to statistically prove if changing the delievery service will make different customer segments react positively or negatively to the change, or none at all. This can be done by randomly selecting a sample set of customers from each customer segment and apply the new delivery services as they are designed. Their feedback on the new services will dictate if the services should be rolled out on other customers of the same segments depending on if the service is successful with the A/B testing group.\nQuestion 11\nAdditional structure is derived from originally unlabeled data when using clustering techniques. Since each customer has a customer segment it best identifies with (depending on the clustering algorithm applied), we can consider 'customer segment' as an engineered feature for the data. Assume the wholesale distributor recently acquired ten new customers and each provided estimates for anticipated annual spending of each product category. Knowing these estimates, the wholesale distributor wants to classify each new customer to a customer segment to determine the most appropriate delivery service.\nHow can the wholesale distributor label the new customers using only their estimated product spending and the customer segment data?\nHint: A supervised learner could be used to train on the original customers. What would be the target variable?\nAnswer:\nWe can use the trained GMM to generate/predict the customer's segment as a basis for the training labels on the supervised learner. This concept is called feature engineering, and will use the output of an unsupervised learning analysis as input to a new supervised learning analysis. Once trained on the existing customer dataset using the new labels, the new supervised learner can be used to predict new customers based on their estimated product spending.\nVisualizing Underlying Distributions\nAt the beginning of this project, it was discussed that the 'Channel' and 'Region' features would be excluded from the dataset so that the customer product categories were emphasized in the analysis. By reintroducing the 'Channel' feature to the dataset, an interesting structure emerges when considering the same PCA dimensionality reduction applied earlier to the original dataset.\nRun the code block below to see how each data point is labeled either 'HoReCa' (Hotel/Restaurant/Cafe) or 'Retail' the reduced space. In addition, you will find the sample points are circled in the plot, which will identify their labeling.", "# Display the clustering results based on 'Channel' data\nvs.channel_results(reduced_data, outliers, pca_samples)", "Question 12\nHow well does the clustering algorithm and number of clusters you've chosen compare to this underlying distribution of Hotel/Restaurant/Cafe customers to Retailer customers? Are there customer segments that would be classified as purely 'Retailers' or 'Hotels/Restaurants/Cafes' by this distribution? Would you consider these classifications as consistent with your previous definition of the customer segments?\nAnswer:\nThe clustering results from the Gaussian Mixture Model algorithm predicted the cluster correctly as 2, but it appears that the distribution of Retailers and Hotels/Restaurants/Cafes are more mixed than GMM predicted. On the whole, the 2 clusters predicted by the GMM maps correctly to the Channel label. Our previous definition of the customer segments does not quite fit with these classification. Our model did not include retailers such as grocery stores that customer segment 0 seems to belong, and segment 1 is now the restaurant, hotel and cafe we previously considered to be segment 0.\n\nNote: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to\nFile -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission." ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
tkurfurst/deep-learning
gan_mnist/Intro_to_GANs_Solution.ipynb
mit
[ "Generative Adversarial Network\nIn this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten digits!\nGANs were first reported on in 2014 from Ian Goodfellow and others in Yoshua Bengio's lab. Since then, GANs have exploded in popularity. Here are a few examples to check out:\n\nPix2Pix \nCycleGAN\nA whole list\n\nThe idea behind GANs is that you have two networks, a generator $G$ and a discriminator $D$, competing against each other. The generator makes fake data to pass to the discriminator. The discriminator also sees real data and predicts if the data it's received is real or fake. The generator is trained to fool the discriminator, it wants to output data that looks as close as possible to real data. And the discriminator is trained to figure out which data is real and which is fake. What ends up happening is that the generator learns to make data that is indistiguishable from real data to the discriminator.\n\nThe general structure of a GAN is shown in the diagram above, using MNIST images as data. The latent sample is a random vector the generator uses to contruct it's fake images. As the generator learns through training, it figures out how to map these random vectors to recognizable images that can foold the discriminator.\nThe output of the discriminator is a sigmoid function, where 0 indicates a fake image and 1 indicates an real image. If you're interested only in generating new images, you can throw out the discriminator after training. Now, let's see how we build this thing in TensorFlow.", "%matplotlib inline\n\nimport pickle as pkl\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIST_data')", "Model Inputs\nFirst we need to create the inputs for our graph. We need two inputs, one for the discriminator and one for the generator. Here we'll call the discriminator input inputs_real and the generator input inputs_z. We'll assign them the appropriate sizes for each of the networks.", "def model_inputs(real_dim, z_dim):\n inputs_real = tf.placeholder(tf.float32, (None, real_dim), name='input_real') \n inputs_z = tf.placeholder(tf.float32, (None, z_dim), name='input_z')\n \n return inputs_real, inputs_z", "Generator network\n\nHere we'll build the generator network. To make this network a universal function approximator, we'll need at least one hidden layer. We should use a leaky ReLU to allow gradients to flow backwards through the layer unimpeded. A leaky ReLU is like a normal ReLU, except that there is a small non-zero output for negative input values.\nVariable Scope\nHere we need to use tf.variable_scope for two reasons. Firstly, we're going to make sure all the variable names start with generator. Similarly, we'll prepend discriminator to the discriminator variables. This will help out later when we're training the separate networks.\nWe could just use tf.name_scope to set the names, but we also want to reuse these networks with different inputs. For the generator, we're going to train it, but also sample from it as we're training and after training. The discriminator will need to share variables between the fake and real input images. So, we can use the reuse keyword for tf.variable_scope to tell TensorFlow to reuse the variables instead of creating new ones if we build the graph again.\nTo use tf.variable_scope, you use a with statement:\npython\nwith tf.variable_scope('scope_name', reuse=False):\n # code here\nHere's more from the TensorFlow documentation to get another look at using tf.variable_scope.\nLeaky ReLU\nTensorFlow doesn't provide an operation for leaky ReLUs, so we'll need to make one . For this you can use take the outputs from a linear fully connected layer and pass them to tf.maximum. Typically, a parameter alpha sets the magnitude of the output for negative values. So, the output for negative input (x) values is alpha*x, and the output for positive x is x:\n$$\nf(x) = max(\\alpha * x, x)\n$$\nTanh Output\nThe generator has been found to perform the best with $tanh$ for the generator output. This means that we'll have to rescale the MNIST images to be between -1 and 1, instead of 0 and 1.", "def generator(z, out_dim, n_units=128, reuse=False, alpha=0.01):\n with tf.variable_scope('generator', reuse=reuse):\n # Hidden layer\n h1 = tf.layers.dense(z, n_units, activation=None)\n # Leaky ReLU\n h1 = tf.maximum(alpha * h1, h1)\n \n # Logits and tanh output\n logits = tf.layers.dense(h1, out_dim, activation=None)\n out = tf.tanh(logits)\n \n return out", "Discriminator\nThe discriminator network is almost exactly the same as the generator network, except that we're using a sigmoid output layer.", "def discriminator(x, n_units=128, reuse=False, alpha=0.01):\n with tf.variable_scope('discriminator', reuse=reuse):\n # Hidden layer\n h1 = tf.layers.dense(x, n_units, activation=None)\n # Leaky ReLU\n h1 = tf.maximum(alpha * h1, h1)\n \n logits = tf.layers.dense(h1, 1, activation=None)\n out = tf.sigmoid(logits)\n \n return out, logits", "Hyperparameters", "# Size of input image to discriminator\ninput_size = 784\n# Size of latent vector to generator\nz_size = 100\n# Sizes of hidden layers in generator and discriminator\ng_hidden_size = 128\nd_hidden_size = 128\n# Leak factor for leaky ReLU\nalpha = 0.01\n# Smoothing \nsmooth = 0.1", "Build network\nNow we're building the network from the functions defined above.\nFirst is to get our inputs, input_real, input_z from model_inputs using the sizes of the input and z.\nThen, we'll create the generator, generator(input_z, input_size). This builds the generator with the appropriate input and output sizes.\nThen the discriminators. We'll build two of them, one for real data and one for fake data. Since we want the weights to be the same for both real and fake data, we need to reuse the variables. For the fake data, we're getting it from the generator as g_model. So the real data discriminator is discriminator(input_real) while the fake discriminator is discriminator(g_model, reuse=True).", "tf.reset_default_graph()\n# Create our input placeholders\ninput_real, input_z = model_inputs(input_size, z_size)\n\n# Build the model\ng_model = generator(input_z, input_size, n_units=g_hidden_size, alpha=alpha)\n# g_model is the generator output\n\nd_model_real, d_logits_real = discriminator(input_real, n_units=d_hidden_size, alpha=alpha)\nd_model_fake, d_logits_fake = discriminator(g_model, reuse=True, n_units=d_hidden_size, alpha=alpha)", "Discriminator and Generator Losses\nNow we need to calculate the losses, which is a little tricky. For the discriminator, the total loss is the sum of the losses for real and fake images, d_loss = d_loss_real + d_loss_fake. The losses will by sigmoid cross-entropys, which we can get with tf.nn.sigmoid_cross_entropy_with_logits. We'll also wrap that in tf.reduce_mean to get the mean for all the images in the batch. So the losses will look something like \npython\ntf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels))\nFor the real image logits, we'll use d_logits_real which we got from the discriminator in the cell above. For the labels, we want them to be all ones, since these are all real images. To help the discriminator generalize better, the labels are reduced a bit from 1.0 to 0.9, for example, using the parameter smooth. This is known as label smoothing, typically used with classifiers to improve performance. In TensorFlow, it looks something like labels = tf.ones_like(tensor) * (1 - smooth)\nThe discriminator loss for the fake data is similar. The logits are d_logits_fake, which we got from passing the generator output to the discriminator. These fake logits are used with labels of all zeros. Remember that we want the discriminator to output 1 for real images and 0 for fake images, so we need to set up the losses to reflect that.\nFinally, the generator losses are using d_logits_fake, the fake image logits. But, now the labels are all ones. The generator is trying to fool the discriminator, so it wants to discriminator to output ones for fake images.", "# Calculate losses\nd_loss_real = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, \n labels=tf.ones_like(d_logits_real) * (1 - smooth)))\nd_loss_fake = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, \n labels=tf.zeros_like(d_logits_real)))\nd_loss = d_loss_real + d_loss_fake\n\ng_loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake,\n labels=tf.ones_like(d_logits_fake)))", "Optimizers\nWe want to update the generator and discriminator variables separately. So we need to get the variables for each part build optimizers for the two parts. To get all the trainable variables, we use tf.trainable_variables(). This creates a list of all the variables we've defined in our graph.\nFor the generator optimizer, we only want to generator variables. Our past selves were nice and used a variable scope to start all of our generator variable names with generator. So, we just need to iterate through the list from tf.trainable_variables() and keep variables to start with generator. Each variable object has an attribute name which holds the name of the variable as a string (var.name == 'weights_0' for instance). \nWe can do something similar with the discriminator. All the variables in the discriminator start with discriminator.\nThen, in the optimizer we pass the variable lists to var_list in the minimize method. This tells the optimizer to only update the listed variables. Something like tf.train.AdamOptimizer().minimize(loss, var_list=var_list) will only train the variables in var_list.", "# Optimizers\nlearning_rate = 0.002\n\n# Get the trainable_variables, split into G and D parts\nt_vars = tf.trainable_variables()\ng_vars = [var for var in t_vars if var.name.startswith('generator')]\nd_vars = [var for var in t_vars if var.name.startswith('discriminator')]\n\nd_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(d_loss, var_list=d_vars)\ng_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(g_loss, var_list=g_vars)", "Training", "batch_size = 100\nepochs = 100\nsamples = []\nlosses = []\n# Only save generator variables\nsaver = tf.train.Saver(var_list=g_vars)\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for e in range(epochs):\n for ii in range(mnist.train.num_examples//batch_size):\n batch = mnist.train.next_batch(batch_size)\n \n # Get images, reshape and rescale to pass to D\n batch_images = batch[0].reshape((batch_size, 784))\n batch_images = batch_images*2 - 1\n \n # Sample random noise for G\n batch_z = np.random.uniform(-1, 1, size=(batch_size, z_size))\n \n # Run optimizers\n _ = sess.run(d_train_opt, feed_dict={input_real: batch_images, input_z: batch_z})\n _ = sess.run(g_train_opt, feed_dict={input_z: batch_z})\n \n # At the end of each epoch, get the losses and print them out\n train_loss_d = sess.run(d_loss, {input_z: batch_z, input_real: batch_images})\n train_loss_g = g_loss.eval({input_z: batch_z})\n \n print(\"Epoch {}/{}...\".format(e+1, epochs),\n \"Discriminator Loss: {:.4f}...\".format(train_loss_d),\n \"Generator Loss: {:.4f}\".format(train_loss_g)) \n # Save losses to view after training\n losses.append((train_loss_d, train_loss_g))\n \n # Sample from generator as we're training for viewing afterwards\n sample_z = np.random.uniform(-1, 1, size=(16, z_size))\n gen_samples = sess.run(\n generator(input_z, input_size, reuse=True),\n feed_dict={input_z: sample_z})\n samples.append(gen_samples)\n saver.save(sess, './checkpoints/generator.ckpt')\n\n# Save training generator samples\nwith open('train_samples.pkl', 'wb') as f:\n pkl.dump(samples, f)", "Training loss\nHere we'll check out the training losses for the generator and discriminator.", "fig, ax = plt.subplots()\nlosses = np.array(losses)\nplt.plot(losses.T[0], label='Discriminator')\nplt.plot(losses.T[1], label='Generator')\nplt.title(\"Training Losses\")\nplt.legend()", "Generator samples from training\nHere we can view samples of images from the generator. First we'll look at images taken while training.", "def view_samples(epoch, samples):\n fig, axes = plt.subplots(figsize=(7,7), nrows=4, ncols=4, sharey=True, sharex=True)\n for ax, img in zip(axes.flatten(), samples[epoch]):\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n im = ax.imshow(img.reshape((28,28)), cmap='Greys_r')\n \n return fig, axes\n\n# Load samples from generator taken while training\nwith open('train_samples.pkl', 'rb') as f:\n samples = pkl.load(f)", "These are samples from the final training epoch. You can see the generator is able to reproduce numbers like 1, 7, 3, 2. Since this is just a sample, it isn't representative of the full range of images this generator can make.", "np.array(samples[-1]).shape\n\n_ = view_samples(-1, samples)", "Below I'm showing the generated images as the network was training, every 10 epochs. With bonus optical illusion!", "rows, cols = 10, 6\nfig, axes = plt.subplots(figsize=(7,12), nrows=rows, ncols=cols, sharex=True, sharey=True)\n\nfor sample, ax_row in zip(samples[::int(len(samples)/rows)], axes):\n for img, ax in zip(sample[::int(len(sample)/cols)], ax_row):\n ax.imshow(img.reshape((28,28)), cmap='Greys_r')\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)", "It starts out as all noise. Then it learns to make only the center white and the rest black. You can start to see some number like structures appear out of the noise like 1s and 9s.\nSampling from the generator\nWe can also get completely new images from the generator by using the checkpoint we saved after training. We just need to pass in a new latent vector $z$ and we'll get new samples!", "saver = tf.train.Saver(var_list=g_vars)\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))\n sample_z = np.random.uniform(-1, 1, size=(16, z_size))\n gen_samples = sess.run(\n generator(input_z, input_size, reuse=True),\n feed_dict={input_z: sample_z})\n_ = view_samples(0, [gen_samples])" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
Kyubyong/numpy_exercises
13_Statistics.ipynb
mit
[ "Statistics", "__author__ = \"kyubyong. kbpark.linguist@gmail.com\"\n\nimport numpy as np\n\nnp.__version__", "Order statistics\nQ1. Return the minimum value of x along the second axis.", "x = np.arange(4).reshape((2, 2))\nprint(\"x=\\n\", x)\n", "Q2. Return the maximum value of x along the second axis. Reduce the second axis to the dimension with size one.", "x = np.arange(4).reshape((2, 2))\nprint(\"x=\\n\", x)\n", "Q3. Calcuate the difference between the maximum and the minimum of x along the second axis.", "x = np.arange(10).reshape((2, 5))\nprint(\"x=\\n\", x)\n\n", "Q4. Compute the 75th percentile of x along the second axis.", "x = np.arange(1, 11).reshape((2, 5))\nprint(\"x=\\n\", x)\n", "Averages and variances\nQ5. Compute the median of flattened x.", "x = np.arange(1, 10).reshape((3, 3))\nprint(\"x=\\n\", x)\n", "Q6. Compute the weighted average of x.", "x = np.arange(5)\nweights = np.arange(1, 6)\n", "Q7. Compute the mean, standard deviation, and variance of x along the second axis.", "x = np.arange(5)\nprint(\"x=\\n\",x)\n\n", "Correlating\nQ8. Compute the covariance matrix of x and y.", "x = np.array([0, 1, 2])\ny = np.array([2, 1, 0])\n", "Q9. In the above covariance matrix, what does the -1 mean?\nQ10. Compute Pearson product-moment correlation coefficients of x and y.", "x = np.array([0, 1, 3])\ny = np.array([2, 4, 5])\n", "Q11. Compute cross-correlation of x and y.", "x = np.array([0, 1, 3])\ny = np.array([2, 4, 5])\n\n", "Histograms\nQ12. Compute the histogram of x against the bins.", "x = np.array([0.5, 0.7, 1.0, 1.2, 1.3, 2.1])\nbins = np.array([0, 1, 2, 3])\nprint(\"ans=\\n\", ...)\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\nplt.hist(x, bins=bins)\nplt.show()", "Q13. Compute the 2d histogram of x and y.", "xedges = [0, 1, 2, 3]\nyedges = [0, 1, 2, 3, 4]\nx = np.array([0, 0.1, 0.2, 1., 1.1, 2., 2.1])\ny = np.array([0, 0.1, 0.2, 1., 1.1, 2., 3.3])\n...\n\nplt.scatter(x, y)\nplt.grid()", "Q14. Count number of occurrences of 0 through 7 in x.", "x = np.array([0, 1, 1, 3, 2, 1, 7])\n", "Q15. Return the indices of the bins to which each value in x belongs.", "x = np.array([0.2, 6.4, 3.0, 1.6])\nbins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])\n\n" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
enakai00/jupyter_NikkeiLinux
No5/Figure8 - integral animation.ipynb
apache-2.0
[ "[3-1] 動画作成用のモジュールをインポートして、動画を表示可能なモードにセットします。", "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n%matplotlib nbagg", "[3-2] x=0〜1の範囲で棒グラフを描いて面積を計算する関数integralを定義します。", "def integral(f, filename):\n fig = plt.figure(figsize=(4,4))\n images = []\n step = 0.5\n \n for _ in range(10):\n subplot = fig.add_subplot(1,1,1)\n subplot.set_xlim(0, 1)\n subplot.set_ylim(0, 1)\n linex = np.linspace(0, 1, 100)\n subimages = []\n\n im, = subplot.plot(linex, f(linex), color='blue')\n subimages.append(im)\n\n area = 0\n for x0 in np.arange(0, 1, step):\n rect = plt.Rectangle((x0,0), step, f(x0), alpha=0.5)\n im = subplot.add_patch(rect)\n subimages.append(im)\n area += step * f(x0)\n im = subplot.text(0.3, 1.05, ('area = %f' % area))\n subimages.append(im)\n images.append(subimages)\n step *= 0.5\n\n ani = animation.ArtistAnimation(fig, images, interval=1000)\n ani.save(filename, writer='imagemagick', fps=1)\n return ani", "[3-3] 二次関数 y=x*x を用意して、関数integralを呼び出します。\nGIF動画ファイル「integral01.gif」が作成されます。", "def f(x):\n y = x*x\n return y\n\nintegral(f, 'integral01.gif')", "[3-4] 円弧を表す関数を用意して、関数integralを呼び出します。\nGIF動画ファイル「integral02.gif」が作成されます。", "def f(x):\n y = np.sqrt(1.0-x*x)\n return y\n\nintegral(f, 'integral02.gif')" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
elizabetht/deep-learning
gan_mnist/Intro_to_GANs_Solution.ipynb
mit
[ "Generative Adversarial Network\nIn this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten digits!\nGANs were first reported on in 2014 from Ian Goodfellow and others in Yoshua Bengio's lab. Since then, GANs have exploded in popularity. Here are a few examples to check out:\n\nPix2Pix \nCycleGAN\nA whole list\n\nThe idea behind GANs is that you have two networks, a generator $G$ and a discriminator $D$, competing against each other. The generator makes fake data to pass to the discriminator. The discriminator also sees real data and predicts if the data it's received is real or fake. The generator is trained to fool the discriminator, it wants to output data that looks as close as possible to real data. And the discriminator is trained to figure out which data is real and which is fake. What ends up happening is that the generator learns to make data that is indistiguishable from real data to the discriminator.\n\nThe general structure of a GAN is shown in the diagram above, using MNIST images as data. The latent sample is a random vector the generator uses to contruct it's fake images. As the generator learns through training, it figures out how to map these random vectors to recognizable images that can foold the discriminator.\nThe output of the discriminator is a sigmoid function, where 0 indicates a fake image and 1 indicates an real image. If you're interested only in generating new images, you can throw out the discriminator after training. Now, let's see how we build this thing in TensorFlow.", "%matplotlib inline\n\nimport pickle as pkl\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIST_data')", "Model Inputs\nFirst we need to create the inputs for our graph. We need two inputs, one for the discriminator and one for the generator. Here we'll call the discriminator input inputs_real and the generator input inputs_z. We'll assign them the appropriate sizes for each of the networks.", "def model_inputs(real_dim, z_dim):\n inputs_real = tf.placeholder(tf.float32, (None, real_dim), name='input_real') \n inputs_z = tf.placeholder(tf.float32, (None, z_dim), name='input_z')\n \n return inputs_real, inputs_z", "Generator network\n\nHere we'll build the generator network. To make this network a universal function approximator, we'll need at least one hidden layer. We should use a leaky ReLU to allow gradients to flow backwards through the layer unimpeded. A leaky ReLU is like a normal ReLU, except that there is a small non-zero output for negative input values.\nVariable Scope\nHere we need to use tf.variable_scope for two reasons. Firstly, we're going to make sure all the variable names start with generator. Similarly, we'll prepend discriminator to the discriminator variables. This will help out later when we're training the separate networks.\nWe could just use tf.name_scope to set the names, but we also want to reuse these networks with different inputs. For the generator, we're going to train it, but also sample from it as we're training and after training. The discriminator will need to share variables between the fake and real input images. So, we can use the reuse keyword for tf.variable_scope to tell TensorFlow to reuse the variables instead of creating new ones if we build the graph again.\nTo use tf.variable_scope, you use a with statement:\npython\nwith tf.variable_scope('scope_name', reuse=False):\n # code here\nHere's more from the TensorFlow documentation to get another look at using tf.variable_scope.\nLeaky ReLU\nTensorFlow doesn't provide an operation for leaky ReLUs, so we'll need to make one . For this you can use take the outputs from a linear fully connected layer and pass them to tf.maximum. Typically, a parameter alpha sets the magnitude of the output for negative values. So, the output for negative input (x) values is alpha*x, and the output for positive x is x:\n$$\nf(x) = max(\\alpha * x, x)\n$$\nTanh Output\nThe generator has been found to perform the best with $tanh$ for the generator output. This means that we'll have to rescale the MNIST images to be between -1 and 1, instead of 0 and 1.", "def generator(z, out_dim, n_units=128, reuse=False, alpha=0.01):\n with tf.variable_scope('generator', reuse=reuse):\n # Hidden layer\n h1 = tf.layers.dense(z, n_units, activation=None)\n # Leaky ReLU\n h1 = tf.maximum(alpha * h1, h1)\n \n # Logits and tanh output\n logits = tf.layers.dense(h1, out_dim, activation=None)\n out = tf.tanh(logits)\n \n return out", "Discriminator\nThe discriminator network is almost exactly the same as the generator network, except that we're using a sigmoid output layer.", "def discriminator(x, n_units=128, reuse=False, alpha=0.01):\n with tf.variable_scope('discriminator', reuse=reuse):\n # Hidden layer\n h1 = tf.layers.dense(x, n_units, activation=None)\n # Leaky ReLU\n h1 = tf.maximum(alpha * h1, h1)\n \n logits = tf.layers.dense(h1, 1, activation=None)\n out = tf.sigmoid(logits)\n \n return out, logits", "Hyperparameters", "# Size of input image to discriminator\ninput_size = 784\n# Size of latent vector to generator\nz_size = 100\n# Sizes of hidden layers in generator and discriminator\ng_hidden_size = 128\nd_hidden_size = 128\n# Leak factor for leaky ReLU\nalpha = 0.01\n# Smoothing \nsmooth = 0.1", "Build network\nNow we're building the network from the functions defined above.\nFirst is to get our inputs, input_real, input_z from model_inputs using the sizes of the input and z.\nThen, we'll create the generator, generator(input_z, input_size). This builds the generator with the appropriate input and output sizes.\nThen the discriminators. We'll build two of them, one for real data and one for fake data. Since we want the weights to be the same for both real and fake data, we need to reuse the variables. For the fake data, we're getting it from the generator as g_model. So the real data discriminator is discriminator(input_real) while the fake discriminator is discriminator(g_model, reuse=True).", "tf.reset_default_graph()\n# Create our input placeholders\ninput_real, input_z = model_inputs(input_size, z_size)\n\n# Build the model\ng_model = generator(input_z, input_size)\n# g_model is the generator output\n\nd_model_real, d_logits_real = discriminator(input_real)\nd_model_fake, d_logits_fake = discriminator(g_model, reuse=True)", "Discriminator and Generator Losses\nNow we need to calculate the losses, which is a little tricky. For the discriminator, the total loss is the sum of the losses for real and fake images, d_loss = d_loss_real + d_loss_fake. The losses will by sigmoid cross-entropys, which we can get with tf.nn.sigmoid_cross_entropy_with_logits. We'll also wrap that in tf.reduce_mean to get the mean for all the images in the batch. So the losses will look something like \npython\ntf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels))\nFor the real image logits, we'll use d_logits_real which we got from the discriminator in the cell above. For the labels, we want them to be all ones, since these are all real images. To help the discriminator generalize better, the labels are reduced a bit from 1.0 to 0.9, for example, using the parameter smooth. This is known as label smoothing, typically used with classifiers to improve performance. In TensorFlow, it looks something like labels = tf.ones_like(tensor) * (1 - smooth)\nThe discriminator loss for the fake data is similar. The logits are d_logits_fake, which we got from passing the generator output to the discriminator. These fake logits are used with labels of all zeros. Remember that we want the discriminator to output 1 for real images and 0 for fake images, so we need to set up the losses to reflect that.\nFinally, the generator losses are using d_logits_fake, the fake image logits. But, now the labels are all ones. The generator is trying to fool the discriminator, so it wants to discriminator to output ones for fake images.", "# Calculate losses\nd_loss_real = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, \n labels=tf.ones_like(d_logits_real) * (1 - smooth)))\nd_loss_fake = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, \n labels=tf.zeros_like(d_logits_real)))\nd_loss = d_loss_real + d_loss_fake\n\ng_loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake,\n labels=tf.ones_like(d_logits_fake)))", "Optimizers\nWe want to update the generator and discriminator variables separately. So we need to get the variables for each part build optimizers for the two parts. To get all the trainable variables, we use tf.trainable_variables(). This creates a list of all the variables we've defined in our graph.\nFor the generator optimizer, we only want to generator variables. Our past selves were nice and used a variable scope to start all of our generator variable names with generator. So, we just need to iterate through the list from tf.trainable_variables() and keep variables to start with generator. Each variable object has an attribute name which holds the name of the variable as a string (var.name == 'weights_0' for instance). \nWe can do something similar with the discriminator. All the variables in the discriminator start with discriminator.\nThen, in the optimizer we pass the variable lists to var_list in the minimize method. This tells the optimizer to only update the listed variables. Something like tf.train.AdamOptimizer().minimize(loss, var_list=var_list) will only train the variables in var_list.", "# Optimizers\nlearning_rate = 0.002\n\n# Get the trainable_variables, split into G and D parts\nt_vars = tf.trainable_variables()\ng_vars = [var for var in t_vars if var.name.startswith('generator')]\nd_vars = [var for var in t_vars if var.name.startswith('discriminator')]\n\nd_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(d_loss, var_list=d_vars)\ng_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(g_loss, var_list=g_vars)", "Training", "!mkdir checkpoints\n\nbatch_size = 100\nepochs = 100\nsamples = []\nlosses = []\n# Only save generator variables\nsaver = tf.train.Saver(var_list=g_vars)\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for e in range(epochs):\n for ii in range(mnist.train.num_examples//batch_size):\n batch = mnist.train.next_batch(batch_size)\n \n # Get images, reshape and rescale to pass to D\n batch_images = batch[0].reshape((batch_size, 784))\n batch_images = batch_images*2 - 1\n \n # Sample random noise for G\n batch_z = np.random.uniform(-1, 1, size=(batch_size, z_size))\n \n # Run optimizers\n _ = sess.run(d_train_opt, feed_dict={input_real: batch_images, input_z: batch_z})\n _ = sess.run(g_train_opt, feed_dict={input_z: batch_z})\n \n # At the end of each epoch, get the losses and print them out\n train_loss_d = sess.run(d_loss, {input_z: batch_z, input_real: batch_images})\n train_loss_g = g_loss.eval({input_z: batch_z})\n \n print(\"Epoch {}/{}...\".format(e+1, epochs),\n \"Discriminator Loss: {:.4f}...\".format(train_loss_d),\n \"Generator Loss: {:.4f}\".format(train_loss_g)) \n # Save losses to view after training\n losses.append((train_loss_d, train_loss_g))\n \n # Sample from generator as we're training for viewing afterwards\n sample_z = np.random.uniform(-1, 1, size=(16, z_size))\n gen_samples = sess.run(\n generator(input_z, input_size, reuse=True),\n feed_dict={input_z: sample_z})\n samples.append(gen_samples)\n saver.save(sess, './checkpoints/generator.ckpt')\n\n# Save training generator samples\nwith open('train_samples.pkl', 'wb') as f:\n pkl.dump(samples, f)", "Training loss\nHere we'll check out the training losses for the generator and discriminator.", "fig, ax = plt.subplots()\nlosses = np.array(losses)\nplt.plot(losses.T[0], label='Discriminator')\nplt.plot(losses.T[1], label='Generator')\nplt.title(\"Training Losses\")\nplt.legend()", "Generator samples from training\nHere we can view samples of images from the generator. First we'll look at images taken while training.", "def view_samples(epoch, samples):\n fig, axes = plt.subplots(figsize=(7,7), nrows=4, ncols=4, sharey=True, sharex=True)\n for ax, img in zip(axes.flatten(), samples[epoch]):\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n im = ax.imshow(img.reshape((28,28)), cmap='Greys_r')\n \n return fig, axes\n\n# Load samples from generator taken while training\nwith open('train_samples.pkl', 'rb') as f:\n samples = pkl.load(f)", "These are samples from the final training epoch. You can see the generator is able to reproduce numbers like 1, 7, 3, 2. Since this is just a sample, it isn't representative of the full range of images this generator can make.", "_ = view_samples(-1, samples)", "Below I'm showing the generated images as the network was training, every 10 epochs. With bonus optical illusion!", "rows, cols = 10, 6\nfig, axes = plt.subplots(figsize=(7,12), nrows=rows, ncols=cols, sharex=True, sharey=True)\n\nfor sample, ax_row in zip(samples[::int(len(samples)/rows)], axes):\n for img, ax in zip(sample[::int(len(sample)/cols)], ax_row):\n ax.imshow(img.reshape((28,28)), cmap='Greys_r')\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)", "It starts out as all noise. Then it learns to make only the center white and the rest black. You can start to see some number like structures appear out of the noise like 1s and 9s.\nSampling from the generator\nWe can also get completely new images from the generator by using the checkpoint we saved after training. We just need to pass in a new latent vector $z$ and we'll get new samples!", "saver = tf.train.Saver(var_list=g_vars)\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))\n sample_z = np.random.uniform(-1, 1, size=(16, z_size))\n gen_samples = sess.run(\n generator(input_z, input_size, reuse=True),\n feed_dict={input_z: sample_z})\n_ = view_samples(0, [gen_samples])" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
bmeaut/python_nlp_2017_fall
course_material/01_Introduction/01_Python_introduction_lab.ipynb
mit
[ "Laboratory 01\nYou are expected to complete all basic exercises.\nAdvanced exercises are prefixed with *.\nYou are free to use any material (lecture, Stackoverflow etc.) except full solutions.\n1. range() practice\n1.1 Print the numbers between 70 and 79 inclusive.\n1.2 Print the first 10 square numbers starting from 1.\n*1.3 Print the numbers from 19 to 10 (backwards).\n2. Reading user input\nUser input can be read with the input() function. It always returns a string which can be converted to integer using the int() function.", "n = input()\nn = int(n)", "2.1 Read a number N and print the numbers from 1 to N.\n2.2 Read a number N and print the first N square numbers starting from 1.\n2.3 Read numbers until 0 and print their sum.\n*2.4 Read numbers until 0 and print their mean and standard deviation without using a list.\n3. Lists\n3.1 Print the odd numbers from this list.", "l = [2, 3, -2, -7, 0, 2, 3]", "3.2 Read numbers until 0 and collect them in a list. Print the elements backwards (zero not included).\nFor example:\ninput: 3 4 2 12 3 0\noutput: 3 12 3 4 3\n3.3 Read a number N and then read exactly N numbers. Print them backwards.\nFor example:\ninput: 4 -1 0 2 12\noutput: 12 2 0 -1\n4. Functions\nThe following exercises contain function skeletons. Finish these functions.\nIf you work correctly, the assert statements should not fail.\n4.1 Write a function that takes an integer parameter (N) and returns a list of the first N prime numbers starting from 2.", "def get_n_primes(N):\n # TODO\n\nassert(get_n_primes(3) == [2, 3, 5])", "4.2 Write a function that takes an integer parameter (N) and returns the Nth Fibonacci number.\nThe Fibonacci series starts as 1, 1, 2, 3, 5, 8, so the 2nd number is 1.", "def get_nth_fibonacci(N):\n # TODO\n\nassert(get_nth_fibonacci(3) == 2)", "4.3 Write a function that takes an integer parameter (N) and returns a list of the first N Fibonacci numbers.\nYou are encouraged to reuse previous functions.", "def get_n_fibonacci(N):\n # TODO\n \nassert(get_n_fibonacci(4) == [1, 1, 2, 3])", "*4.4 Write a function that takes two integers, A and B and returns B-A Fibonacci numbers starting from the Ath Fibonacci number to the (B-1)th number. See the example below.", "def get_range_fibonacci(A, B):\n # TODO\n\nassert(get_range_fibonacci(2, 5) == [1, 2, 3])", "5. Default and keyword arguments\n5.1 Write a function that computes the sum of a list with an optional starting value. If no starting value is provided, it should sum from 0.", "# TODO def sum_list...\n\nassert(sum_list([1, 2, 3]) == 6)\nassert(sum_list([1, 2, 3], 5) == 11)", "5.2 Write a function that takes two numbers and an arithmetic operator as a string (\"+\", \"-\", \"*\" or \"/\") and returns the result of the arithmetic operation on the two numbers. The default operation should be addition.", "# TODO def arithmetic...\n\nassert(arithmetic(2, 3) == 5)\nassert(arithmetic(2, 3, \"-\") == -1)\nassert(arithmetic(2, 3, \"*\") == 6)\nassert(arithmetic(2, 3, \"/\") == 2/3)", "*5.3 Write a function that takes three parameters. The third is a callable (function) that takes two parameters. The function should call its third parameter with the first two as parameters. If the third parameter is not specified the function should add the two arguments.\nThis is very similar to the previous function but the third parameter is a function instead of a string.", "# TODO def call_func(...)\n\ndef product(x, y):\n return x * y\n\nassert(call_func(3, 4, product) == 12)\nassert(call_func(\"foo\", \"bar\") == \"foobar\")", "6. Extra exercises\n*6.1 Create a function that take a list and a predicate (function with boolean return value) as parameters and returns a new list of those elements which the predicate return True.\nA predicate is a function that takes one element and return True or False, for example is_even, is_prime.\nIf you implemented The following tests should run.", "def filter_list(input_list, predicate):\n # TODO\n return output_list\n\ndef is_prime(n):\n # TODO\n pass\n\ndef is_odd(n):\n return n % 2 == 1\n\nl1 = [1, 2, 3, 4, 19, 35, 11]\n\nassert(filter_list(l1, is_odd) == [1, 3, 19, 35, 11])\nassert(filter_list(l1, is_prime) == [2, 3, 19, 11])", "*6.2 Reduce is a function that applies a two argument function against an accumulator and each element in the sequence (from left to right) to reduce it to a single value. If no initial value is provided, the accumulator is initialized with the return value of the function run on the first two elements of the sequence.\nreduce([1, 2, 3], product) ---&gt; 6\nreduce([1, 2, 3], product, accumulator=10) ---&gt; 60\nreduce([\"foo\", \"bar\"], string_addition) ---&gt; \"foobar\"\nreduce([\"foo\", \"bar\"], string_addition, accumulator=\"hello\") ---&gt; \"hellofoobar\"", "def reduce(l, acc_func, accumulator=None):\n # TODO\n \ndef add(x, y):\n return x + y\n\nl1 = [1, 2, -1, 5]\n\nassert(reduce(l1, add) == 7)\nassert(reduce(l1, add, 10) == 17)\n\ndef string_len_add(acc, s):\n return acc + len(s)\n\nl2 = [\"foo\", \"bar\", \"hello\"]\n\nassert(reduce(l2, string_len_add, 0) == 11)", "*6.3 Use your reduce function for the following operations:\n\ncount the number of odd elements in a list of integers,\nfind the maximum of a list of integers,\nfind the longest string in list of strings.\n\nTest your solutions.\n*6.4 Implement qsort. Qsort sorts a list in place using the quicksort algorithm.", "def qsort(l):\n # TODO\n \nl = [10, -1, 2, 11, 0]\n\nqsort(l)\n\nassert(l == [-1, 0, 2, 10, 11])", "*6.5 Implement bubble sort (in place).", "def bubblesort(l):\n # TODO\n \nl = [10, -1, 2, 11, 0]\n\nbubblesort(l)\n\nassert(l == [-1, 0, 2, 10, 11])" ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]